Gray Wolf Corporation

Update Postman environment variables with response values

Postman is a great tool for testing apis. One of the best features is the scripting language, that can be used both as pre-request script as well as a testing framework.

One time saving area is when you are working behind a password protected api. When you need to re-authenticate, it is very handy to have the token stored as an environment variable. This environment variable can then be updated by running a login request through Postman that will extract the token. The updated environment variable then can be used in all requests where authentication is implemented.

The following script is added to the Tests section of a Postman request. It checks to confirm the request returned status 200. If so, it parses the reponse body. It will then look for a property called "token" in the parsed object and assign that value (if any) to the environment variable "palmBearerToken".

pm.test("Status code is 200", function () {
  pm.response.to.have.status(200);
});

var json = JSON.parse(responseBody);
postman.setEnvironmentVariable("palmBearerToken", json.token);

pm script

An unhandled error has occurred. Reload 🗙