Extracting and Managing Access Tokens in Postman
When working with APIs that use OAuth 2.0 or token-based authentication, a common requirement is to extract an access_token from a successful authentication request and reuse it in subsequent API calls. Postman provides a built-in scripting environment that makes this straightforward and repeatable.
This article explains how to capture an access token from a POST request response and store it securely as an environment variable in Postman.
Context
In many APIs, an authentication endpoint returns a JSON response similar to the following:
{
"access_token": "<JWT_ACCESS_TOKEN>",
"token_type": "Bearer",
"expires_in": 3600
}
The goal is to:
- Parse the response.
- Extract the
access_token. - Store it in a Postman environment variable.
- Reuse it automatically in other requests.
Using the Postman Sandbox (pm)
Postman exposes a global object called pm inside Pre-request Scripts and Tests. This object is part of the Postman Sandbox API and allows interaction with requests, responses, variables, and assertions.
Key capabilities include:
- Reading response data
- Defining tests
- Managing environment and collection variables
- Logging to the Postman Console
Extracting the Access Token
In the request that returns the token, open the Tests tab and add the following script:
let body = pm.response.json();
pm.test("access_token exists", function () {
pm.expect(body.access_token).to.be.a("string").and.not.empty;
});
pm.environment.set("TOKEN", body.access_token);
console.log("TOKEN stored in environment");
Important notes:
- Ensure the correct environment is selected (for example,
zoom,dev, orstaging) in the top-right environment selector. - Avoid logging the raw token in shared workspaces.
Reusing the Token in Other Requests
Once stored, the token can be referenced using Postman variable syntax:
Header configuration
Authorization: Bearer {{TOKEN}}
This ensures all subsequent requests automatically include the latest valid token without manual updates.
Optional: Handling Token Expiration
If the response includes expiration metadata, you can store it as well:
if (typeof body.expires_in === "number") {
const expiresAt = Date.now() + body.expires_in * 1000;
pm.environment.set("TOKEN_EXPIRES_AT", String(expiresAt));
}
This allows you to implement logic in a Pre-request Script to refresh the token when it expires.
Viewing Logs
To inspect logs produced by console.log:
- Open View → Show Postman Console
- Execute the request
- Review the output for debugging purposes
Best Practices
- Never commit real tokens to version control.
- Avoid printing sensitive values in shared environments.
- Use environment variables instead of hardcoded values.
- Separate environments (local, staging, production).