When sending a request with Postman, we can parse a value from the response and save it into a global variable or environment variable. This is useful when we need to use a value obtained from one request in other requests; for example, when we obtain an access token that needs to be included as the authorization header in other requests.
To keep the examples simple, I used REQ|RES (a mock REST API) for my requests and responses.
Parse response value into a global variable
Global variables are available across all Postman environments.
In this example, we want to save a token returned by a login request.
To parse the value of the “token” field into a global variable called “oauth_token”, click on the Tests tab and add the following JavaScript code:
const jsonResponse = pm.response.json();
pm.globals.set("oauth_token", jsonResponse.token);
Code language: JavaScript (javascript)
The next time you execute the request, the token is saved into the “oauth_token” global variable.
To access the variable value, enter {{oauth_token}}. For example, in the following request we use the “oauth_token” variable in the authorization header.
Parse response value into an environment variable
Environment variables are only available in the environment you specify. Parsing a value into an environment variable is very similar to parsing a value into a global variable, which we explained above.
To parse the value of the “token” field into an environment variable called “oauth_token”, in the currently selected environment, click on the Tests tab and add the following JavaScript code:
const jsonResponse = pm.response.json();
pm.environment.set("oauth_token", jsonResponse.token);
Code language: JavaScript (javascript)
Note: If you use the same name for an environment variable and a global variable, the environment variable takes precedence.
The next time you execute the request, the token is saved into a variable called “oauth_token” in the environment you have selected (“Development” in our case).
To see an environment variables and their values, click on the eye icon next to the environment name.
To access the variable value, enter {{oauth_token}}. For example, in the following request we use the “oauth_token” variable in the authorization header. You must select the correct environment (“Development” in our case) in order to access the variable value.
Comments are closed.