Skip to content

Script API reference ​

Everything a script can use in ApiWorkbench 1.4.0: the pm object, console, the bundled libraries and the older Postman globals. For an introduction, start with Scripts.

Scripts are JavaScript. Each script runs as the body of an async function, so top-level await works.

pm.info ​

Facts about the request that is running.

PropertyValue
pm.info.eventName"prerequest" or "test" (post-response)
pm.info.requestNameThe request's name
pm.info.requestIdThe request's id
pm.info.iterationThe current iteration, counting from 0
pm.info.iterationCountPlanned iterations: 1 for a single send, 0 in a recurring run

Variables ​

Five objects read and write variables. See Variables for what each scope is.

ObjectScopeWritable
pm.environmentThe selected environmentYes
pm.collectionVariablesThe request's collectionYes
pm.globalsGlobalsYes
pm.variablesEvery scope, resolved; writes are temporaryYes
pm.iterationDataThe current row of a data fileNo

pm.environment, pm.collectionVariables, pm.globals and pm.iterationData share these methods:

MethodWhat it does
get(name)The value, or undefined when the scope has none
set(name, value)Sets the variable's current value
unset(name)Removes the variable
has(name)true when the scope has the variable
clear()Removes every variable in the scope
toObject()All of the scope's variables as one object
replaceIn(text)Fills {{name}} placeholders in text from this scope

pm.variables looks through all scopes. The first scope that has the name wins, in this order: temporary values set with pm.variables.set, the data row, the environment, the collection, globals.

MethodWhat it does
pm.variables.get(name)The value the request would use for {{name}}
pm.variables.has(name)true when any scope has it
pm.variables.set(name, value)Sets a temporary value that overrides every scope. It is never saved.
pm.variables.unset(name), clear()Remove temporary values
pm.variables.toObject()Every variable, resolved
pm.variables.replaceIn(text)Fills {{name}} placeholders, including dynamic variables such as {{$guid}}

Notes:

  • Values are stored as text. set("n", 5) stores 5; an object is stored as JSON text.
  • With no environment selected, pm.environment values last until you close the app.
  • pm.iterationData is read-only. Its values are always text.

pm.request ​

The request about to be sent (pre-request) or the one that was sent (post-response). A pre-request script can change it: the method, URL, query parameters, path variables, headers, body and auth are applied to the request that goes out. The saved request is not altered.

MemberWhat it is
pm.request.methodThe HTTP method, such as "POST"
pm.request.urlThe URL object (below)
pm.request.headersA list of headers (see Lists); names ignore case
pm.request.bodyThe body: mode is raw, urlencoded, formdata, file or graphql
pm.request.authThe auth settings; pm.request.auth.type is the scheme
addHeader(h), upsertHeader(h), removeHeader(name)Shortcuts for the header list
addQueryParams(p), removeQueryParams(p)Shortcuts for the URL's query
getHeaders()The headers as a plain object

pm.request.url:

MemberWhat it is
toString()The whole URL as text
getHost()The host name
getPath()The path, starting with /
getQueryString()The query without the ?
getPathWithQuery()Path and query together
getRemote()Host and port
protocol, host, port, path, hashThe parts; host and path are arrays of segments
queryThe query parameters, as a list
variablesThe path variables, as a list
addQueryParams(p), removeQueryParams(p)Add or remove query parameters

pm.request.body:

MemberWhat it is
modeWhich kind of body is set
rawThe text of a raw body
urlencoded, formdataLists of fields
graphqlAn object with query and variables
update(body)Replaces the body; a string becomes a raw body
toString()The body as text

Scripts cannot attach local files. A file field or file body added by a script is dropped, with a note in the Console.

pm.response ​

The response. Available in post-response scripts only.

MemberWhat it is
pm.response.codeThe status code, such as 200
pm.response.statusThe reason text, such as "OK"
pm.response.headersA list of headers; names ignore case
pm.response.responseTimeTime taken, in milliseconds
pm.response.responseSizeBody size, in bytes
pm.response.cookiesCookies set by this response's Set-Cookie headers
pm.response.text()The body as text
pm.response.json()The body parsed as JSON; throws if it is not JSON
pm.response.jsonp()The JSON inside a JSONP wrapper
pm.response.reason()Same as status
pm.response.size()An object with body, header and total sizes
pm.response.contentInfo()contentType, mimeType, mimeFormat and charset
pm.response.toStarts an assertion (next table)

