Automatically Update Postman Variables

When building APIs, you'll often want to create and store a collection of endpoints and requests in order to test quickly and effectively. There are a number of tools to help with this, but the one I use most often is Postman.

When building or integrating with APIs, you'll often want to create and store a collection of endpoints and requests in order to test quickly and effectively. There are a number of tools to help with this, but the one I use most often is Postman.

To make things easier, postman has a concept of collections, which is a collection of endpoints, and environments, which allow you to store variables and information for a particular environment such as test or production.

Many APIs have some kind of short-lived authorization token that must be added to the header, and if you have endpoints in Postman that are saved with variables, it can be a hassle to manually update the auth token (or anything else) every time it changes

One simple way to resolve this is through the use of "Tests." Lets say you have an API that's protected by a service like Auth0. You have an environment that has a "token" variable, and that token only lasts for 2 hours.

You also have two endpoints in the collection - one for getting the token, and another that will use the token

To automatically update the {{token}} variable in all of our other requests, we can go to the "Tests" section of the "Get Token" request and write some JavaScript that runs after the request has been completed.

What this does is that once the request to retrieve a token has been made, the response is saved in responseData. We can then set the "token" variable to the response data's "access_token" value, and we're ready to go.

Any time that we retrieve a new token, that token will be utilized in all other endpoints that have an "Authorization": "Bearer {{token}}" header value.


Have you used Postman tests to automate something or make your life easier? I'd love to hear about it in the comments!