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.
| Property | Value |
|---|---|
pm.info.eventName | "prerequest" or "test" (post-response) |
pm.info.requestName | The request's name |
pm.info.requestId | The request's id |
pm.info.iteration | The current iteration, counting from 0 |
pm.info.iterationCount | Planned 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.
| Object | Scope | Writable |
|---|---|---|
pm.environment | The selected environment | Yes |
pm.collectionVariables | The request's collection | Yes |
pm.globals | Globals | Yes |
pm.variables | Every scope, resolved; writes are temporary | Yes |
pm.iterationData | The current row of a data file | No |
pm.environment, pm.collectionVariables, pm.globals and pm.iterationData share these methods:
| Method | What 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.
| Method | What 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)stores5; an object is stored as JSON text. - With no environment selected,
pm.environmentvalues last until you close the app. pm.iterationDatais 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.
| Member | What it is |
|---|---|
pm.request.method | The HTTP method, such as "POST" |
pm.request.url | The URL object (below) |
pm.request.headers | A list of headers (see Lists); names ignore case |
pm.request.body | The body: mode is raw, urlencoded, formdata, file or graphql |
pm.request.auth | The 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:
| Member | What 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, hash | The parts; host and path are arrays of segments |
query | The query parameters, as a list |
variables | The path variables, as a list |
addQueryParams(p), removeQueryParams(p) | Add or remove query parameters |
pm.request.body:
| Member | What it is |
|---|---|
mode | Which kind of body is set |
raw | The text of a raw body |
urlencoded, formdata | Lists of fields |
graphql | An 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.
| Member | What it is |
|---|---|
pm.response.code | The status code, such as 200 |
pm.response.status | The reason text, such as "OK" |
pm.response.headers | A list of headers; names ignore case |
pm.response.responseTime | Time taken, in milliseconds |
pm.response.responseSize | Body size, in bytes |
pm.response.cookies | Cookies 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.to | Starts 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.
| Assertion | Passes 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.ok | The status is exactly 200 |
to.be.info, success, redirection, clientError, serverError | The status is 1xx, 2xx, 3xx, 4xx, 5xx |
to.be.error | The status is 4xx or 5xx |
to.be.accepted, withoutContent | The status is 202, 204 |
to.be.badRequest, unauthorized, forbidden, notFound, notAcceptable, rateLimited | The 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.xml | The 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
| Function | What 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:
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.
| Form | Returns |
|---|---|
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:
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.
| Method | What 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.
| Method | What 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.location | An 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
| Method | What 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.
| Method | What 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.
| Function | Level |
|---|---|
console.log, console.dir, console.table | log |
console.info | info |
console.warn | warn |
console.error | error |
console.debug, console.trace | debug |
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():
const moment = require("moment");| Name | Library | Also available as |
|---|---|---|
lodash | Lodash utility functions | _ |
crypto-js | Hashes, HMAC and ciphers | CryptoJS |
moment | Dates and times | |
uuid | UUID generation | |
chai | Assertions (what pm.expect uses) | |
tv4 | JSON Schema validation (draft 4) | tv4 |
ajv | JSON Schema validation | |
handlebars | Templates (what pm.visualizer uses) | |
buffer | An object with Buffer | Buffer |
url | An object with URL and URLSearchParams | URL, URLSearchParams |
atob, btoa | Base64 decode and encode | atob, 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
| Global | What it is |
|---|---|
setTimeout, setInterval, setImmediate and their clear functions | Timers. A script is finished when no timer or request is pending. |
crypto.getRandomValues(array), crypto.randomUUID() | Secure random numbers and UUIDs |
Buffer | Convert between text, base64 and hex |
URL, URLSearchParams | Parse and build URLs |
TextEncoder, TextDecoder | UTF-8 encode and decode |
atob, btoa | Base64 decode and encode |
Older Postman globals
Scripts written for older versions of Postman keep working.
| Global | Equivalent 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"] = condition | pm.test |
responseBody | pm.response.text() |
responseCode.code | pm.response.code |
responseTime | pm.response.responseTime |
responseHeaders | pm.response.headers |
responseCookies | pm.cookies.all() |
request | pm.request (read-only snapshot with method, url, headers, data) |
environment, globals, data | Read-only snapshots of pm.environment, pm.globals, pm.iterationData |
iteration | pm.info.iteration |
Not available
pm.requireand Postman package libraries.- Changing the cookie jar from a script.
- Files, processes,
fetch,XMLHttpRequestandWebSocket. - Attaching a local file to a request from a script.
Next steps
- Script cookbook: recipes that use this API.
- Scripts: where scripts go and when they run.
- Console: read script output.