pm.response.to assertions ​

Use these inside pm.test. Each can be negated with not, as in pm.response.to.not.be.error.

AssertionPasses when
to.have.status(200)The status code is 200
to.have.status("OK")The reason text is OK
to.have.statusCode(200)The status code is 200
to.have.statusCodeClass(2)The status is 2xx
to.have.statusReason("OK")The reason text matches
to.be.okThe status is exactly 200
to.be.info, success, redirection, clientError, serverErrorThe status is 1xx, 2xx, 3xx, 4xx, 5xx
to.be.errorThe status is 4xx or 5xx
to.be.accepted, withoutContentThe status is 202, 204
to.be.badRequest, unauthorized, forbidden, notFound, notAcceptable, rateLimitedThe status is 400, 401, 403, 404, 406, 429
to.have.header(name)The header exists
to.have.header(name, value)The header equals value, or matches it when value is a regular expression
to.be.withBody, to.have.body()The body is not empty
to.have.body(text)The body equals text exactly
to.have.body(/regex/)The body matches the pattern
to.be.json, to.have.jsonBody()The body is valid JSON
to.have.jsonBody(path)The JSON has a value at path, such as "data.items[0].id"
to.have.jsonBody(path, value)The value at path deep-equals value
to.have.jsonBody(object)The whole JSON body deep-equals object
to.have.jsonSchema(schema)The JSON body is valid against a JSON Schema (checked with Ajv)
to.be.html, to.be.xmlThe Content-Type contains html, xml
to.have.cookie(name)A cookie with that name is set
to.have.cookie(name, value)The cookie has that value
to.have.responseTime.below(500)The response took less than 500 ms
to.have.responseSize.below(1000)The body is smaller than 1000 bytes

After responseTime and responseSize you can use any Chai number check: below, above, within(a, b), at.most.

pm.test and pm.expect ​

FunctionWhat it does
pm.test(name, fn)Runs fn as a named test. It passes unless fn throws.
pm.test.skip(name, fn)Records the test as skipped. It never fails a run.
pm.expect(value)Starts a Chai assertion on any value

Tests can be asynchronous. Return a promise or use an async function, and the test waits for it. A test whose promise never settles fails with "The test did not finish".

Common pm.expect checks:

js
pm.expect(user.name).to.equal("Ada");
pm.expect(user).to.have.property("id");
pm.expect(user.roles).to.include("admin");
pm.expect(items).to.have.lengthOf(3);
pm.expect(pm.response.code).to.be.oneOf([200, 201]);
pm.expect(user).to.deep.equal({ id: 1, name: "Ada" });
pm.expect(total).to.be.above(0);
pm.expect(user.email).to.match(/@example\.com$/);

pm.sendRequest ​

Sends another request from inside a script. This is the only way a script can reach the network.

FormReturns
pm.sendRequest(urlOrRequest, callback)Nothing. Calls callback(error, response) when done.
await pm.sendRequest(urlOrRequest)A promise for the response

The first argument is a URL as text, or a request object:

js
const response = await pm.sendRequest({
  url: "https://api.example.com/login",
  method: "POST",
  header: { "Content-Type": "application/json" },
  body: { mode: "raw", raw: JSON.stringify({ user: "ada" }) },
});

The response has the same members as pm.response. {{variables}} in the URL, headers and body are filled in. These requests appear in the Console with the source script.

pm.cookies ​

The cookies the cookie jar holds for the request's address. Read-only.

MethodWhat it does
pm.cookies.get(name)The cookie's value, or undefined
pm.cookies.has(name)true when the cookie exists
pm.cookies.toObject()All cookies as an object of name and value
pm.cookies.jar()An object whose get(url, name, callback) and getAll(url, callback) read these cookies

jar().set, jar().unset and jar().clear answer with an error: changing the cookie jar from scripts is not supported. Manage cookies in the cookie manager.

pm.execution ​

