Postman Pre-request Scripts

This is a helpful tip for those who use Postman to test their APIs. I was testing a third-party API and one of the required parameters for each request is a security token. To get the current token I have to call a /refresh endpoint which returns the new token. So anytime I want to make a request to some other endpoint, say /foo, and my token is stale, I have to call /refresh first and copy and paste the returned access token into my /foo request’s token parameter. This got to be pretty tedious and I thought surely there was a better way to handle this.

Turns out, Postman has a couple of features that have helped immensely. The first feature is Postman’s Pre-request Script. This gets executed before your actual request. The below is my example pre-request script that hits the /refresh endpoint and stores the returned access token in a global environment variable. Environment variables is the second feature that helps with this.

var settings = {
"async": true,
"crossDomain": true,
"url": environment.ThirdPartyUrl + "/authorize/refresh/?AppKey=" + environment.ThirdPartyApiKey,
"method": "GET"
$.ajax(settings).done(function (response) {
postman.setGlobalVariable("AccessToken", response.AccessToken);

I’m using a couple of environment variables to access the third-party API’s base URL and my given API key. In the request callback, I’m accessing the setGlobalVariable method on the built-in postman object to set the returned response’s AccessToken value to the global variable “AccessToken”.

As you can see in the above image for the /foo request, I’m accessing the value stored in the environment variable, AccessToken, by wrapping it in double curly braces. Now instead of having to make a separate request to /refresh and then copy and paste the returned AccessToken into the /foo request, I let the pre-request script and environment variable handle all that for me.

Environment variables can be managed in the upper right corner of Postman.