Postman – Set Variable Values Dynamically with Response Data

If you’re a developer, chances are you’ve worked with APIs. If you’ve worked with APIs, chances are you’ve worked with Postman! I love this tool. Being able to save requests, group them into collections, and store variables for them makes my life easier. Recently, I discovered how to set variable values dynamically with response data in Postman from a previous request. Here I’ll show you an example of how to do that.

In this example, I am going to save an API Auth Token to a variable for subsequent Postman requests. It’s very common for these kinds of tokens to expire, and if you are working on a project with a lot of different requests, it can be time consuming to update the token across all of the requests. But with a little Javascript, you can actually set the token to a variable automatically, so whenever your token expires, simply hit the endpoint again and it will update the token across all of your requests. Pretty cool, huh?

Set variable values dynamically with response data

First, create a collection and click on the Variables tab. Create your authentication variables. I created a token variable but left it blank for now.

screen shot showing where to set request variables in Postman

Next, create a POST request to hit the authentication endpoint. Click on the “Tests” tab. This is where the magic happens. Add this code in the tests screen.

let response = pm.response.json();
console.log(response);
screenshot showing where to write tests in Postman

Down at the bottom left of the screen you will see a button for “console”. Click that to open your developer console. Now, send the request and it will log the response in JSON format to your console. This way you can determine how to extract the token from the response. In my case, I will access my token with response.token. Once you figure out how to access your token, you can set it by updating your code in the tests tab like so:

let response = pm.response.json();
pm.collectionVariables.set('token', response.token);
Screenshot of code for how to set a request variable from response data in Postman

Now when you send the response, go back to your collection variables and you will see the “current value” was updated with the token from the request! You can use the token in as many requests as you need to, and when it expires you can easily update all of your requests by simply re-authenticating. I like to create a “requests” folder and store all of my requests that need the token in there. Then for the folder, you can add the token variable as the authorization type. This way, you can keep requests that don’t need a token separate from the ones that do.

Example of folder structure in Postman Workspace

So, that is how to set variable values dynamically with response data in Postman. Hopefully this will help you with your workflow and gives you a bigger appreciation for what a great tool Postman is. Happy coding!