How to update environment variables based on a response in Postman

0
401

Sometimes, the response from a request is required first in order to continue with all the other API requests currently stored in your Postman folders. Think of a request that, in order to return results, it requires from you to be authenticated, so a typical workflow would be:

  1. authenticate yourself with a proper username and password;
  2. get an authentication token;
  3. update your other requests to use this new token.

To avoid updating manually all your request headers with the new auth token, you can use environments and variables in Postman.

Setting up Environments and Variables

Environments is a set of key-value pairs that allows you to customize requests using variables. Variables can be used in the following form – {{variableName}} and, whenever the {{variableName}} appears, it will be replaced by its corresponding value.

For example, in the screenshot above we have created a “Dev locally” environment where the variable WebAppUrl will be replaced by localhost:4000 whenever found, and when the AuthToken variable is found by N/A.

So, if you need to be authorized to access some resources, firstly you need to call localhost:4000/oauth/token to get an authentication token and then use this token to your other request, let’s say localhost:4000/api/categories.

To avoid copying and pasting the access_token returned from the first request to update the variable AuthToken to be used in the second request, you can use test scripts to make your life easier.

Test Scripts

The test script runs inside a sandbox and Postman provides the postman object to interact with the main Postman context. In addition, you can extract data from responses and chain requests using test scripts.

In our case, click on Tests tab and parse the response body from auth request:
var data = JSON.parse(responseBody);
then, you can update the environment variable AuthToken through the following command:
postman.setEnvironmentVariable("AuthToken", data.access_token);
Now all other calls will use the new updated AuthToken without the need to manually update the environment variable.

Reference Link – https://blog.postman.com/extracting-data-from-responses-and-chaining-requests/

LEAVE A REPLY

Please enter your comment!
Please enter your name here