Codementor Events

Enhance Your Postman Testing Experience with a Basic Script

Published May 06, 2020Last updated Oct 24, 2023

Victoria Etim

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)

In this article, you'll learn how to optimize your API testing workflow using Postman. With Postman, you can leverage scripts to work with dynamic variables, transfer data between requests, and perform tests. The article provides guidance on writing pre-request and post-response scripts, making it easier to manage authorization tokens and streamline your API testing process.

By following these steps, you can ensure that your API requests remain up-to-date with the latest token, simplifying the testing process. Say goodbye to manual token management, and say hello to more efficient API testing with Postman! 😃

Key sections covered in the script include:

Testing the success of a login request.
Extracting the authorization token from the response, typically in JSON format.
Setting the token as a collection variable for easy access across requests.

1. Test that the login was successful

pm.test(“Status code is 200”, function () {  
 pm.response.to.have.status(200);  
 /\*.......\*/  
});

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

{  
 status: true,  
 auth_token: 'fnfvkfokrkfmorlfkrpfmfldcmdlxnklde94i95nndmefolkeo'  
}

to access the token from the response,

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

3. Setting the token as a collection variable.

Please read up on dynamic variables is 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

You final script should look like thios

pm.test(“Status code is 200”, function () {  
 pm.response.to.have.status(200);  
 let jsonData = pm.response.json();  
 let accessToken = jsonData.auth_token;  
 pm.collectionVariables.set('collection_access_token', accessToken);});
Discover and read more posts from Victoria Etim
get started
post commentsBe the first to share your opinion
Show more replies