Table of contents
1.
Introduction
2.
The pm object in Postman
2.1.
Using scripts variables
2.1.1.
Using environment variables in scripts
2.1.2.
Using collection variables in scripts
2.1.3.
Using global variables in scripts
2.1.4.
Using data variables in scripts
2.2.
Request and response data Scripting
2.2.1.
Scripting with request data 
2.2.2.
Scripting with response data
2.2.3.
Scripting with request info
2.2.4.
Scripting with request cookies
2.3.
Sending requests from scripts
3.
Scripting workflows
4.
Scripting Postman Visualizations
5.
Build response data into Postman Visualizations
6.
Writing test assertions
7.
Using external libraries
8.
Frequently Asked Questions
8.1.
How to add a delay between Postman requests?
8.2.
How to read external files?
8.3.
How do I add a library to my Postman?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

JavaScript Libraries available in Postman

Author Sanjana Yadav
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Postman has a powerful Node.js runtime that allows you to add dynamic behavior to requests and collections. This runtime helps you to conduct API tests, create calls with dynamic parameters, transmit data across requests, and much more. 

Introduction

Postman provides JavaScript APIs, which are used in request scripts. The pm object allows you to test your request and response data, while the postman object gives further workflow management.

With this prior knowledge of Postman, let us discuss the Javascript libraries in Postman.

The pm object in Postman

The pm.* gives access to the request and response data and variables and performs most of the Javascript API functionality.

Using scripts variables

With the help of Postman's pm API, you can access and change variables at each scope.

Using Script variables

Postman supports several variable scopes. The pm object has methods for precisely accessing variables at the global, collection, and environment levels. The pm.variables methods are used to access variables at various levels and build local variables.

Below are some use cases:

✨To Verify if a Postman variable is present in the current scope:

  pm.variables.has(variableName:String):function → Boolean


✨To get the value of the Postman variable with the given name:

pm.variables.get(variableName:String):function → *


✨To add the name and value of the specified local variable:

 pm.variables.set(variableName:String, variableValue:*):function


✨Using the notation {{$variableName}}, to return the resolved value of a dynamic variable inside a script:

pm.variables.replaceIn(variableName:String):function: → *


✨To send back an object with a list of all variables and their associated values for the current scope. This will include variables from several scopes depending on the order of precedence.

pm.variables.toObject():function → Object


Variable scope creates the order of increasing priority that Postman gives variables when you mention them:

✒️Global

✒️Collection

✒️Environment

✒️Data

✒️Local
 

The one with the closest scope overrides any other variables. 

Using environment variables in scripts

By using the pm.environment methods in scripts, we can access and change the variables in the active(currently chosen) environment.

Using environment variables in scripts

A list of some use cases is given below:

✔️To get the active environment's name:

pm.environment.name:String

 

✔️Check to see whether the environment contains the named variable:

pm.environment.has(variableName:String):function → Boolean

 

✔️To identify the variable by name in the current environment:

pm.environment.get(variableName:String):function → *

 

✔️To set the variable in the current environment with the given name and value:

pm.environment.set(variableName:String, variableValue:*):function

 

✔️Using the notation {{$variableName}}, return the resolved value of a dynamic variable inside a script:

pm.environment.replaceIn(variableName:String):function → *

 

✔️The current environment's variables and values should all be returned in a single object:

pm.environment.toObject():function → Object

 

✔️By naming the variable and removing it from the current environment:

pm.environment.unset(variableName:String):function


✔️To clear every variable in the environment that is active:

pm.environment.clear():function


Using collection variables in scripts

The pm.collectionVariables methods let you access and work with collection variables in your scripts.

Using collection variables in scripts

✔️Verify if the collection has a variable with the given name:

pm.collectionVariables.has(variableName:String):function → Boolean


✔️Give the name-specified collection variable's value back:

pm.collectionVariables.get(variableName:String):function → *


✔️Set the name and value of the collection variable:

pm.globals.set(variableName:String, variableValue:*):function


✔️Using the notation {{$variableName}}, return the resolved value of a dynamic variable inside a script:

pm.globals.replaceIn(variableName:String):function → String


✔️Object that contains all of the variables' values from the collection:

pm.globals.toObject():function → Object


✔️The collection's specified variable is removed using:

pm.globals.unset(variableName:String):function


✔️Delete the collection's variables completely:

pm.globals.clear():function


Using global variables in scripts

We can use the pm.global methods to access and change the global variables of the workspace using scripts.

Using global variables in scripts

✔️Verify if there is a global variable with the given name :

pm.globals.has(variableName:String):function → Boolean


✔️Return the value of the named global variable:

