Basic Script to ease your postman testing experience

Victoria Etim
2 min readMay 6, 2020
Photo by Max Duzij on Unsplash

With Postman, you can add scripts to your request to use dynamic variables, pass data between requests, and write tests. Code added under the Pre-request Script tab will execute before your request is sent, and code added under the Tests tab will execute after your response is received.(Ref: https://blog.getpostman.com/2017/10/25/writing-tests-in-postman)

Writing test and pre-request script in postman comes in handy when you are building an API that requires authorization token which is usually sent in the login response. Imagine not having to copy the access_token from the login endpoint when it expires, cool right? :)

This script has 3 basic sections

  1. Test that the login was successful
pm.test(“Status code is 200”, function () {
pm.response.to.have.status(200);
/*.......*/
});

2. Fetch the authorization token from the response: in this case, it’s a JSON response formatted like

{
status: true,
auth_token: 'fnfvkfokrkfmorlfkrpfmfldcmdlxnklde94i95nndmefolkeo'
}

to access the token from the response,

var jsonData = pm.response.json();
var accessToken = jsonData.auth_token;

3. Set the token to a collection variable. Please read up on dynamic variables if you have not.

pm.collectionVariables.set('collection_access_token', accessToken);

With that done, anywhere in the request in that collection can use the access_token by setting {{collection_access_token}}.

On any request, go to click the Authorization tab. Select Bearer token or whatever authentication type is required and assign the value to the collection variable {{collection_access_token}}.

Now every time your token expires you just have to click login and all requests in the collection have the updated token :)

Putting it all together

pm.test(“Status code is 200”, function () {
pm.response.to.have.status(200);
var jsonData = pm.response.json();
var accessToken = jsonData.auth_token;
pm.collectionVariables.set('collection_access_token', accessToken);
});

--

--