The Postman JavaScript API functionality enables you to programmatically access and alter request and response data and variables using the pm
object. You can also dynamically alter execution order to build request workflows for the Collection Runner.
You can access and manipulate variables at each scope in Postman using the pm
API.
You can use dynamic variables to generate values when your requests run.
Postman supports a variety of variable scopes. The pm
object provides methods for accessing global, collection, and environment variables specifically, and pm.variables
methods for accessing variables at different scopes and setting local variables.
pm.variables.has(variableName:String):function → Boolean
pm.variables.get(variableName:String):function → *
pm.variables.set(variableName:String, variableValue:*):function
{{$variableName}}
:pm.variables.replaceIn(variableName:String):function: → *
For example:
const stringWithVars = pm.variables.replaceIn("Hi, my name is {{$randomFirstName}}");
console.log(stringWithVars);
pm.variables.toObject():function → Object
Variable scope determines the precedence Postman gives to variables when you reference them, in order of increasing precedence:
The variable with the closest scope overrides any others. For example, if you have variables named score
in both the current collection and the active environment, and you call pm.variables.get('score')
, Postman will return the current value of the environment variable. When you set a variable value using pm.variables.set
, the value is local and will only persist for the current request or collection run.
//collection var 'score' = 1
//environment var 'score' = 2
//first request run
console.log(pm.variables.get('score'));//outputs 2
console.log(pm.collectionVariables.get('score'));//outputs 1
console.log(pm.environment.get('score'));//outputs 2
//second request run
pm.variables.set('score', 3);//local var
console.log(pm.variables.get('score'));//outputs 3
//third request run
console.log(pm.variables.get('score'));//outputs 2
See the Postman Collection SDK Variables reference for more detail.
You can also access variables defined in the individual scopes with pm.environment, pm.collectionVariables, and pm.globals.
Your scripts can use the pm.environment
methods to access and manipulate variables in the active (currently selected) environment.
pm.environment.name:String
pm.environment.has(variableName:String):function → Boolean
pm.environment.get(variableName:String):function → *
pm.environment.set(variableName:String, variableValue:*):function
{{$variableName}}
:pm.environment.replaceIn(variableName:String):function → *
For example:
//environment has vars firstName and age
const stringWithVars = pm.environment.replaceIn("Hi, my name is {{firstName}} and I am {{age}}.");
console.log(stringWithVars);
pm.environment.toObject():function → Object
pm.environment.unset(variableName:String):function
pm.environment.clear():function
Note that your ability to edit variables depends on your access level in the workspace.
Your scripts can use the pm.collectionVariables
methods to access and manipulate variables in the collection.
pm.collectionVariables.has(variableName:String):function → Boolean
pm.collectionVariables.get(variableName:String):function → *
pm.collectionVariables.set(variableName:String, variableValue:*):function
{{$variableName}}
:pm.collectionVariables.replaceIn(variableName:String):function → *
For example:
//collection has vars firstName and age
const stringWithVars = pm.collectionVariables.replaceIn("Hi, my name is {{firstName}} and I am {{age}}.");
console.log(stringWithVars);
pm.collectionVariables.toObject():function → Object
pm.collectionVariables.unset(variableName:String):function
pm.collectionVariables.clear():function
Your scripts can use the pm.globals
methods to access and manipulate variables at global scope within the workspace.
pm.globals.has(variableName:String):function → Boolean
pm.globals.get(variableName:String):function → *
pm.globals.set(variableName:String, variableValue:*):function
{{$variableName}}
:pm.globals.replaceIn(variableName:String):function → String
For example:
//globals include vars firstName and age
const stringWithVars = pm.globals.replaceIn("Hi, my name is {{firstName}} and I am {{age}}.");
console.log(stringWithVars);
pm.globals.toObject():function → Object
pm.globals.unset(variableName:String):function
pm.globals.clear():function
Note that your ability to edit variables depends on your access level in the workspace.
Your scripts can use the pm.iterationData
methods to access and manipulate variables from data files during a collection run.
pm.iterationData.has(variableName:String):function → boolean
pm.iterationData.get(variableName:String):function → *
pm.iterationData.toObject():function → Object
pm.iterationData.toJSON():function → *
pm.iterationData.unset(key:String):function
A variety of methods provide access to request and response data in Postman scripts, including pm.request, pm.response, pm.info, and pm.cookies. Additionally you can send requests using pm.sendRequest.
The pm.request
object provides access to the data for the request the script is running within. For a Pre-request this is the request that's about to run, and for a Post-response script this is the request that has already run.
You can use the pm.request
object pre-request scripts to alter various parts of the request configuration before it runs.
The pm.request
object provides the following properties and methods:
pm.request.url:Url
pm.request.headers:HeaderList
pm.request.method:String
pm.request.body:RequestBody
pm.request.headers.add(header:Header):function
For example:
pm.request.headers.add({
key: "client-id",
value: "abcdef"
});
pm.request.headers.remove(headerName:String):function
pm.request.headers.upsert({key: headerName:String, value: headerValue:String}):function)
See the Postman Collection SDK Request reference for more detail.
The pm.response
object provides access to the data returned in the response for the current request in scripts added to the Post-response tab.
The pm.response
object provides the following properties and methods:
pm.response.code:Number
pm.response.status:String
pm.response.headers:HeaderList
pm.response.responseTime:Number
pm.response.responseSize:Number
pm.response.text():Function → String
pm.response.json():Function → Object
See the Postman Collection SDK Response reference for more detail.
The pm.info
object provides data related to the request and the script itself, including name, request ID, and iteration count.
The pm.info
object provides the following properties and methods:
prerequest
or test
depending on where the script is executing within the request:pm.info.eventName:String
pm.info.iteration:Number
pm.info.iterationCount:Number
pm.info.requestName:String
pm.info.requestId:String
The pm.cookies
object provides access to the list of cookies associated with the request.
The pm.cookies
object provides the following properties and methods:
pm.cookies.has(cookieName:String):Function → Boolean
pm.cookies.get(cookieName:String):Function → String
pm.cookies.toObject():Function → Object
See the Postman Collection SDK Cookie List reference for more detail.
You can also use pm.cookies.jar
to specify a domain for access to request cookies.
To enable programmatic access using the pm.cookies.jar
methods, first add a domain to the allowlist.
pm.cookies.jar():Function → Object
For example:
const jar = pm.cookies.jar();
//cookie methods...
jar.set(URL:String, cookieName:String, cookieValue:String, callback(error, cookie)):Function → Object
jar.set(URL:String, { name:String, value:String, httpOnly:Bool }, callback(error, cookie)):Function → Object
For example:
const jar = pm.cookies.jar();
jar.set("httpbin.org", "session-id", "abc123", (error, cookie) => {
if (error) {
console.error(`An error occurred: ${error}`);
} else {
console.log(`Cookie saved: ${cookie}`);
}
});
jar.get(URL:String, cookieName:String, callback(error, value)):Function → Object
jar.getAll(URL:String, callback(error, cookies)):Function
jar.unset(URL:String, cookieName:String, callback(error)):Function → Object
jar.clear(URL:String, callback(error)):Function → Object
jar.clear(URL:String, callback(error) => {
jar.set(URL:String, cookieName:String, cookieValue:String, callback(error, cookie)):Function → Object
}):Function → Object
Function calls execute asynchronously. Use a callback function to ensure functions execute in sequence.
See the Postman Collection SDK Cookie reference for more detail.
You can use the pm.sendRequest
method to send a request asynchronously from a Pre-request or Post-response script. This allows you to execute logic in the background if you are carrying out computation or sending multiple requests at the same time without waiting for each to complete. You can avoid blocking issues by adding a callback function so that your code can respond when Postman receives a response. You can then carry out any additional processing you need on the response data.
You can pass the pm.sendRequest
method a URL string, or can provide a complete request configuration in JSON including headers, method, body, and more.
// Example with a plain string URL
pm.sendRequest('https://postman-echo.com/get', (error, response) => {
if (error) {
console.log(error);
} else {
console.log(response);
}
});
// Example 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());
});
// Example 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');
});
});
See the Request definition and Response structure reference docs for more detail.
The pm.execution.location
property enables you to get the complete path of a request, including the folder and collection, in array format. For example, for a request named R1 in folder F1 in collection C1, the following post-response script code will return ["C1", "F1", "R1"]
:
console.log(pm.execution.location);
// Returns the full path of a request in array format, for example:
// ["C1", "F1", "R1"]
To get the name of the current element, you can use the pm.execution.location.current
property. For example, if you add the following code to the pre-request script of a folder named F1, it will return F1
:
console.log(pm.execution.location.current);
// Returns the name of the current element, for example:
// F1
You can use the pm.execution.location
and pm.execution.location.current
properties in your scripts to understand what items are being executed when a request is sent. This information enables you to implement logic and actions in your scripts tailored to the current location within your API testing or collection structure.
The pm.execution.skipRequest
method enables you to stop the execution of a request from a pre-request script.
pm.execution.skipRequest()
You can use the pm.execution.skipRequest
method on the Pre-request tab of a request, collection, or folder. When pm.execution.skipRequest()
is encountered, the request isn't sent. Any remaining scripts on the Pre-request tab are skipped, and no tests are executed.
For example:
//Skip this request if an authentication token isn't present
if (!pm.environment.get('token')) {
pm.execution.skipRequest()
}
In the Collection Runner, when pm.execution.skipRequest()
is encountered, Postman skips execution of the current request (including its post-response scripts) and moves to the next request in order. The run results will show no response and no tests found for the request. This same behavior also applies to Postman Flows, Newman, and the Postman CLI.
Using the
pm.execution.skipRequest
method isn't supported on the Post-response tab of a request, collection, or folder and will have no effect there. You will also get the following Console error:TypeError: pm.execution.skipRequest is not a function
.
The jsonSchema
method enables you to write a test assertion that validates the response data with a JSON Schema. Postman uses version 6.12.5 of the Ajv JSON Schema validator to validate response data with a JSON Schema.
To write your test assertion, use the pm.response
object and Chai Assertion Library BDD syntax to access the data returned in the response.
The jsonSchema
method accepts a JSON Schema as an object in the first argument. It also accepts an object of optional Ajv options in the second argument.
pm.response.<bdd-syntax>.jsonSchema(schema, options);
You can define a JSON Schema in Postman, such as the Tests tab of a request. Then you can write a test that validates the properties in your response data against the defined JSON Schema.
In the following example, the JSON Schema requires the response data to have a property named "alpha" that's a boolean data type. If the response data is missing this property or it's a different data type, the test will fail. This example uses BDD syntax to.have
to express the assertion.
const schema = {
"type": "object",
"properties": {
"alpha": {
"type": "boolean"
}
},
"required": ["alpha"]
};
pm.test('Response is valid', function() {
pm.response.to.have.jsonSchema(schema);
});
You can use the pm.execution.setNextRequest
method for building request workflows when you use the collection runner or Newman.
Note that
setNextRequest
has no effect when you run requests using Send; it only has an effect when you run a collection.
When you run a collection (using the collection runner or Newman), Postman will run your requests in a default order or an order you specify when you set up the run. However, you can override this execution order using pm.execution.setNextRequest
to specify which request to run next.
pm.execution.setNextRequest(requestName:String):Function
pm.info.requestId
):pm.execution.setNextRequest(requestId:String):Function
For example:
//script in another request calls:
//pm.environment.set('next', pm.info.requestId)
pm.execution.setNextRequest(pm.environment.get('next'));
Use pm.visualizer.set
to specify a template to display response data in the Postman Visualizer.
pm.visualizer.set(layout:String, data:Object, options:Object):Function
layout
required
data
optional
options
optional
Handlebars.compile()
Example usage:
var template = `<p>{{res.info}}</p>`;
pm.visualizer.set(template, {
res: pm.response.json()
});
Use pm.getData
to retrieve response data inside a Postman Visualizer template string.
pm.getData(callback):Function
The callback function accepts two parameters:
error
data
pm.visualizer.set
Example usage:
pm.getData(function (error, data) {
var value = data.res.info;
});
pm.test(testName:String, specFunction:Function):Function
You can use pm.test
to write test specifications inside either the Pre-request or Post-response scripts. Tests include a name and assertion. Postman will output test results as part of the response.
The pm.test
method returns the pm
object, making the call chainable. The following sample test checks that a response is valid to proceed.
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');
});
An optional done
callback can be passed to pm.test
, to test asynchronous functions.
pm.test('async test', function (done) {
setTimeout(() => {
pm.expect(pm.response.code).to.equal(200);
done();
}, 1500);
});
pm.test.index():Function → Number
The pm.expect
method allows you to write assertions on your response data, using ChaiJS expect BDD syntax.
pm.expect(assertion:*):Function → Assertion
You can also use pm.response.to.have.*
and pm.response.to.be.*
to build your assertions.
See Test examples for more assertions.
You can use the pm.require
method to import packages from your team's Package Library inside pre-request and post-response scripts in HTTP requests, collections, and folders. The contents of packages will only execute from personal, private, and team workspaces. The Package Library enables you to reuse scripts and tests in your workspaces. Learn how to reuse scripts and tests with the Package Library.
The pm.require
method accepts the name of the package in the Package Library. Declare the method as a variable if the package has functions or objects you want to call. If the package only has code or instances of the pm
object, you don't need to declare the method as a variable.
const variableName = pm.require('@team-domain/package-name');
variableName.functionName()
require(moduleName:String):function → *
The require
method allows you to use the sandbox built-in library modules. The list of available libraries is listed below with links to the corresponding documentation.
_
object v3.10.1 exists in the sandbox by default. Use require
to load the latest version.)The following NodeJS modules are also available to use in the sandbox:
To use a library, call the require
method, pass the module name as a parameter, and assign the return object from the method to a variable.
You can use tests to build Postman into your development projects in a variety of ways using Postman utilities.
Last modified: 2020/09/04
Additional resources
Videos
Blog posts