pm.globals.get(variableName:String):function → *


✔️Specify a name and value for a global variable:

pm.globals.set(variableName:String, variableValue:*):function


✔️Using the notation {{$variableName}}, return the resolved value of a dynamic variable inside a script:

pm.globals.replaceIn(variableName:String):function → String


✔️Return the values of all global variables as an object:

pm.globals.toObject():function → Object


✔️Remove the given global variable:

pm.globals.unset(variableName:String):function


✔️Clear the workspace of all global variables:

pm.globals.clear():function


Using data variables in scripts

By using the pm.iterationData methods, the scripts can read and modify the variables from data files.

Using data variables in scripts

✔️Verify whether the data from the current iteration contains a variable with the required name:

pm.iterationData.has(variableName:String):function → boolean


✔️Return a variable with the given name from the iteration data:

pm.iterationData.get(variableName:String):function → *


✔️The iteration data variables should be returned as an object:

pm.iterationData.toObject():function → Object


✔️Change the iterationData object's format to JSON:

pm.iterationData.toJSON():function → *


✔️Delete the given variable:

pm.iterationData.unset(key:String):function

Request and response data Scripting

Postman scripts may fetch request and response data in various different ways, including pm.request, pm.response, pm.info, and pm.cookies. You can also send requests by using pm.sendRequest methods.

Request and response data Scripting

Scripting with request data 

We can use the pm.request object to access the data for the request in which the scripts are running.

The following attributes and methods are available through the pm.request object:

🌻URL of the request:

pm.request.url:Url


🌻The current request's list of headers is as follows:

pm.request.headers:HeaderList


🌻HTTP request method:

pm.request.method:String


🌻The data in the body of the request. This item is script-immutable and cannot be changed:

pm.request.body:RequestBody


🌻For the current request, add a header with the name and value you've specified:

pm.request.headers.add(header:Header):function

 

🌻The request header with the given name needs to be removed:

pm.request.headers.remove(headerName:String):function


🌻If the header doesn't already exist, add the supplied header name and value; otherwise, the current header will be updated with the new value.

pm.request.headers.upsert({key: headerName:String, value: headerValue:String}):function)


Scripting with response data

In scripts added to the Tests, the pm.response object gives access to the data returned in the response for the current request.

The following attributes and methods are available from the pm.response object:

🌻The status code of the response:

pm.response.code:Number


🌻The status text string:

pm.response.status:String


🌻The list of headers in the response:

pm.response.headers:HeaderList


🌻The time in milliseconds it takes to receive the response:

pm.response.responseTime:Number


🌻Size of the response that was returned:

pm.response.responseSize:Number


🌻The response text is:

pm.response.text():Function → String


🌻You may utilize the response JSON to go deeper into the attributes you received:

pm.response.json():Function → Object


Scripting with request info

The pm.info object provides data about the request and script itself, such as the name, request ID, and iteration count.

The following properties and methods are available through the pm.info object:

🌻Depending on where the script is running within the request, the event will either be pre-request or test:

pm.info.eventName:String


🌻The total number of scheduled iterations is as follows:

pm.info.iteration:Number


🌻The current iteration's value:

pm.info.iterationCount:Number


🌻The running request's stored name is:

pm.info.requestName:String


🌻A special GUID that distinguishes the active request:

pm.info.requestId:String


Scripting with request cookies

Access to the list of cookies connected to the request is available through the pm.cookies object.

The following attributes and methods are available from the pm.cookies object:

🌻Check to see whether the given domain has a certain cookie (provided by name):

pm.cookies.has(cookieName:String):Function → Boolean


🌻Retrieve the provided cookie's value:

pm.cookies.get(cookieName:String):Function → String


🌻Get an object containing copies of all the cookies and their values. Any cookies that are defined for the request domain and path are returned:

pm.cookies.toObject():Function → Object


To specify a URL for access to request cookies, you may also use pm.cookies.jar

Sending requests from scripts

You can send a request asynchronously from a Pre-request(the is the request that is about to run)  or Test script(this is the request that has already run) by using the pm.request method.

This method allows you to run the logic in the background in cases when you are making computations or sending multiple requests simultaneously.

We can send a URL string or a complete request configuration in JSON, including headers, method, body, and more, to the pm.sendRequest function.

Sending requests from scripts

Examples:

🍁 With a plain string URL

  pm.sendRequest('https://postman-echo.com/get', (error, response) => {
  if (error) {
    console.log(error);
  } else {
  console.log(response);
  }
});


🍁With a full-fledged request

