Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 730
Kirsten Avatar asked Dec 08 '22 14:12

Kirsten


1 Answers

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.

like image 141
Mr_Green Avatar answered May 22 '23 22:05

Mr_Green