Controls what happens next.

MethodWhat it does
pm.execution.skipRequest()Pre-request only: the request is not sent, and counts as skipped
pm.execution.setNextRequest(name)In a run, jump to the request with this name (or id) after this one
pm.execution.setNextRequest(null)In a run, stop the current pass after this request
pm.execution.locationAn array of the collection name and request name; location.current is the running script's origin

setNextRequest works in the collection runner and the command-line runner. It has no effect on a single send. An unknown name ends the pass. A pass stops after 10,000 jumps, so a loop cannot run for ever.

pm.visualizer ​

MethodWhat it does
pm.visualizer.set(template, data)Renders a Handlebars template with data and shows it in the response's Visualize tab
pm.visualizer.clear()Removes the visualization

Lists ​

Headers, query parameters, path variables, form fields and cookies are lists with the same methods.

MethodWhat it does
get(key)The value for key
has(key)true when an item has that key
one(key)The whole item
all()Every item, as an array
add(item)Adds an item: { key, value }
upsert(item)Updates the item with that key, or adds it
remove(key)Removes items with that key
clear()Removes everything
count()How many items
each(fn), map(fn), filter(fn), find(fn), reduce(fn, start)Walk the items
toObject()The items as a plain object of key and value

console ​

Output goes to the Console, marked with its level.

FunctionLevel
console.log, console.dir, console.tablelog
console.infoinfo
console.warnwarn
console.errorerror
console.debug, console.tracedebug
console.assert(condition, ...)error, only when the condition is false
console.time(label), timeLog(label), timeEnd(label)log: time since time(label)
console.count(label), countReset(label)log: how many times it was called
console.group(label), groupCollapsed(label)log: prints the label, without indenting

Objects are printed as JSON. Format placeholders such as %s, %d and %o work in the first argument.

Libraries ​

Load a bundled library with require():

js
const moment = require("moment");
NameLibraryAlso available as
lodashLodash utility functions_
crypto-jsHashes, HMAC and ciphersCryptoJS
momentDates and times
uuidUUID generation
chaiAssertions (what pm.expect uses)
tv4JSON Schema validation (draft 4)tv4
ajvJSON Schema validation
handlebarsTemplates (what pm.visualizer uses)
bufferAn object with BufferBuffer
urlAn object with URL and URLSearchParamsURL, URLSearchParams
atob, btoaBase64 decode and encodeatob, btoa

Any other name throws Cannot find module. Node modules such as fs and http are not available. pm.require is not supported.

Other globals ​

GlobalWhat it is
setTimeout, setInterval, setImmediate and their clear functionsTimers. A script is finished when no timer or request is pending.
crypto.getRandomValues(array), crypto.randomUUID()Secure random numbers and UUIDs
BufferConvert between text, base64 and hex
URL, URLSearchParamsParse and build URLs
TextEncoder, TextDecoderUTF-8 encode and decode
atob, btoaBase64 decode and encode

Older Postman globals ​

Scripts written for older versions of Postman keep working.

GlobalEquivalent today
postman.setEnvironmentVariable(k, v), getEnvironmentVariable(k), clearEnvironmentVariable(k), clearEnvironmentVariables()pm.environment
postman.setGlobalVariable(k, v), getGlobalVariable(k), clearGlobalVariable(k), clearGlobalVariables()pm.globals
postman.getResponseHeader(name)pm.response.headers.get(name)
postman.getResponseCookie(name)pm.cookies.one(name)
postman.setNextRequest(name)pm.execution.setNextRequest(name)
tests["name"] = conditionpm.test
responseBodypm.response.text()
responseCode.codepm.response.code
responseTimepm.response.responseTime
responseHeaderspm.response.headers
responseCookiespm.cookies.all()
requestpm.request (read-only snapshot with method, url, headers, data)
environment, globals, dataRead-only snapshots of pm.environment, pm.globals, pm.iterationData
iterationpm.info.iteration

Not available ​

  • pm.require and Postman package libraries.
  • Changing the cookie jar from a script.
  • Files, processes, fetch, XMLHttpRequest and WebSocket.
  • Attaching a local file to a request from a script.

Next steps ​