Tokens help keep your API requests safe and working. Storing tokens in variables makes it easy to reuse and update them without changing every request.
0
0
Token management in variables in Postman
Introduction
When you need to send an access token with many API requests.
When your token changes often and you want to update it in one place.
When sharing your Postman collection with others who need the same token setup.
When automating tests that require login and token refresh.
When you want to keep your token secret and not hard-code it in requests.
Syntax
Postman
pm.environment.set('token', 'your_token_here'); pm.environment.get('token');
Use pm.environment.set to save a token in environment variables.
Use pm.environment.get to retrieve the token when making requests.
Examples
This saves the token 'abc123xyz' in the environment variable named 'authToken' and then prints it.
Postman
pm.environment.set('authToken', 'abc123xyz'); console.log(pm.environment.get('authToken'));
This stores a temporary token in local variables for the current request only.
Postman
pm.variables.set('tempToken', 'temp123'); const token = pm.variables.get('tempToken');
This saves a token globally, accessible in all collections and environments.
Postman
pm.globals.set('globalToken', 'global456'); const token = pm.globals.get('globalToken');
Sample Program
This script saves a token in environment variables, adds it to the request header, and tests that the token is present and valid.
Postman
// 1. Save token after login pm.environment.set('accessToken', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'); // 2. Use token in Authorization header const token = pm.environment.get('accessToken'); pm.request.headers.add({key: 'Authorization', value: `Bearer ${token}`}); // 3. Check token exists pm.test('Token is set', function () { pm.expect(token).to.not.be.undefined; pm.expect(token).to.be.a('string').and.not.empty; });
OutputSuccess
Important Notes
Always store tokens in environment or global variables, not hard-coded in requests.
Use environment variables for tokens that change per environment (dev, test, prod).
Clear tokens from variables when they expire or after tests to avoid confusion.
Summary
Tokens keep your API requests authorized and secure.
Store tokens in Postman variables to reuse easily and update quickly.
Use environment variables for tokens that change with environments.