const postRequest = {
  url: 'https://postman-echo.com/post',
  method: 'POST',
  header: {
    'Content-Type': 'application/json',
    'X-Foo': 'bar'
  },
  body: {
    mode: 'raw',
    raw: JSON.stringify({ key: 'this is json' })
  }
};
pm.sendRequest(postRequest, (error, response) => {
  console.log(error ? error : response.json());
});


🍁Containing a test

pm.sendRequest('https://postman-echo.com/get', (error, response) => {
  if (error) {
    console.log(error);
  }
  pm.test('response should be okay to process', () => {
    pm.expect(error).to.equal(null);
    pm.expect(response).to.have.property('code', 200);
    pm.expect(response).to.have.property('status', 'OK');
  });
});


You can practice by yourself with the help of Online Javascript Compiler for better understanding.

Scripting workflows

The setNextRequest function of the postman object allows us to create request workflows while using the collection runner or Newman.

Scripting workflows

When you run a collection (using the collection runner or Newman), Postman will execute your requests in either the default order or the order you choose when you set up the run. To change this execution sequence, use postman.setNextRequest to indicate which request should be executed next.

🌼Run the provided request (the one with the name defined in the collection, such as "Get customers") after this one:

postman.setNextRequest(requestName:String):Function


🌼Run the specified request after this one (the request ID returned by pm.info.requestId):

postman.setNextRequest(requestId:String):Function

Scripting Postman Visualizations

We can use the pm.visualizer.set to define a template for the Postman Visualizer to display response data

pm.visualizer.set(layout:String, data:Object, options:Object):Function

Here,

layout is a required field.

data is a required field.

options is a required field.

Scripting Postman Visualizations

Build response data into Postman Visualizations

We can access response information included within a Postman Visualizer template string using pm.getData.

pm.getData(callback):Function


Two arguments are accepted by the callback function:

error: Any error information

Data: provided by pm.visualizer.set to the template

Writing test assertions

Build response data into Postman Visualizations

Syntax:

pm.test(testName:String, specFunction:Function):Function

You can use pm.test to create test requirements in either the Pre-request or Tests scripts. Tests have a name and an assertion. The Postman will respond with the test results.

The call chain is chainable since the pm.test function returns the pm object. The sample test that follows verifies a response's validity before moving on.

pm.test("response should be okay to process", function () {
  pm.response.to.not.be.error;
  pm.response.to.have.jsonBody('');
  pm.response.to.not.have.jsonBody('error');
});
pm.test('async test', function (done) {
  setTimeout(() => {
    pm.expect(pm.response.code).to.equal(200);
    done();
  }, 1500);
});

Using external libraries

You may use the built-in library modules of the sandbox by using the require method.

require(moduleName:String):function → *

The list of accessible libraries is provided below:

✍️ajv

✍️atob

✍️btoa

✍️chai

✍️cheerio

✍️crypto-js

✍️csv-parse/lib/sync

✍️lodash 

✍️moment

✍️postman-collection

✍️tv4

✍️uuid

✍️xml2js
 

NodeJS modules listed below can also be used in the sandbox:

✍️path

✍️assert

✍️buffer

✍️util

✍️url

✍️punycode

✍️querystring

✍️string-decoder

✍️stream

✍️timers

✍️events
 

To use a library: 

👉Call the require method. 

👉Supply the module name as an argument.

👉Then, return the method's result object to a variable.

Frequently Asked Questions

How to add a delay between Postman requests?

Include the following in your tests to introduce a delay after a request:s
setTimeout(() => {}, 10000);

How to read external files?

You might wish to use Postman to access any information stored locally on your machine.
Unfortunately, this is not feasible. There is a technique to read a CSV or JSON data file that allows you to change some variables dynamically. These variables, also known as data variables, are typically used to test various iterations of a particular request or collection.

Possible ways are:

  • Start a local server to serve the file and get it using a GET request in Postman.
  • Use the filesystem to read the file using a custom Node.js script called Newman.

How do I add a library to my Postman?

Copy and paste the library's code into a collection variable.
After saving the code, you can run it in the Postman sandbox by creating and setting a variable equal to the collection variable.

Conclusion

In this blog, we discussed Javascript libraries in Postman. We learned scripting with request and response data, starting with the pm object and usage of several variables in scripts.

We also discussed script workflows and scripting visualizations in postman.
We hope this blog increases your knowledge of API Testing tools. To learn more about Postman, refer to our articles, Learn and Practice Postman from Coding Ninjas Studio.
And if you want to explore more API testing tools and technologies, you can refer to our blogs on Web Testing, API Testing and API.

You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more.
If you liked our article, do upvote our article and help other ninjas grow!
Visit our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and interview bundle
Follow guided paths for placement preparations and much more!

Thankyou
Live masterclass