Postman variables: environments, collections and passing a token
Variables save you from copying addresses and tokens between requests. The key is knowing which scope holds the value and which scope wins.
Scopes
Postman has five scopes: global, collection, environment, data from a file during a run, and local for the duration of a request. If a name exists in several, the narrowest wins: local, then data, environment, collection and finally global. Keep stand addresses in environments and values shared by the collection in collection variables.
Save a token from a response
The login request gets a token and a post-response script stores it in an environment variable. Other requests put {{token}} into the header. A variable has a value that is shared on export and collaboration and a value kept only on your machine: keep secrets in the latter.
// Scripts tab → Post-response of the login request
const body = pm.response.json();
pm.environment.set("token", body.access_token);
// In the following requests: Authorization → Bearer Token → {{token}}Dynamic variables
Postman fills in random and utility values with no scripts: {{$guid}} is a new identifier, {{$timestamp}} the current time in seconds, {{$randomInt}} a random number. They are handy for unique order numbers and emails in test data.
{
"orderId": "{{$guid}}",
"createdAt": {{$timestamp}},
"email": "user{{$randomInt}}@example.com"
}Why a variable is not substituted
No environment is selected in the top right corner. The name differs in case: token and Token are different variables. The value is set in another scope or overridden by a narrower one. The script that sets it has not run yet: post-response runs only after the request is sent. An unresolved variable is highlighted in the URL and headers.
Without scripts
In Checkcraft a value from the response is saved to a variable with a checkbox in the rule and inserted into the next step’s URL, header or body. Postman collections can be imported and their responses checked with rules, no JavaScript.
Repeat this on your own API
Checkcraft is a desktop app that saves API response checks without code and shows what did not match. Start with a sample, then use your own sanitized data. Free runs on Windows and Linux with no time limit.
Download FreeDownload and first runNo sign-up or email needed, the archive is ready in a couple of minutes. See the edition limits.
References
Start with the linked example and compare its result with your own test requirement.