POSTMAN: Get access token and set to variable

Most of the testing in API requires authentication and we need to pass it in every request we make.
Similarly there can be any other dynamic authorization/authentication mechanism which needs to be passed along with header or as parameter.
What becomes problem is every time we generate access token from one endpoint (EX: token endpoint) and copy the token and paste in another request as header or body parameter.
There is a simpler way to handle this by transferring the token from one request to another request via a variable.

POSTMAN supports javascript based Test scripts where we can write code snippet to do the above.

Use case:
1- Call token endpoint using some valid credentials
2- Get the token from response and store in a variable
3- Use the token variable in another request

pm.test("Fetch Token and Set", function () {
    var jsonData = pm.response.json();
    pm.globals.set("token_global", jsonData.access_token);

The above code can be added in Test tab of POSTMAN.
It will store the response in a variable.
Then it will extract the value from the key access_token from response and set in the variable token_global
* Please note that you need to create a global variable named token_global.

Token Endpoint
Token from above is used in this request

Notice that the token generated in step 1 is used in step 2.
Highlighted the token to show the token value are same.

Leave a Reply