How do i set up a bearer token in postman from an environment variable?

Kirsten Greed picture Kirsten Greed · Jun 17, 2018 · Viewed 7k times · Source

I have set up a collection in PostMan and am able to save my bearer token value to an environment variable successfully using the following test

var jsonData = JSON.parse(responseBody);
pm.environment.set("mytoken", jsonData.token);

but how do I set up a new call to use it?

I have tried adding a Header with

Authorization Bearer <mytoken>

but when I Post the Status is 401 Unauthorized

Answer

Mr_Green picture Mr_Green · Jan 21, 2020

You can use Tests tab to write your code which updates the Environment variable, as explained in this link. Read more about Test scripts here.

enter image description here

Assuming the response of the auth call is:

{
    "token": "woaejrlajfaoidhfalskdjfalsdijfasd"
}

Then, in Tests tab, you can write like:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.token);

This will update the variable token whenever you trigger the auth call. This token variable should be used in headers of all the API calls, to update automatically.

Do also check inheriting the auth.