pm Scripting API Compatibility¶
Vayu exposes a Postman-compatible pm scripting API for pre-request and test
scripts. Scripts run in the engine's QuickJS runtime
(engine/src/runtime/script_engine.cpp); the global pm object is bound there, and most
of its surfaces live under engine/src/runtime/pm/, one file per family. The intent is
that the most common Postman scripts paste in and run unchanged; what is not
supported is listed below.
"Postman" is a trademark of Postman, Inc. Vayu is not affiliated with or endorsed by Postman. Vayu re-implements a compatible API surface (method names and behaviour); it does not ship Postman's code or documentation. References to Postman in code and docs are nominative ("compatible with…") only.
Supported surface¶
| Group | API |
|---|---|
| Core | pm, pm.test(name, fn) - in either script, each result naming the one that made it, returning pm so calls chain, and handing a done to a callback that declares one (see below), pm.expect(value[, message]) - the message prefixes the failure, as in chai, pm.expect.fail([message]) |
| Response | pm.response.code, .status, .responseTime, .responseTimeWire, .responseTimeQueueWait, .responseSize (the body's bytes, .size().body), .headers, .json(), .text(), .reason(), .size(), plus .errorCode / .errorMessage on a transport failure - see Response timings |
| Response headers | pm.response.headers.get(name), .has(name[, value]) - case-insensitive; the value compare is strict; .each(fn, thisArg?), .all(), .count(), .toObject(excludeDisabled?, caseSensitive?), .one(name), .indexOf(name) - the read half of a Postman PropertyList, see Header methods |
| Response cookies | pm.response.cookies (array of { name, value, attrs }), .get(name), .has(name), .toObject() - read-only, see below |
| Streamed events | pm.response.events (array of { event, id?, data, dataTruncated? }), .totalEvents, .eventsTruncated - a streaming request only, see below. Vayu-specific |
| Redirect hops | pm.response.redirects (array of { code, status, url, schemeDowngrade, headers }, one per followed 3xx, oldest first) - a design send and a sequential run; absent where the chain is not recorded, see below. Vayu-specific |
| Cookie jar | pm.cookies.get(name), .has(name), .toObject(), .each(fn), .all(), .count() - the stored session for this URL; pm.cookies.jar() for get/getAll/set/unset/clear(url?) (reads and writes limited to the request's site), see below |
| Response assertions | pm.response.to.have.status(code \| reason), .statusCode(code), .statusReason(reason), .statusCodeClass(digit), .header(name[, value]), .body([expected]), .jsonBody(path?[, value]) (a lodash path), .jsonSchema(schema[, options]), .responseTime and .responseSize (a call and a chain), the pm.response.to.be.* status classes below, and pm.response.to.not negating every one of them - see Response assertions |
| Request | pm.request.url (Postman's Url object - protocol/host/port/path/hash/query, getHost(), getPath(), getQueryString(), getPathWithQuery(), getRemote(), getRaw(), query.each/map/filter/find/one/indexOf/idx, update(), addQueryParams(), removeQueryParams()), .method, .headers, .body (with .update()), .auth (basic, bearer, apikey, noauth; see Request mutation) |
| Request methods | pm.request.addHeader(), .upsertHeader(), .removeHeader(), .forEachHeader(), .getHeaders(options?), .addQueryParams(), .removeQueryParams(), .toJSON() - each the member method it names - and .authorizeUsing(), which assigns .auth; see Request methods |
| Request headers | pm.request.headers.get(name), .has(name[, value]), .upsert({key, value}), .add({key, value}), .remove(name), .each(fn, thisArg?), .all(), .count(), .toObject(excludeDisabled?, caseSensitive?), .one(name), .indexOf(name) |
| Environment | pm.environment.get/set/has/unset/clear/toObject/replaceIn, see scoped replaceIn |
| Globals | pm.globals.get/set/has/unset/clear/toObject/replaceIn, see scoped replaceIn |
| Collection vars | pm.collectionVariables.get/set/has/unset/clear/toObject/replaceIn, see scoped replaceIn |
| Merged variables | pm.variables.get(name), .has(name), .toObject(), .replaceIn(template) - the local scope first, then a bound row's bare column names; .set(name, value), .unset(name), .clear() write the local scope, never stored, see below |
| Script identity | pm.info.requestId, .requestName, .eventName, .iteration, .vu, .iterationCount - each optional, see below |
| Crypto | pm.crypto.sha256(data, encoding?), .hmacSha256(key, data, encoding?) - synchronous, see below |
| Modules | require('crypto-js') (also the CryptoJS global; a Vayu-written shim), require('uuid') (npm's uuid, vendored; callable), require('lodash') (also the _ global; npm's lodash, vendored), require('moment') (npm's moment, vendored; English only), require('csv-parse/lib/sync') (npm's csv-parse 1.2.4 sync parser, bundled; string input), require('xml2js') (npm's xml2js 0.6.2 with sax 1.2.4, bundled; also Postman's xml2Json global over it) require('chai') (npm's chai 4.4.1, bundled; a separate object from pm.expect, with chai-postman's response assertions installed), require('ajv') (npm's ajv 6.12.5, vendored; draft-07) and require('tv4') (npm's tv4 1.3.0, minified; draft-04; also the tv4 global) - any other module throws; see The require shelf |
| Send from script | pm.sendRequest(urlOrOptions, callback?) - synchronous; a settled promise without the callback; refused for agent-started runs, see below |
| Flow control | pm.execution.setNextRequest(name \| null), .skipRequest() - collection runs only, see below |
| Data rows | pm.iterationData.get(name), .has(name), .toObject() - read-only, a data-driven collection run, a send-with-row, or a data-driven load run's scripts (inline or deferred), see below |
| Base64 | btoa(binaryString), atob(base64) - globals, standard web semantics |
| Timers | setTimeout, setInterval, clearTimeout, clearInterval - globals, run before the script ends without waiting, see below |
Legacy postman |
postman.setEnvironmentVariable and the other ten pre-pm.* helper methods, each an alias of the pm.* method Postman names - see The legacy postman object |
| Legacy globals | tests[...], responseBody, responseCode, responseHeaders, responseCookies, responseTime, environment, globals, data, iteration and request, each read off the pm.* member Postman names - see Postman's legacy globals |
| Visualizer | pm.visualizer.set(template, data?, options?), .clear() - accepted and not drawn, one console warning per call - see Visualizer |
| Console | console.log/info/warn/error; with scriptEnableConsole off they stay defined and record nothing |
pm.response.headers is a plain object keyed by the lower-cased header name, not
Postman's HeaderList - but it carries get() / has() plus the read half of a
Postman PropertyList: each(), all(), count(), toObject(), one() and
indexOf(). Every one of them that takes a header name matches it the way HTTP
header names work - case-insensitively. Indexing is not, so
headers['Content-Type'] reads back undefined while
headers.get('Content-Type') works (see Header methods).
A header name the server sent twice reads as a single value with the two
folded together by ", " (RFC 7230 §3.2.2) - Postman's HeaderList would give
you two entries. That matters most for Set-Cookie, which servers routinely
send once per cookie: both cookies are there, in one string. Do not split that
string yourself - an Expires= value contains a comma of its own. Read
pm.response.cookies, which is the same header already parsed.
all() reports the object's key order, not wire order, and can never report
a duplicate the way Postman's HeaderList does - a name sent twice is
already the one folded entry above by the time any script sees it, so there is
only ever one member for all() to report for it.
Variable writes persist to the scope they target (environment / collection / globals) and
participate in variable resolution. Calling set(name, value)
on a variable that already exists updates its value and keeps the existing secret flag and
type (unless the third argument names one, below), but makes the row enabled: a script that sets a name means to use it, so a row
unticked in the variables editor is ticked again by the set (and persisted that way). A
set on a new name creates it with the defaults (not secret, enabled, type: "string").
set takes Postman's optional third argument (issue #2664, postman-collection 5.3.0), in
either of its two shapes: a string is a type, set('n', 1, 'number'), and an object
contributes type when it is a string and secret when it is a boolean,
set('token', t, { secret: true }). Anything else is ignored. string, number,
boolean and json declare their own type, object and array declare json, and any
other type name (any, default) leaves the type as it was. "secret" - as the string or as
type - marks the variable secret and leaves the type alone: Postman has no such type, this
is the reading the importer gives a variable of type: "secret". An explicit secret
boolean wins over it, and { secret: false } clears the flag. Both fields apply to a new
and to an existing row; a field the argument does not name keeps what the row has. The
text stored follows the type the set declares, so set('o', {a: 1}, 'json') stores the
JSON document. A flag reaches disk with the run, and run snapshots mask a secret from the
next run on, not within the run that set it. pm.variables.set takes the argument too,
but the local scope is never stored or masked, so a flag there has no effect.
unset(name) removes it outright, which is not the same as setting it to "": an emptied
variable is still an enabled row that {{name}} resolves to.
set refuses a name no {{name}} could read back (issue #3461): a blank name, one that
starts or ends with whitespace, or one containing { or } throws a TypeError naming the
call and stores nothing, on every scope and through the legacy postman.set*Variable
aliases. Postman stores such a name; Vayu does not, because {{ pad }} looks up pad and a
reference stops at a brace. unset accepts any name, so one already stored can be removed.
A value a script sets keeps its JavaScript type for the rest of the run, as in
Postman (issue #2529): after pm.environment.set('n', 0),
pm.environment.set('n', pm.environment.get('n') + 1) stores 1, not "01", and
get hands back the number, the boolean, the array or the object that was set, as do
toObject, pm.variables.get and pm.variables.toObject. "The run" is the scripts of
one send, the steps of a collection run, and one virtual user's steps in a load run.
What is stored, what {{name}} substitutes and what goes on the wire is the value's
string form, which is also Postman's: 1, true, 1,2,3, [object Object], null;
set(name, undefined) stores "" and reads back as undefined. A variable a run only
loaded is read from that stored text.
The exception is a row whose type is declared number, boolean or json: it keeps
casting its stored text by that type, whatever the script set. On a json row an object
or an array is stored as its JSON text (JSON.stringify(value), not [object Object]),
so it reads back as the object and {{name}} substitutes the document; a string set there
stays as given. Vayu's default "string" stands for Postman's any as well, so a set on a row of
that type is read back as set. Objects and arrays keep what JSON.parse(JSON.stringify(value))
keeps (a Date reads back as its ISO string, a nested NaN as null), and a value
JSON cannot write at all (a function, a cycle, a BigInt) reads back as its string form.
get, has and toObject read only enabled variables, so a row unticked in the
variables editor is invisible to a script until a script sets it; unset and clear
remove it regardless.
pm.variables resolves a name across every tier: the run-local scope pm.variables.set
writes (below), then a bound data row's bare column names, then environment, collection and
global - below the local scope, the same order {{name}} uses. While a data row is
bound, its bare column names answer above all three named scopes (issue #1007): get,
has and toObject check the row before the environment, so pm.variables.get("username") reads
the current iteration's username cell rather than a same-named environment variable -
Postman's own precedence for a dataset's columns. get and toObject hand back the
row's value typed, exactly as pm.iterationData.get does (a number column reads as a
number); a column the row does not carry falls through to the three scopes as an ordinary
name, not a failed bind. With no row bound, pm.variables behaves exactly as before.
pm.variables.set(name, value, options?) writes Postman's local scope (issue #2564), the top
tier, above the row: every read above answers from it first, replaceIn and
pm.sendRequest substitute it, and a {{name}} left written after composition (one it
could not answer, or any name of a request a pre-request script runs before) goes out
carrying it, so a pre-request pm.variables.set("sig", …) reaches a {{sig}} header. It
keeps the value's type as the scoped setters do. unset(name) and clear() remove local
names only. The local scope is never stored and never shown in the Variables panel; it
lives for one send (pre-request script through test script), for the whole of a
collection run, for one virtual user's iteration in a scenario load run, and for one
submission in a single-request load run with requestElements. See
scripting.md for every run
shape.
{{templates}} in scripts (pm.variables.replaceIn)¶
pm.variables.replaceIn(template) resolves {{name}} placeholders in a string
with the exact semantics the request's own URL/headers/body get when they
resolve (at compose time, or after the pre-request script for a scripted request, #2521):
scopes first (in pm.variables' precedence), then the dynamic-variable
table - so {{$guid}}, {{$timestamp}} and the {{$random*}} set generate a
fresh value per occurrence, a name nothing defines keeps its braces
($name and ordinary alike, issue #1009), and a value that itself holds
{{tokens}} resolves through them to a bounded depth, cycles left literal.
Always over the raw stored strings.
const id = pm.variables.replaceIn("{{$guid}}");
const payload = pm.variables.replaceIn('{"user": "{{userId}}", "trace": "{{$guid}}"}');
{{data.column}} resolves here too (issue #890), against the row bound to
this iteration - the same row pm.iterationData reads. It did not before, and
that made this the one template resolver in the product that disagreed with the
others about what the token means: a URL, a header and a body all bind it, and
handing the same string to replaceIn returned it with its braces still on.
// In a data-driven run, with a row carrying userId and city:
pm.variables.replaceIn("/users/{{data.userId}}"); // "/users/1001"
A bare column name resolves here too (issue #1007), at the same
above-the-environment position pm.variables.get reads it at:
pm.variables.replaceIn("{{userId}}") reads the bound row's userId cell
before it reads any scope. Unlike the reserved spelling, a bare name the row
does not carry is not an error here either - it falls through to the
scopes exactly as pm.variables.get does, which is what keeps one script's
replaceIn calls working whether or not a request happens to share a name
with a column.
Three rules come with {{data.column}} specifically, all of them the ones the
request binding already follows:
- A column the row does not have is a
TypeError, naming the token and the columns the row does have - not""and not the token verbatim. The token says the value came from the file, so a name no column answers is a mistake about the column, and both quiet answers hide it. This refusal is the prefixed spelling's alone - a bare name that misses falls through instead, as above. - With no row bound the token keeps its braces, unchanged - true of both
spellings. A plain design send has no row by design, so a shared script that
guards with
pm.iterationDatastill runs in both modes. - The prefixed
data.spelling is still not a variable scope.pm.variables.get("data.userId")and.has(...)remainundefined/false; the row's accessor for it ispm.iterationData.replaceInis different in kind - it resolves a template, and{{data.userId}}is a token template syntax has. A bare column name is not the same question (issue #1007):pm.variables.get("userId")does read the bound row - see above - soreplaceIn("{{userId}}")andpm.variables.get("userId")agree with each other the same wayreplaceIn("{{data.userId}}")andpm.iterationDatado.
{{$vu}} and {{$iteration}} resolve here too (issue #1057), to the
numbers the request beside the script was bound with - the same numbers
pm.info.vu / pm.info.iteration
carry inside a run, and 1 / 0 on a single Send, because POST /execute
binds exactly those two into every send that carries no row of its own (a
single send is a run of one, issue #994 - the same rule the table below states
for pm.info). pm.info reading undefined for both on that same Send is not
a disagreement with what replaceIn renders: the two answer different
questions. pm.info reports which iteration of which run this script is
running in, and there is no run to report; a token in a template reports what
it resolves to here, and here it resolves to what the request beside it
carried.
This is the only way {{...}} works inside a script, and that is
deliberate (issue #226, decision D16): script source is never interpolated,
because a rewrite cannot tell code from a string literal and splicing variable
values into JavaScript is an injection. replaceIn keeps values as data the
script explicitly asked to resolve.
Two timing consequences worth knowing: the map is built at call time, so a
variable the script set a line earlier resolves at once (the request's own {{}} in
the URL waits for the pre-request script to end, #2521); and the collection scope is the
script context's - the request's whole collection chain, leaf shadowing
ancestor, the same walk pm.collectionVariables does (#234). The argument must
be a string; anything else is a TypeError rather than a silently coerced
"undefined".
Scoped replaceIn¶
pm.environment.replaceIn(template), pm.globals.replaceIn(template) and
pm.collectionVariables.replaceIn(template) (issue #3133) are Postman's
per-scope forms: the template resolves against that scope's enabled values
alone, so a name only another scope defines keeps its braces. Everything that
is not a scope answers as it does for pm.variables.replaceIn - {{$guid}} and
the other generators, {{$vu}} / {{$iteration}}, and a bound row's
{{data.column}} and bare column names, which win over the scope's own value
of the same name. The run-local scope (pm.variables.set) is a scope of its
own, so it is read only by the merged form. pm.collectionVariables reads its
ancestor collections as it does everywhere else, and the argument rules and
errors are the merged form's, naming the call the script wrote.
pm.environment.set("host", "api.example.com");
pm.globals.set("host", "other.example.com");
pm.environment.replaceIn("https://{{host}}/{{$guid}}"); // "https://api.example.com/<a fresh UUID>"
pm.globals.replaceIn("{{host}}"); // "other.example.com"
pm.collectionVariables.replaceIn("{{host}}"); // "{{host}}" - not defined in this scope
Script identity (pm.info) - seven fields, all optional¶
pm.info is always an object; each field is present only when there is a
truthful value for it, so a script tests with typeof rather than assuming:
| Field | What it is | When it is undefined |
|---|---|---|
requestId |
The saved request the send is filed under | An ad-hoc request (MCP's run_request with no requestId, a load run started from a URL) |
requestName |
The request's name as the client sent it - the name in the editor, which for an unsaved edit differs from the stored row | A request with no name, and an ad-hoc one |
eventName |
"prerequest" in the Pre-request tab, "test" in the Tests tab, "setup" in a script.setup element, "teardown" in a script.teardown element (issue #1499) |
Never, for a script Vayu runs - every hook sets it |
iteration |
The 0-based pass this response was sent in - a collection run's pass, the iteration a load run's sampled response carried, or 0 for a send that bound a row, which is row 0 of 1 |
An ordinary Send, which is one request rather than a pass of anything |
vu |
The 1-based virtual user that sent it. Spans the concurrency in a collection load run; 1 everywhere else, because one request repeated is one user's iterations, and 1 for a send that bound a row, beside its iteration 0 |
An ordinary Send |
iterationCount |
How many passes that run will make - a collection run's total, and 1 for a send that bound a row, which is row 0 of 1 |
An ordinary Send, and a load run |
run |
A run summary (issue #1499): {requestsSent, errorRate, assertionsPassed, assertionsFailed}, whole run; a load run's errorRate is the report's, by the one error definition |
Every hook except script.teardown - the one script that runs after there is a run to summarize |
if (pm.info.eventName === "prerequest") {
// one shared collection-level script, branching on where it runs
}
console.log("running " + (pm.info.requestName || "an unnamed request"));
iterationCount is set by the collection runner, and by a send that bound a
row: the runner reports the run's total, and a send-with-row reports 1,
because that send is row 0 of 1 and it has said so about iteration already
(POST /execute, on both the buffered and the streaming path). A load run
is the mode that leaves it undefined - a duration-bounded run has no total to
report, and a field readable from one load run and not another is worse than
one that is never readable there at all.
iteration and vu are reported by every run, load runs included (issue #994).
That is not a reversal of issue #300's ruling but the case it excluded: what
300 refused was reporting a reservoir position as an iteration number, and¶
neither of these is one - a load run's submission claims its iteration and its
virtual user before it is sent, and both travel with the response into the
sample, exactly as the bound data row does. An ordinary Send reads
undefined for both; a send that bound a row reports iteration 0 of 1, the
same exception iterationCount makes above.
pm.sendRequest is synchronous, bounded, and not available to agents¶
Three divergences from Postman, each for a reason the sandbox forces.
It blocks, in both of Postman's forms. The send blocks and the callback
runs inline, before pm.sendRequest returns, so the call shape a Postman user
writes is unchanged and the semantics are honest. Called without a callback it
returns a promise instead, as Postman's does (#2577), already settled when it
comes back: resolved with res, or rejected with the err the callback would
have been given. So const res = await pm.sendRequest(url) works, at the top
level of a script or inside an async test.
// Pre-request: fetch a token and put it where the request will find it.
pm.sendRequest(
{
url: "https://auth.example.com/token",
method: "POST",
header: { "Content-Type": "application/json" },
body: { mode: "raw", raw: JSON.stringify({ client_id: "abc" }) },
},
function (err, res) {
if (err) {
return; // refused, DNS, or timeout - res is null
}
pm.environment.set("token", res.json().access_token);
}
);
The callback receives (err, res). A transport failure - connection refused, a
host that does not resolve, a timeout - is the network's answer rather than the
script's mistake, so it arrives as err (an Error carrying .code, e.g.
TIMEOUT) with res null. The script's own mistakes throw instead: an
unreadable argument, an unsupported body mode, the request cap, and the
capability being off. res carries code, status, responseTime,
headers with get()/has()/each()/all()/count()/toObject()/one()/
indexOf() - the same read methods as pm.response.headers - json() and
text(), a subset of pm.response with no assertion chain. status is the
reason phrase there too, so the two objects called a response do not disagree
inside one sandbox - code is the number on both. Both spellings changed
together in #1000; a script reading res.status as a number wants res.code,
and the migration
note
names the one pattern that degrades silently.
Every call is listed in the Console, as it is in Postman's (#3462): one
info line per request that was sent, naming the method, the URL, the status
(or failed: and the error code when the transfer did not complete) and the
duration, written before the callback runs. A callback that returns on err
therefore leaves a trace, and the "Fetch a token before the send" snippet logs
the failure itself. The URL has credentials blanked as an export blanks them
and scriptEnableConsole off records nothing; the line is described under
pm.sendRequest.
It is bounded three ways, and two of them throw. The request's timeout is
clamped to whatever is left of the script's own time budget (scriptTimeout,
5s by default), because QuickJS only checks its deadline between bytecode
operations - a blocking call never yields to it, so without the clamp a 5s
script would hold its thread for the whole request timeout. That timeout is
the call's own timeout option, else the one the enclosing send runs under
(the request's timeout, else the defaultTimeout setting). One script may
issue at most 10 requests; a load run's Tests script runs once per sampled
response, so an uncapped loop would turn post-run validation into minutes of
apparent hang. The third is the response body: the fetch reads at most what
the enclosing execution reads - maxDesignResponseBodyBytes for a Send's or a
collection step's scripts, maxResponseBodyBytes for a load run's deferred
Tests script - and past it the transfer is refused, arriving as the
callback's err with .code RESPONSE_TOO_LARGE rather than as a throw. It
refuses rather than handing over a prefix because res carries no truncation
flag for a script to check, so a cut body would reach JSON.parse as corrupt
input.
Agents cannot use it. Vayu's MCP target allowlist is enforced in the MCP
server against the composed URL, and by the engine against the URL a send is
about to dial (targetPolicy, #2521) - but not against a request issued from
inside a script, which passes neither. Rather than leave a hole in
a control the user configured in Settings, the engine refuses script-issued
requests unless the caller explicitly asks for them: Vayu's own Send and load
runs ask, and the MCP server never does. See
docs/engine/mcp.md.
Three body modes are supported: raw, urlencoded and formdata (#2563). The
rest of Postman's - file and graphql - are refused by name rather than sent
as an empty body; serialise the payload yourself and set the Content-Type
header. A form body's rows are Postman's array of { key, value, disabled? } or
a plain { name: value } object, encoded by the engine's own form encoders, and
sent as application/x-www-form-urlencoded or multipart/form-data with its
boundary; a disabled row is skipped. A formdata row of type: 'file' is
refused by name, since a script cannot be granted a file to read. A raw body is
sent as text/plain unless that header names another type, which always wins
(a urlencoded body's type is likewise only a default). Headers
may be Postman's header array of { key, value } or a plain object under
either header or headers; sending both spellings at once is refused rather
than resolved by precedence.
{{variables}} in the script-supplied URL, header names and values, a raw body,
a form body's field names and values and an auth credential are resolved, as the call is made (issues #1001,
1067) - so a value the same script set two lines earlier is visible, which is¶
Postman's rule and the reason an imported token-refresh script works. This is not a second pass over the request being sent: that request's own names resolve after the pre-request script ends (#2521), and nothing here revisits them. A name nothing defines keeps its braces rather than becoming empty, as everywhere else. Two header names that resolve to one name are refused rather than sent with one of the two dropped - the collision rule composition owns (issue #1051), in its words, so the script layer answers it the way every other layer does; a name resolving to nothing is refused beside it.
auth takes Postman's { type, <type>: params } shape, with the parameter block
in either spelling - the exported [{ key, value }] array or a plain object.
basic, bearer and apikey are composed by the engine's own auth resolver,
the same one POST /execute sends through, so an api key sent as a query
parameter is percent-encoded onto the URL exactly as it would be on the main
request and an Authorization header the script set itself still wins.
noauth (spelled none too) is accepted and composes nothing, so a script can
say this one request carries no credential rather than omitting the option.
Every other type - oauth2 included, whose token acquisition needs a database
this path deliberately does not carry - is refused by name rather than dropped, and so
is a type whose parameter block is absent or misspelled, a parameter name the type
does not take, and a block with no credential in it (basic with neither half,
bearer with no token, apikey with no key). Each type takes the names Postman's
own auth helper reads - basic username/password, bearer token, apikey
key/value/in - and the refusal lists them, so basic: { user, pass } fails
naming user rather than composing Basic Og== and sending it. An exported block
still reads: an entry's type member and the basic helper's showPassword are
Postman's own and send nothing. One divergence: Postman sends a basic block whose
two halves are both empty as Basic Og==; here it is refused as no credential.
A request that goes out unauthenticated because the sandbox skipped an option
is the same silent wrong request the body modes are refused to prevent.
Hashing (pm.crypto) is Vayu's own name, and it is synchronous¶
Postman exposes Web Crypto globally (crypto.subtle), whose every method
returns a Promise and which covers far more algorithms than Vayu's sandbox
implements. Rather than wear a familiar name with unfamiliar behaviour, the
surface is pm.crypto and it returns its result directly.
pm.crypto.sha256('abc'); // hex, 64 chars
pm.crypto.sha256('abc', 'base64'); // 'hex' | 'base64' | 'base64url' | 'bytes'
pm.crypto.hmacSha256(secret, canonicalString); // hex by default
Strings are hashed as their UTF-8 bytes. Pass a Uint8Array to hash bytes
directly, and ask for 'bytes' to get one back - that is what multi-round key
derivation (AWS SigV4) needs, since each round is keyed by the raw digest of the
previous one. Anything that is neither a string nor a byte-sized typed array
throws: stringifying an object would hash the text [object Object] and return
a digest that looks perfectly valid.
btoa / atob keep their web semantics deliberately - they operate on binary
strings, one byte per code unit, so btoa throws on a code point above U+00FF
instead of silently UTF-8 encoding it. A signature over quietly-substituted
bytes verifies nowhere.
Not provided: crypto/crypto.subtle under those names, TextEncoder, and
any asymmetric algorithm. pm.crypto is SHA-256 and HMAC-SHA256 only; MD5, SHA-1
and the other SHA-2 hashers are the crypto-js shelf's, see
The require shelf. The engine-side detail is in
scripting.md.
The require shelf¶
require(name) answers a fixed shelf of libraries Vayu bundles and throws
Cannot find module '<name>' for any other name; it reads no file and fetches
nothing. The shelf holds nine libraries, crypto-js, uuid, lodash,
moment, csv-parse/lib/sync, xml2js, chai, ajv and tv4, each matched
as the whole name.
crypto-js is also bound as the global CryptoJS, lodash as _ and tv4 as
tv4, so both spellings of a Postman script run (xml2Json is a global too, but a
parse function over xml2js rather than the module, as in Postman):
const CryptoJS = require('crypto-js');
const sig = CryptoJS.HmacSHA256(canonical, secret).toString(CryptoJS.enc.Base64);
It is a Vayu-written shim of crypto-js's shape, not the crypto-js library. The shim is 6 KB of JavaScript over OpenSSL's digests, so a digest is exact; the surface around it is deliberately small. Covered:
MD5,SHA1,SHA224,SHA256,SHA384,SHA512andHmacMD5...HmacSHA512(HmacSHA256(message, key)), over a string (UTF-8) or aWordArrayenc.Hex,enc.Latin1,enc.Utf8,enc.Base64, eachparseandstringifylib.WordArray(create,toString(encoder?),concat,clone)
Anything else of crypto-js reads as undefined and throws when called: AES,
DES, TripleDES, Rabbit, RC4, PBKDF2, EvpKDF, SHA3, RIPEMD160,
enc.Utf16, the progressive algo.* hashers and WordArray.random. A wrong
argument type is a TypeError, never a hash of something else. The Postman
import's notice for scripts that use an API Vayu does not run
names CryptoJS for exactly these members and for a computed CryptoJS[name],
and stays silent for the covered ones. It names them read through an alias or a
destructure too (const C = CryptoJS; C.AES, require('crypto-js').AES,
const { AES } = CryptoJS), following a name one declaration at a time: a
reassignment or a name handed through a parameter is not followed.
It costs nothing until used: the shim is evaluated the first time a script reads
require or CryptoJS, not when a script starts. First use is about 0.55 to
0.75 ms and about 22 KB of the script's memory, per execution; the engine binary
grew by 0.2 % (debug build) for it.
uuid is npm's uuid package (8.3.2), vendored unmodified, so it is the
library rather than a Vayu-written shape. The module is callable and has npm's
members on the same value:
const uuid = require('uuid');
const id = uuid(); // a v4, as in Postman
const same = uuid.v4(); // the same, spelled npm's way
const stable = uuid.v5('orders', uuid.v5.DNS);
uuid.validate(id); // true
v1, v3, v4, v5, NIL, parse, stringify, validate and version
are all there. Postman's own uuid is uuid() and uuid.v4(), drawn from
Math.random; Vayu's is a superset of that backed by a CSPRNG, so every Postman
use runs unchanged. Vayu has no uuid global, only require.
First use costs about 1.2 ms (-O2) to 2.8 ms (Debug build) per execution,
nothing until a script requires it. The import's notice does not name a
require('uuid'). The engine-side detail is in
scripting.md.
lodash is npm's lodash package (4.18.1), the whole library vendored
unmodified, and the _ global is the same object as require('lodash'):
const id = _.get(pm.response.json(), 'items[0].id');
const pages = require('lodash').chunk(pm.response.json().items, 10);
pm.environment.set('pageCount', pages.length);
Assigning _ replaces the global without loading the library, and a script's
own const _ = ... is its own. First use (a read of _ or a
require('lodash')) costs about 10 ms (-O2) to 24 ms (Debug build) and
about 800 KB of the script's memory, per execution; a script that touches
neither pays nothing. The import's notice names neither.
moment is npm's moment package (2.31.0), vendored unmodified as its
min/moment.min.js, and is reached only through require, as in Postman:
there is no moment global. It is the same build Postman's sandbox gives
require('moment') (plain moment, English only, no moment-timezone);
Postman 6.8.0 ships 2.30.1, one minor release behind:
const moment = require('moment');
pm.environment.set('expires', moment.utc().add(1, 'hour').toISOString());
pm.test('issued today', () => pm.expect(moment(pm.response.json().issued).isSame(moment(), 'day')).to.be.true);
moment.locale('fr') and every other locale fall back to English with no
error, because the build carries no locale files; moment.tz does not exist.
First use (a require('moment')) costs about 8 ms (-O2) to
17 ms (Debug build) and about 550 KB of the script's memory, per
execution; a script that does not require it pays nothing. The import's notice
does not name require('moment').
csv-parse is npm's csv-parse package (1.2.4), its sync parser bundled
into one file, and is reached as require('csv-parse/lib/sync'), the one path
Postman's sandbox exposes and the version it pins. The module is the parse
function and has no global:
const parse = require('csv-parse/lib/sync');
const rows = parse(pm.response.text(), { columns: true, skip_empty_lines: true });
pm.environment.set('firstId', rows[0].id);
The options are 1.2.4's (delimiter, columns, skip_empty_lines,
relax_column_count, auto_parse, rowDelimiter, ...), not the renamed ones
of later majors, and a malformed record throws csv-parse's own error
(Quoted field not terminated at line 3). The input is a string; a Buffer
is not supported. require('csv-parse'), csv-parse 5's csv-parse/sync and
every other path under the package throw like any name off the shelf. First
use costs about 1.3 ms (-O2) to 2.6 ms (Debug build) and about 90 KB of the
script's memory, per execution; a script that does not require it pays
nothing. The import's notice does not name require('csv-parse/lib/sync'),
and still names every other csv-parse path.
xml2js is npm's xml2js package (0.6.2), bundled into one file with the
sax (1.2.4) and xmlbuilder (11.0.1) it depends on, the versions Postman's
sandbox ships, and is reached as require('xml2js'). Postman's xml2Json
global is there too: its helper over the same library, a synchronous
parseString with explicitArray: false, trim: true and
mergeAttrs: false:
const doc = xml2Json(pm.response.text()); // <order><id>7</id></order> is { order: { id: '7' } }
require('xml2js').parseString(pm.response.text(), (err, result) => {
pm.test('the body is XML', () => pm.expect(err).to.equal(null));
});
xml2Json answers undefined for a document the parser refuses (Postman
drops the error) and null for empty input; require('xml2js') hands the
error, with sax's message, to the callback. The module is xml2js's whole
export (parseString, parseStringPromise, Parser, Builder, ...). An
async: true parse calls back through a zero-delay timer, which runs before
the script ends, so a pm.test inside the callback is recorded. The input is
a string; a Buffer is not supported, and a Parser's event emitter carries
on, emit and removeAllListeners only. xml2js/lib/parser, sax and
xmlbuilder throw like any name off the shelf. First use (either name) costs
about 16 ms (-O2) to 42 ms (Debug build) and about 900 KB
of the script's memory, per execution; a script that touches neither pays
nothing. The import's notice names neither.
chai is npm's chai package (4.4.1, the version Postman's sandbox pins),
bundled into one file with the seven packages it depends on at the versions
Postman's own bundle carries, and is reached as require('chai'). The module
is chai's whole export (expect, assert, should, use, config,
AssertionError, ...):
const { expect, assert } = require('chai');
pm.test('the order is complete', () => {
expect(pm.response.json().status).to.equal('complete');
assert.deepEqual(pm.response.json().items, [{ id: 7 }]);
});
A failing chai assertion inside pm.test is an ordinary failed test with
chai's message (AssertionError: expected 1 to equal 2). The module is a
separate object from pm.expect, which is Vayu's own implementation and is
not changed by loading chai or by chai.use(plugin). The module carries
chai-postman's response assertions, as Postman's chai does (#2751), so
require('chai').expect(pm.response).to.have.status(200) runs: each forwards
to the matching pm.response.to member, with its verdict and message, and the
target must be pm.response itself (any other value is a TypeError). Its
failure is a Vayu AssertionError, not an instance of chai.AssertionError,
as with pm.expect. pm.expect(pm.response).to.have.status(200) is still not
a form: write it with pm.response.to or this module. chai.should() adds should
to Object.prototype when called, for that script only. chai.version reads
'4.3.8', as chai 4.4.1 does everywhere (its source was never bumped). First
use costs about 5.5 ms (-O2) to 15 ms (Debug build) and about 470 KB of the
script's memory, per execution; a script that does not require it pays nothing.
The import's notice does not name it.
ajv is npm's ajv package, version 6.12.5, the version Postman's sandbox
pins, as the package's own browser bundle, and is reached as require('ajv').
The module is the Ajv constructor, callable with or without new:
const Ajv = require('ajv');
const validate = new Ajv({ allErrors: true }).compile({ type: 'object', required: ['id'] });
pm.test('the body matches the schema', () => {
pm.expect(validate(pm.response.json()), JSON.stringify(validate.errors)).to.be.true;
});
It validates draft-07; a $schema naming draft-04 or draft-06 is refused until
the script adds that meta-schema with addMetaSchema, as in Postman. Vayu has
no Ajv global, and ajv-formats and every path under the package throw like
any name off the shelf. First use costs about 21 ms (-O2) to 55 ms (Debug
build) and the first compile 10 ms to 35 ms more, with about 1,000 KB of the
script's memory held, per execution; a script that does not require it pays
nothing. The import's notice does not name it.
ajv and jsonSchema are two validators that agree on the draft-07 they
share. pm.expect(x).to.have.jsonSchema stays on the engine's own validator
(see Assertion chains), and a conformance suite
(engine/tests/script_json_schema_conformance_test.cpp over
engine/tests/fixtures/json-schema-conformance.json) runs the same schemas and
data through ajv, tv4 and jsonSchema and fails on any disagreement. These
are the answers recorded as different, and the reason for each:
| Schema and value | ajv |
jsonSchema |
Why |
|---|---|---|---|
{"format": "date"}, "2024-13-01" or "2024-02-30" |
passes | fails | ajv's default fast formats match a shape; jsonSchema checks the calendar |
{"format": "time"}, "25:00:00Z" |
passes | fails | fast takes any two digits for an hour |
{"format": "time"}, "03:04:05" |
passes | fails | ajv leaves the offset optional; jsonSchema follows RFC 3339, which requires it |
{"multipleOf": 0.01}, 0.07 or 19.99 |
fails | passes | ajv divides in binary floating point unless multipleOfPrecision is set |
A keyword jsonSchema refuses to pass on (2019-09 and later, and OpenAPI's
nullable and discriminator) is one ajv 6 ignores, so the same schema passes
ajv with the keyword left out. A propertyNames below the schema root is the
exception: ajv evaluates it, jsonSchema does not, so ajv can reject a body
that jsonSchema only discloses.
tv4 is npm's tv4 package, version 1.3.0, the version Postman's sandbox
pins, minified (the package ships no minified build). require('tv4') and the
tv4 global are one object, as in Postman, which deprecates the global in
favour of require('ajv') but still runs it:
if (!tv4.validate(pm.response.json(), { type: 'object', required: ['id'] })) {
console.log(tv4.error.message, tv4.error.dataPath);
}
tv4 is a draft-04 validator, so a draft-06 or draft-07 keyword (const,
contains, propertyNames, if/then/else, a numeric exclusiveMinimum)
is ignored and format is checked only for a name added with addFormat. It
keeps the last verdict on itself (tv4.error, tv4.missing, tv4.valid).
One difference from Postman: the shelf evaluates every library in strict
mode, so a method called detached (const v = tv4.validate; v(data, schema))
throws a TypeError, where Postman's sloppy-mode bundle writes error,
missing and valid onto the global object. tv4.validate(...) behaves the
same. First use costs about 2.7 ms (-O2) to 6.5 ms (Debug build) and about
190 KB of the script's memory, per execution; a script that touches neither
name pays nothing. The import's notice names neither require('tv4') nor
tv4.
Not on the shelf, and unshipped on purpose: cheerio, Backbone,
csv-parse at any path but csv-parse/lib/sync, moment-timezone and Node's
built-ins (crypto, fs, buffer, ...). require of one throws, the editor
underlines cheerio and Backbone as unusable, and a Postman import names the
request in meta.unsupportedScriptApis.
Timers run before the script ends, and do not wait¶
setTimeout, setInterval, clearTimeout and clearInterval are globals, as
in Postman, and every timer a script queues runs before the script ends: the
request is not sent, and a test script's results are not read, until the
queue is empty (#2577). A callback runs in due order, with the promise jobs it
queues run before the next one, and can call pm.test.
setTimeout(function () {
pm.test("checked from a timer", function () {
pm.expect(pm.response.code).to.equal(200);
});
}, 100);
The one divergence: the delay is not waited out. The queue runs on a
virtual clock, so setTimeout(fn, 5000) runs fn as soon as the work queued
ahead of it has, where Postman would wait five seconds of the script's
deadline. A setTimeout written to delay a request does not; add a Think time
element (timer.think) for that. An interval nothing clears runs until the
script's deadline stops it, which fails the script. The rules are in
scripting.md.
pm.test runs in either script, and every result says which¶
Postman's does, and so does Vayu's: a pre-request script may assert, and the
usual reason is a
pm.sendRequest
it just made - a token fetch that answered 401, a fixture that is not there -
which is worth catching before the request goes out.
Both phases' assertions are reported together, in execution order, each entry
carrying source: "pre" | "test" (issue #810). The Tests pane groups the list
under the script's name, because an assertion made before the request is a
different claim from one about the response. A failing assertion fails its
collection-run step whichever script made it, which was already true while the
list showed the test script's alone - the step was failed by an assertion
nothing named. A result restored from a run stored before that carries no
source and reads as the test script's.
Collection and folder scripts assert too, and every level is reported
(#2522), as Postman runs every event at every level. The collection's script,
each folder's, then the request's own all run, and each entry carries
scope: "collection" | "folder" | "request" beside its source. A failing
collection-level test fails the step even when the request's own tests pass,
and a throwing collection or folder script errors the step with the level
named ("Collection pre-request script failed - ..."). An entry stored before
the field carries no scope and reads as the request's.
A load test runs a pre-request script only when it is opted in inline
(config.inline, set by the Run inline switch under the script's editor
in the Elements tab, or the run's elements.scripts override; see
load-test scripts), so a check
before the request has nothing to assert on unless the script is inlined.
It returns pm, and a callback that declares a parameter gets a done
(issue #1004). Both are Postman's contract - postman-sandbox returns pm to
"make it chainable" and reads the callback's fn.length to decide the
done-style form - so pm.test(a, fn).test(b, fn) runs both, and done() /
done(err) complete or fail the test that asked for one. The zero-argument
form is untouched: it passes unless it throws.
The one divergence is what "asynchronous" can mean here. Postman waits for
a done() that arrives later; Vayu judges a done-style test when its callback
returns, and a done() left for a .then or an await runs only after the
row is written. A callback that declares done and returns without calling it
therefore fails, naming the reason - where the same script used to fail
with undefined is not a function, which said nothing about why. Calling
done() twice throws rather than overwriting the first verdict, and the throw
fails the test.
An async callback with no done is recorded as passed, as in Postman
(#2531): postman-sandbox does not await the promise either. A rejection inside
it is not lost: the job queue is drained before the script ends, and a
rejection nothing handles is a script error on the step, Unhandled promise
rejection in test "<name>": <reason>, the way Postman reports it on the run.
A rejected promise outside any test reads Unhandled promise rejection:
<reason>, and one the script catches is no error.
Assertion chains (pm.expect)¶
Chai-style chains on a pm.expect(value) expectation, implemented in the QuickJS
runtime and held to every public member of chai 4.4.1's expect API
(engine/tests/fixtures/chai-conformance.json: a snippet that must pass, one
that must fail and the shape of its message, per member, each checked against
the real package; ChaiConformanceTest runs them, and fails when a member
listed below has no row). pm.response.to is a separate object: it
answers only to the response assertions in the table above and the status
classes below, not to these:
.to.equal(v) / .eq(v) / .equals(v) .to.eql(v) / .eqls(v) .to.deep.equal(v)
.to.exist / .exists .to.be.true .to.be.false
(.true / .false are strict, `=== true` / `=== false`: `1`, `'true'`
and `{}` are not `.true`, `0`, `''` and `null` are not `.false`;
`.ok` is the truthy check)
.to.be.null .to.be.undefined .to.be.ok .to.be.empty
.to.be.NaN .to.be.finite
(.finite is a number that is finite: the string '1' is not)
.to.be.arguments / .Arguments (a function's own `arguments` object)
.to.be.extensible .to.be.sealed .to.be.frozen
(what Object.isExtensible / isSealed / isFrozen answer, so a
primitive is sealed and frozen and is not extensible)
.to.be.above(n) / .gt(n) / .greaterThan(n)
.to.be.below(n) / .lt(n) / .lessThan(n)
.to.be.at.least(n) / .gte(n) / .greaterThanOrEqual(n)
.to.be.at.most(n) / .lte(n) / .lessThanOrEqual(n)
.to.be.within(start, finish)
(each takes a number or a Date on both sides, never a coercion;
within takes both bounds in)
.to.be.closeTo(v, delta) / .approximately(v, delta) .to.be.oneOf([…])
.to.be.a(type) .to.be.an(type) .to.be.instanceOf(Ctor) / .instanceof(Ctor)
(.a / .an are also words: .to.be.an.instanceof(Ctor))
.to.have.property(name[, v]) .to.have.nested.property('a.b[0].c'[, v])
.to.have.own.property(name[, v]) / .ownProperty(name[, v]) / .haveOwnProperty(name[, v])
.to.have.ownPropertyDescriptor(name[, d]) / .haveOwnPropertyDescriptor(name[, d])
(name alone moves the chain's subject to the property's value,
or its descriptor; with v, or under .not, the subject stays
the object)
.to.have.length(n) .to.have.lengthOf(n)
(also the start of a chain: .length.above(n) and
.lengthOf.within(a, b) compare the length, a Map's or Set's size)
.to.have.keys(…) / .to.have.key(k) .to.have.members([…])
.to.have.any.keys(…) .to.have.all.keys(…)
.to.include.keys(…) / .to.contain.keys(…)
.to.include.members([…]) .to.have.ordered.members([…])
.to.include.ordered.members([…]) .to.contain.oneOf([…])
.to.include(v) / .includes(v) / .contain(v) / .contains(v) .to.have.string(sub)
.to.include({ a: 1 }) .to.have.own.include({ a: 1 })
.to.nested.include({ 'a.b[0]': 1 })
.to.match(/regex/) / .matches(/regex/) .to.satisfy(fn) / .satisfies(fn)
.to.throw([Ctor | msg | /regex/][, msg | /regex/]) / .to.throws(…) / .to.Throw(…)
(a string or pattern is matched against err.message)
.to.respondTo(name) / .respondsTo(name) .itself.to.respondTo(name)
.to.change(obj, 'prop') / .changes(…) .to.increase(obj, 'prop') / .increases(…)
.to.decrease(obj, 'prop') / .decreases(…) .and.by(n)
(each takes a function, or an object and a property name, calls
the target once and compares before and after; by(n) is how far)
.to.have.jsonSchema(schema[, options])
(chai-postman's, draft-07: see jsonSchema below)
.to.not … (sets the negation for the rest of the chain; a second
.not in one chain is a no-op, not a double negative)
.deep … (deep comparison for equal / include / property / members / oneOf)
.nested … (dotted or indexed path for property and include)
.own … (own properties only, for property and include)
.any … .all … (any: one of the keys is enough; all, the default, wants them all)
.ordered … (members by position)
.itself … (respondTo on a function's own members, not its prototype's)
.and … (continues a chain; flags, `not` included, carry over)
.that … .which … .is … .has … .been … .with …
.does … .but … .also … .of … .same … .still …
(chai's language chains: they assert nothing and read as
English, and carry the chain's flags like .and)
The table holds a row for each of chai's 96 members of Assertion.prototype
and for expect.fail, and for nothing else: the test holds the rows to the
names read off the package in both directions, so a row deleted, renamed or
added for a member chai does not have fails by name. The pm.response.to rows
are held to chai-postman's names the same way, and to the response assertions
and status classes this page lists.
The chain words above are a vocabulary, not a route. The dotted spellings
in that table are how the completion popup offers each matcher, not the only
way to reach it: to, be, have, at, and, all, not, deep, nested
and every language chain are members of the same expectation and each hands it
back, so any of them may precede any matcher, exactly as in chai. All four of
these run, and the editor accepts all four (#1209):
pm.expect(code).to.be.equal(200); // `be` asserts nothing
pm.expect(token).to.be.a('string').and.match(/^prefix_/); // matcher after .and
pm.expect(scope).to.be.a('string').and.not.empty; // `not` after .and
pm.expect(value).not.to.equal(1); // `not` before .to
Terminal getters (.to.be.true, .to.exist) return the chain too, so a chain
continues past one: .to.be.true.and.equal(1).
.property(name) moves the subject to the property's value (#2524), as in
chai, so what follows asserts on the value: expect({id: 1}).to.have.property('id')
.that.is.a('number') passes and .that.is.a('string') fails with
Expected type number to be string. .nested.property('a.b') moves it to the
value at the last path segment, the failure message and the deep / nested
flags carry over, and the value is read once, so a getter runs once. Two forms
keep the chain they were called on: .property(name, value), which already
compared the value, and .not.have.property(name), which asserts absence and
has no value to move to. A property that is missing fails the assertion before
any retarget. A primitive is read through its wrapper, as chai reads it
(#2582): expect('abc').to.have.ownProperty('length') and
.property('length', 3) pass, expect(5).to.have.ownProperty('x') fails, and
null and undefined have no property at all.
equal is ===; eql (and deep.equal) is deep. So
expect({a:1}).to.equal({a:1}) fails - different references - and
expect({a:1,b:2}).to.eql({b:2,a:1}) passes: key order is not part of deep
equality. include, property(name, value), members and oneOf compare
strictly too, unless a deep appears in the chain. The one place the two
libraries Vayu answers for disagree is the pair +0 / -0: eql separates
them (deep-eql's 1/x rule) while the response assertions in the table above
compare them equal, because chai-postman runs on lodash _.isEqual.
include answers by the target's type, as chai does: a substring of a
string (a boxed String too), an element of an array, a member of a Set, a
value of a Map (never a key), and on any other object a subset match, every
key of the argument on the target with an equal value. A Set or Map compares
by SameValueZero, what Set.prototype.has answers, so NaN finds NaN, and
deeply under deep: expect(new Set([{a:1}])).to.include({a:1}) fails and
.deep.include({a:1}) passes. Any other pair is chai's own refusal, an
AssertionError in both polarities: expect({a:1}).to.include('a') and
expect(5).to.include('x') fail with or without .not. Vayu is stricter than
chai in two places, each because chai's answer there is a silent non-assertion
or a quiet wrong verdict: an expectation carrying no own enumerable keys is
refused (to.include({}), a Date, a RegExp, a function - chai passes all of
them, in both directions, having compared nothing); and a getter that throws is
reported rather than read as "these differ".
Quantifiers, order and ownership are flags the matcher after them reads (#2528),
as in chai. any and all (the default) say how many of the keys are
enough, and the later word wins. Reading include or contain - as the call
include(x) or as a chain word - sets chai's contains, which turns keys and
members into "at least these" and makes oneOf ask whether the target
contains a candidate (a substring, an element). ordered makes members
compare by position, and include.ordered.members checks a prefix. own makes
property and include({...}) look at own properties only, nested.include
reads each key as a path, and nested together with own is a TypeError, as
chai refuses it. .keys() with no names is a TypeError too: include.keys([])
would pass for every target having compared nothing. One plain-object argument
stands for its own keys (keys({a: 1}) asks for a, chai's Object.keys). On
a Map the keys are its keys and on a Set its members, compared as values
rather than names: new Map([[1, 1]]) has the key 1 and not '1', and
deep.keys compares them deeply. .length and .lengthOf
are a call (length(3)) and a chain (length.above(2)), and the ordering
matchers after one compare the length - a Map's or Set's size. A target with
no length fails as chai's to.have.property('length') does, an
AssertionError that .not does not reverse:
expect(3).to.not.have.length.within(1, 2) fails. length
directly after a chainable method (include, a, length itself,
responseTime) is a TypeError, as chai's length guard makes it; write
lengthOf there.
.a() and .an() name a value the way chai's type-detect does: string,
number, boolean, null, undefined, array, object and function, and
for anything else the lower-cased tag - date, regexp, map, set, error,
promise, symbol, bigint. Both are chai's chainable methods: read without a
call they hand the chain on, so .to.be.an.instanceof(Array) runs, and the call
returns the chain, so .an('array').that.includes(1) does too.
change, increase and decrease call the target exactly once, reading
the subject before and after, and a .by(n) that follows judges that same
measurement. The subject has to be a function, or an object holding the named
property; increase and decrease need a number to start from. Only a number
measures for by, so a numeric string counts as no move where chai would
coerce it. respondTo asks a function about its prototype unless itself
comes first, and refuses a function with no prototype (an arrow function) the
way chai's TypeError does, because answering "does not respond" would make
.not.respondTo pass for it.
jsonSchema(schema[, options]) is chai-postman's, on pm.expect(value) and
on pm.response.to.have, and is checked by the engine's draft-07 validator
rather than ajv. A failure names the first path that broke the schema
(at /items/1/id: ...). A keyword the validator cannot evaluate - one from JSON Schema
2019-09 or 2020-12 (unevaluatedProperties, prefixItems,
dependentSchemas, ...), OpenAPI's own (nullable, discriminator), or a
propertyNames nested below the schema's root (in properties, items, an
allOf member or a $ref target; ajv evaluates it there and the engine's
validator cannot, #2729) - fails
the assertion in both polarities, naming the keyword, because ignoring it
makes the schema looser anywhere but inside not, where it makes it stricter:
neither verdict could be trusted, so neither is given. options is ajv's and is accepted and not read.
format is checked for date, time, date-time, ipv4, email, uri,
uuid, hostname and ipv6; every other format (uri-reference, regex,
int64, ...) is an annotation, as the specification allows, so a schema that
relies on one of ajv's other formats passes values it would fail in Postman. The
checks are the engine's own, not ajv's, and are stricter or looser than ajv in
the corners: email is a dot-atom local@hostname (no quoted local part, no
bracketed address literal), uri is an absolute RFC 3986 URI checked for a
scheme and its character set rather than the grammar of the authority, and
uuid is the hyphenated form without a urn:uuid: prefix. The body of pm.response.to.have.jsonSchema is read as
JSON.parse reads it, so 1.0 is the integer 1. require('ajv') is on the
shelf and is the real library; the data it and jsonSchema answer
differently are pinned by a conformance suite.
Where the vocabulary stops matching chai. Each of these is a difference in what is accepted or how it is reported, never a quiet pass:
expect.fail(actual, expected, message, operator)is refused by name; onlypm.expect.fail([message])exists.- chai's per-matcher trailing
msgargument (.equal(1, 'why')) is accepted and not read. The message goes inpm.expect(value, 'why'), which prefixes every failure of the chain. - chai-postman's
postmanRequest,postmanResponseandpostmanRequestOrResponseare not implemented - there are no collection-SDK objects to recognise - and neither ispm.expect(pm.response).to.have.status(...): onpm.expectthe response assertions live onpm.response.to, andrequire('chai').expect(pm.response)carries them (the shelf). Each throws aTypeErrornaming the member. - A name outside this list throws, which chai would too for a misspelling but not for a plugin's member; there is no plugin interface.
Which wrong-typed values are an AssertionError and which a TypeError.
Where chai checks a type as an assertion of its own, so does Vayu, in both
polarities (#2582): a members target that is not an array
(expect('foo').to.include.members(['f'])), a length read off a target with
none, and an include pair chai has no rule for (expect({a:1}).to.include(1)).
What stays a TypeError is a call that was itself malformed: a missing or
wrong-typed argument (members(1), above()), keys() with no names, nested
with own, and the ordering matchers' refusal of a value that is not a number
or a Date (expect('5').to.be.above(3)). chai raises an AssertionError for
each of these; the TypeError is deliberate, the same choice
pm.response.to.have.body made for a wrong-typed argument (#998), because
nothing was asserted. Both throw, so a test fails either way; e.name is what
differs.
The second argument is chai's failure message. pm.expect(value, 'context')
prefixes context: to whatever the failing matcher reports, so an assertion
that runs more than once says which value it was about:
Non-strings are coerced and undefined / null mean no message, both as in
chai. Assertion failures carry it; a malformed call (.to.be.above() with no
argument) reports its own misuse unprefixed.
A failed assertion is an AssertionError, as in chai - both from
pm.expect and from pm.response.to:
pm.expect(1).to.equal(2);
// AssertionError: Expected 1 to equal 2
try { pm.response.to.have.status(200); } catch (e) { e.name === 'AssertionError'; }
QuickJS has no AssertionError class, so this is an Error carrying that
name: instanceof Error holds, e.stack is the same one a native throw
gets, and there is no AssertionError global to reference (chai's lives on the
chai module; require('chai') is that module, a separate
object, so a pm.expect failure is not an instance of its AssertionError:
test e.name). A mistake in the script text stays a
TypeError - a matcher called with no argument, a name nothing implements -
because nothing was asserted, the call itself was wrong. That covers
property-style members too (issue #999): pm.expect(x).to.be.NaN is an
expression statement, so an unimplemented name used to evaluate to undefined
and report PASS whatever the value was. Every name the chain does not carry -
a typo, or one of the chai-postman members Vayu lacks (.postmanRequest,
.postmanResponse, .postmanRequestOrResponse) - now raises a TypeError
naming itself. So does a name read off a matcher or a chainable method
(#2528): a matcher is a call, so .within.foo and .equal.name are refused,
and after include, length or a only the chain's own members resolve, so
.include.name is refused rather than answering the function's own name.
pm.expect.fail([message]) throws that same AssertionError on demand
(issue #1004), defaulting to chai's own expect.fail() text. Inside a
pm.test it fails that test; outside one it aborts the script, the way any
uncaught throw does. What it changes there is the shape of the verdict, not
whether the script stops: the run is reported as a failed assertion carrying
this message, rather than as the TypeError a misuse reports.
chai's fail(actual, expected, message, operator) form is not supported -
this AssertionError has nowhere to carry the two compared values, so a second
argument is refused by name rather than actual being reported as the failure
text.
have.keys asserts exactly those keys. Map / Set / typed arrays are
reported unequal by eql rather than compared (their contents are not
properties); Date compares by instant, RegExp by pattern; a cycle
raises a RangeError at the depth it closes (#959), naming the pair of
objects the walk met twice, and a merely very deep structure raises a different
RangeError after 64 levels - a backstop with its own message, not the same
finding reported late. A throw the
comparison runs into is the verdict (#1048) - a key, an array element or an
array length behind a getter that throws, an overridden toJSON / toString
on the Date and RegExp sides, and the values include, oneOf, members,
keys, property, empty and length read before they compare, all reach the
test as the script's own error rather than as a difference. Chai reports a
difference for some of these, which under .not is a pass; a test that cannot
read its subject has not passed.
code is the number, status is the reason phrase¶
Postman splits the status line in two and Vayu answers the same split:
pm.response.code is 200, pm.response.status is "OK" - the phrase the
status line carried, or the registered text for the code where the wire had
none (HTTP/2 carries no phrase at all). pm.response.reason() answers the
same string, and pm.response.to.have.status(...) compares a number against
the code and a string against the phrase.
Vayu spelled status as the number until #1000, so this is a break for a
script written against the old spelling rather than against Postman.
docs/engine/scripting.md carries the migration
note,
including the one legacy pattern - arithmetic on status - that goes on
compiling, stops matching, and reports nothing.
Response timings, and the two error fields¶
Postman reports one duration; Vayu's response carries three numbers and, when the transfer failed, two fields naming why:
| Property | What it is |
|---|---|
responseTime |
What the caller waited - submission to completion, queue wait included. The one a ported Postman script reads, since it is the one carrying Postman's name |
responseTimeWire |
CURLINFO_TOTAL_TIME less any wait for a connection slot: DNS, connect, TLS, send and receive. What the server and the network cost, with none of Vayu's own queue in it |
responseTimeQueueWait |
responseTime minus responseTimeWire, clamped at zero - the generator's queue plus libcurl's wait for a connection slot. Near zero on a single send, which has nothing to wait for |
errorCode |
The transport failure's code (TIMEOUT, CONNECTION_FAILED, TOO_MANY_REDIRECTS, …), as pm.sendRequest's err.code spells it |
errorMessage |
That failure's message |
The two error fields are absent on a transfer that completed, rather than
empty or null - the same absent-not-empty rule pm.response.events follows -
so if (pm.response.errorCode) is the test, and reading errorMessage without
it is a guess about a sibling field.
The two extra timings are there because a load run's latency and the engine's
own overhead are different questions: responseTimeWire is libcurl's view of
the transfer, and the gap between the two is what the generator's queue cost.
An assertion on responseTime under load is an assertion on both.
Response status classes (pm.response.to.be)¶
Getters, so the paren-less form is the assertion:
.to.be.ok (200 only) .to.be.success (2xx)
.to.be.info (1xx) .to.be.redirection (3xx)
.to.be.clientError (4xx) .to.be.serverError (5xx)
.to.be.error (4xx or 5xx)
.to.be.accepted (202) .to.be.withoutContent(204)
.to.be.badRequest (400) .to.be.unauthorized (401)
.to.be.unauthorised(401) .to.be.forbidden (403)
.to.be.notFound (404) .to.be.notAcceptable (406)
.to.be.rateLimited (429)
.to.be.json (body parses as JSON)
.to.be.withBody (body is not empty)
pm.response.to.not is the negation of every member of pm.response.to: the
have calls and the be getters above, pm.response.to.not.be.ok and
pm.response.to.not.have.status(500) alike (#2528). It sets the negation as
.not does on pm.expect - not.not is still negated - and, as in
chai-postman, negates each of the checks an assertion makes on its own, in
order, so a two-step form fails once the first step holds: not.have.header(
'X-Count', '6') fails when X-Count is there at all, and not.have.jsonBody(
'id', 2) fails when id exists, whatever its value. That is Postman's verdict;
reading it as "the pair is not equal" would pass an assertion Postman fails.
ok narrowed to status 200 only (#998) - it used to match any 2xx, the same
class success still matches. A script that asserted .ok meaning "any 2xx"
should assert .success instead; a script that meant "200 exactly" needed no
change. Postman's own named statuses (accepted, withoutContent, badRequest,
notFound, ...) match by reason phrase as well as by code; Vayu's stay
code-only. Two of chai-postman's phrases are ones no server sends -
unauthorised wants Unauthorised and notAcceptable wants Acceptable - so
in Postman those two fail against a real 401 and 406, where Vayu passes on the
code. statusReason(reason) is the exact-phrase check for a script that wants
it, and statusCode(code) takes a number or a numeric string as chai-postman's
Number(code) does.
have.body's substring form is gone (#998). A string argument now has to
equal the body exactly, not merely appear in it - .to.have.body(sub) written
for "the body contains sub" should become .to.have.body(new RegExp(sub)).
It takes chai-postman's three argument forms and no others: a string compares
equal, a regular expression is run against the body with its own test, and a
plain object is deep-equalled against the parsed body - which reports
Response body is not valid JSON when the body does not parse. A number or a
boolean is a TypeError naming what was passed. With no argument have.body()
asserts that the response has a body (the call form of to.be.withBody).
.have.jsonBody(path, value) also started comparing value, which it used to
accept and ignore - a script relying on the old no-op should not pass an
argument it does not want checked. The path is lodash's, as chai-postman
reads it with _.has and _.get (#2528): a.b[2].c, a['b'].c, a key the
root holds whole ({"a.b": 1} answers a.b), and [0].id on a body that is an
array. Each step is an own property, so an array's length is reachable and
map is not.
have.status refuses a code that is not a whole finite number (#1048).
status(200.5) used to be truncated to 200 and pass against a 200; a
fractional or NaN expectation is a mistake in the script text - no response
can carry such a code - so it raises a TypeError naming what was written
rather than a verdict naming the status that arrived. Postman would report a
failure here too, so no assertion that passes there fails here.
responseTime and responseSize are a call and a chain (#2528), as in
chai-postman: pm.response.to.have.responseTime.below(200) is pm.expect's
below on the time, and responseTime(120) asserts it equals 120. A name
the chain does not carry is refused naming pm.response.to.have.responseTime,
the chain the script wrote, not pm.expect(...).
responseSize is the body and the header together, which is what chai-postman
adds up; pm.response.responseSize, the property, is the body alone. Under
not the call form fails whatever it is given - chai-postman's own first check,
that the measure is a number, always holds, and Postman's verdict is kept.
Every other name under pm.response.to throws a TypeError naming the
chain - a misspelling, or an idiom Vayu does not implement. This is deliberate:
a paren-less assertion is an expression statement, so a name that merely
evaluated to undefined would report PASS against a broken API.
Streamed events (pm.response.events) - Vayu-specific¶
Postman has no equivalent: it has no streaming request type, so nothing in its
pm surface names one. A request sent with the Event stream setting on gets
three extra properties on pm.response, and the post-request script runs once,
after the stream has terminated. A reply that is not text/event-stream (a
JSON error, NDJSON) keeps its body, so pm.response.text() and json() read
it; an event stream's text() is "":
const events = pm.response.events || [];
pm.test('the stream said done', function () {
pm.expect(events.some(function (e) { return e.event === 'done'; })).to.be.true;
});
Buffered, not live, and that is structural rather than a limitation of this release. The post-request script runs once the stream has ended, and runs to completion - its timers and promise jobs included - before anything is reported, so there is no "later" in which a per-event callback could run while the stream is still arriving. A script sees the retained list, once.
pm.response.totalEvents and pm.response.eventsTruncated come with it. The
list is bounded by the engine's sseMaxStoredEvents, so a script that means to
assert over the whole stream has to check eventsTruncated first; counting a
prefix would otherwise report a wrong number with complete confidence.
A load run's deferred tests script reads the same three. POST /runs
with "stream": true samples its streaming responses the way it samples any
other, and the deferred script replays against those samples - so the three
properties mean there what they mean in design mode, with two differences. The
list is rebuilt by reparsing the sample's stored body and is bounded by
sseMaxStoredEvents, while totalEvents is the count taken off the wire, so
it stays right about a stream the stored body is only a prefix of. And there is
no per-sample end reason: whether a stream ended by a cap is a run-level fact,
reported once as stream.capped.
All three are absent on an ordinary response rather than empty, so
typeof pm.response.events === 'undefined' distinguishes "not a stream" from "a
stream that produced nothing" - the same absent-not-empty rule
pm.iterationData follows. Full reference in
scripting.md.
Redirect hops (pm.response.redirects)¶
Vayu-specific; Postman has no equivalent. Postman's sandbox exposes the final
response only, so a script that is lifted into or out of Postman should not
depend on this property. Each entry is a followed 3xx response, oldest first:
code (number) and status (reason phrase) named as on pm.response, url
(the request that hop answered, an auth query parameter's value blanked),
schemeDowngrade (true for an https request redirected to http, the one
hop a header-placed API key crosses in clear text) and headers, shaped as
pm.response.headers is.
pm.test('no redirect left https for http', function () {
const leaked = (pm.response.redirects || []).filter(function (hop) {
return hop.schemeDowngrade;
});
pm.expect(leaked).to.be.empty;
});
An empty array means the send was not redirected (or ran with Follow redirects
off). The property is absent - typeof is 'undefined' - on a load run's
scripts and a streamed request's, where redirects are followed but not recorded,
so redirects.length === 0 cannot pass over a chain nobody saw. Full reference in
scripting.md.
Response cookies (pm.response.cookies)¶
pm.response.cookies.get('session'); // value, or undefined
pm.response.cookies.has('session'); // boolean
pm.response.cookies.toObject(); // { session: 'abc' }
pm.response.cookies[0].attrs; // ['Path=/', 'HttpOnly'] - raw chunks
An array of { name, value, attrs } in wire order, parsed from that one
response's Set-Cookie, one received line per cookie (a comma inside a value
does not split it, #2460; a response that kept no lines falls back to splitting
the folded header). It is not Postman's CookieList and its entries
are not postman-collection Cookie objects: there is no key, no path,
no secure, no expires, because those fields would restate the attribute
string rather than report what the engine holds - the jar itself is
pm.cookies. attrs is that string, split on ;
and untouched otherwise.
Three divergences worth knowing before porting a script:
- This is the response, not the session. What will actually be sent next
time is
pm.cookies; this reports what this one response set, expired cookies included. - Names are case-sensitive, unlike header names -
get('SESSION')does not find thesessioncookie. RFC 6265 says they differ, and answering anyway would be a wrong value dressed as a right one. - A repeated name answers with its last value from
get()/toObject(), which is the one a browser's jar would keep, while the array still lists both.
The parse is shared with the response Cookies tab in the UI through
engine/tests/fixtures/set-cookie-conformance.json (the tab parses each
received line with parseSetCookieLine, #2460), so a cookie cannot read one
way on screen and another in a script.
The cookie jar (pm.cookies)¶
pm.cookies.get('session'); // value, or undefined
pm.cookies.has('session'); // boolean
pm.cookies.toObject(); // { session: 'abc' }
pm.cookies.each(function (cookie) { /* ... */ }); // whole cookie objects
pm.cookies.all(); // array of cookie objects
pm.cookies.count(); // number
The read half of Postman's pm.cookies, over a jar the engine keeps for
design-mode requests: a Set-Cookie on one request is sent on the next one
automatically. What these answer is matched against this request's URL -
domain, path, Secure and expiry - so they report what will go on the wire and
not everything stored. each, all() and count() are Postman's CookieList
reads, over that same matched set, read fresh on every call.
A cookie object - what each, all(), jar().getAll() and jar().set's
callback all hand back - carries name and key (same value, both spellings),
value, domain, path, secure, httpOnly, hostOnly, session
(booleans), and expires (a Date, or null for a session cookie). Postman's
maxAge and its unmodelled extensions are not modelled - the jar does not
keep them. Full field list in
scripting.md.
The write half is pm.cookies.jar(), Postman's own jar object:
const jar = pm.cookies.jar();
jar.set(pm.request.url, { name: 'session', value: token }); // or (url, name, value)
jar.get('https://api.example.com/', 'session'); // value, or undefined
jar.getAll('https://api.example.com/'); // every cookie that URL would carry
jar.unset('https://api.example.com/', 'session');
jar.clear('https://api.example.com/'); // that URL's cookies
jar.clear(); // this environment's jar
Every method names only the request's own site and the hosts the script has
called through pm.sendRequest. get and getAll answer undefined / [] for
any other URL, and set, unset and clear(url) store or remove nothing, each
with a console warning. See the divergences below. In a pre-request script, where
the request's URL still holds its {{name}}s (#2521), its site is that URL as the
variables resolve it at the call.
Every method is URL-scoped and takes an optional trailing callback, invoked
inline, that carries what the call did: get the value, getAll the array,
set the stored cookie object (domain/path filled in from the URL), unset
the removed name, clear nothing. Each is also the method's return value. A
written cookie's domain and path default from the URL, and it is then
matched by exactly the rules a received cookie is.
Divergences from Postman:
- No flat
pm.cookies.set(name, value). Only thejar()form ships: a written cookie needs a URL to take its domain and path from, which is why Postman's own write half lives on the jar object. jar.getandjar.getAllare limited to the request's site (#2358). Postman's jar answers for any URL; here a URL answers only when its host is equal to, a subdomain of, or a parent domain of the request's host (or of a host the script has called withpm.sendRequest), and anything else givesundefined/[]plus a console warning naming the host. The jar holds the sessions of every host the environment has talked to, and a collection's script should not be able to read them all. A redirect's target is not seen, so it does not widen the scope. Details in scripting.md.jar.set,jar.unsetandjar.clear(url)are limited to the same site (#2631). A write whose URL is outside it is refused with a console warning and stores or removes nothing, and so is asetwhose cookiedomainis outside it. RFC 6265 section 5.3 has a user agent ignore aDomainthat does not domain-match the request host; Postman's own jar does not apply that rule to a script's write, and here it is checked in both directions like the read scope. A single-label domain (.com,test) is also refused unless it is the request's own host, because it would reach every site under it; no public-suffix list is applied (#2731), soco.ukstill passes. The call still returns and calls its callback as a stored write would. A script that logs in across hosts bysetting a cookie with a foreigndomainstops working: call the other host throughpm.sendRequestfirst and it is in scope. Details in scripting.md.- A write is applied after the transfer it was made before, not the moment it is called - so it rides that request and cannot be lost when the response's cookies are captured. Details in scripting.md.
jar.clear(url)matches Postman - it removes every cookie that URL would have carried, which isunsetwith no name to narrow it.jar.clear()with no URL is Vayu's own and empties this environment's jar, because the environment is Vayu's scope unit. A URL the engine cannot parse is refused rather than cleared as a wipe matching nothing.getAllandpm.cookies.all()return a plain array, not Postman'sCookieList- the same divergencepm.response.cookiesalready makes, for the same reason: an array is what every other cookie surface here, and a plainfor (const c of ...), treats it as.expirestakes aDate, a date string, or a whole number of seconds since the epoch - all three read the way the same script's ownnew Date(...)would, since the Date and the string are parsed by QuickJS's ownDaterather than a parser written into the engine.- Scope is the environment, not the domain-with-permission model Postman uses. One jar per environment plus one for "no environment", in memory only, clearable in Settings → General → Cookies.
pm.sendRequestshares the jar with the request around it, so logging in from a pre-request script leaves the session where the real request finds it.- Load runs have no jar, and every read and write here throws there rather
than answering
undefined- see scripting.md.
Flow control (pm.execution)¶
pm.execution.setNextRequest('Checkout'); // run that request next
pm.execution.setNextRequest(pm.info.requestId); // the same jump, by id
pm.execution.setNextRequest(null); // end this iteration, start the next
pm.execution.setNextRequest('null'); // the quoted stop form, read the same way
pm.execution.skipRequest(); // pre-request only: do not send this one
Both are available only inside a collection run, and outside one they throw a sentence naming why rather than being ignored - a single Send has no next request, and a load run's test scripts run after the run has finished, against responses already recorded.
Both target spellings Postman accepts work: a request's name, and the id a
script reads off pm.info.requestId. So does the quoted stop form
setNextRequest('null') - with one stated precedence, which is a divergence
only in the sense that Postman has no answer for it: a run that carries a
request actually named null jumps to that request rather than stopping.
Divergences from Postman:
- An unresolvable target fails the step, naming it. A target no request in
the run answers to by name or by id, and a name two of them share, are both
errors that end the iteration, whatever
stopOnErrorsays; Postman resolves an ambiguous name to whichever it finds. - A redirect from a script that then threw is ignored: the step is
erroredand the iteration walks to the next request in order. Postman's order for that case is unverified, so Vayu takes the rule that never runs a sequence the script did not finish deciding on. - A cycle is bounded. Two requests pointing at each other run forever in
Postman's runner; here the iteration is cut off by
maxStepsPerIterationand the failure names the steps that were looping. - A skipped step is reported as
skipped, never as a pass, in the step list and in the run summary alike.
Matching Postman since issue #2526: a script error no longer ends the
iteration. A pre-request script that throws still sends its request, a test
script that throws (a top-level pm.response.to.have.status(200) on a 500
included) is reported on the step, and the run moves on to the next request -
Postman's and Newman's default with stopOnError unset. The step is errored
with the script's message, never passed. The run option stopOnError: true
restores the old rule (Newman's --bail shape); the Run Collection dialog's
Stop the iteration on a script error switch and run_collection's
stopOnError argument set it. A request that got no response at all is
the same: its step is errored with the transport error and the iteration
carries on, as in Postman, so a later step that reads the missing response
errors on its own row. A run whose iterations an error cut short says how many steps
that cost as stepsNotRun.
Details, including every case that throws, are in scripting.md.
Data rows (pm.iterationData)¶
pm.iterationData.get('username'); // this iteration's value for that column
pm.iterationData.has('coupon'); // whether the row carries that column
pm.iterationData.toObject(); // the whole row
A collection run can be given rows - the app parses the CSV, TSV, JSON or
JSONL file and sends them inline on the run payload; the engine never opens a
file. Row i % rows binds to iteration i, so iterations above the row
count wraps.
A single send can bind one row as well: the request builder's Send-with-row
caret and MCP's run_request both take one row on POST /execute, which is
what makes a script that reads pm.iterationData testable without starting a
run. pm.info.iteration is then 0 of 1 - the send is row 0 of 1.
A load run given rows binds one into its scripts too, on either shape: a
deferred script reads the row its sampled response was bound to, and an
inline script.pre / script.post reads the row of the request it runs
beside (#3124). Those three - a data-driven collection run, a send-with-row,
and a data-driven load run - are every surface that binds a row, and they are
what a stashed pm.iterationData names when it refuses a later call.
Divergences from Postman:
- It is
undefinedwhen the run has no data, rather than an empty scope that answersundefinedto every column. Absence is a fact worth being able to test:pm.iterationData ? pm.iterationData.get('user') : 'default'. This is the opposite treatment topm.executionabove, deliberately - flow control is a capability, and one that silently does nothing is a false success. - It is read-only:
set,unsetandclearthrow. The rows are a run input, not a scope, so a write has nowhere to land and the next iteration binds a different row regardless. - Which row was used is recorded. Every step's stored row and live event
carries
dataRowIndex, and the step list shows it beside the iteration, so a wrapped run says which row a pass re-used.
The same row is also readable by column name through pm.variables while
it is bound (issue #1007) - see above and
scripting.md - but
pm.iterationData stays the accessor that reads only the row, with none of
the three scopes behind it.
Details are in scripting.md.
Migrating from Postman¶
Every Postman global below runs today, and the import notice
(meta.unsupportedScriptApis) does not name any of them. The table is for
anyone who wants to modernise a script to pm.*; nothing here needs doing for
it to keep working. The sections after it give each spelling's rules.
| Postman's legacy spelling | pm.* replacement |
|---|---|
postman.setEnvironmentVariable / getEnvironmentVariable / clearEnvironmentVariable |
pm.environment.set / get / unset |
postman.setGlobalVariable / getGlobalVariable / clearGlobalVariable |
pm.globals.set / get / unset |
postman.setNextRequest |
pm.execution.setNextRequest |
postman.getResponseHeader |
pm.response.headers.get |
postman.getResponseCookie |
pm.cookies.get(name) for the value, or pm.cookies.all() for the whole cookie object |
tests["name"] = ... |
pm.test("name", function () { ... }) |
responseBody |
pm.response.text(), or pm.response.json() for the parsed body |
responseCode |
pm.response.code |
responseHeaders |
pm.response.headers.get(name) |
responseCookies |
pm.cookies.all() |
responseTime |
pm.response.responseTime |
environment, globals |
pm.environment.toObject(), pm.globals.toObject() |
data |
pm.iterationData.toObject() |
iteration |
pm.info.iteration |
request |
pm.request (a different shape: the legacy headers is a lower-cased object and data a form object or the body text, see the table below) |
The legacy postman object¶
Postman's pre-pm.* helper methods run (#2577), each an alias of the pm.*
method Postman itself names as its replacement, so a script imported from
Postman that calls them runs as it did there:
postman.setEnvironmentVariable("token", pm.response.json().token);
const token = postman.getEnvironmentVariable("token"); // the same as pm.environment.get
if (postman.getResponseHeader("Content-Type") !== "application/json") {
postman.setNextRequest(null); // the same as pm.execution.setNextRequest(null)
}
postman. |
Alias of |
|---|---|
setEnvironmentVariable / getEnvironmentVariable / clearEnvironmentVariable / clearEnvironmentVariables |
pm.environment.set / get / unset / clear |
setGlobalVariable / getGlobalVariable / clearGlobalVariable / clearGlobalVariables |
pm.globals.set / get / unset / clear |
setNextRequest |
pm.execution.setNextRequest |
getResponseHeader |
pm.response.headers.get |
getResponseCookie |
pm.cookies.get, answering the whole cookie object (.value, .domain, ...) as Postman's does, rather than its value |
Postman's rules carry over with the methods:
- The two setters store a string. A value with a
toString()is stored as the string it returns, which is what Postman's legacy setters do andpm.environment.setdoes not:postman.setEnvironmentVariable("n", 5)reads back"5", an object reads back"[object Object]".false,0,"",nullandundefinedare stored as they are. - The two response readers exist only in a test script. A pre-request
script has no response, so it has no
getResponseHeaderand nogetResponseCookie, as in Postman, and calling one there is aTypeError. - Everything else is the
pm.*method's.postman.setNextRequestworks only inside a collection run and throws elsewhere in the wordspm.execution.setNextRequestuses (see Flow control);postman.getResponseCookiereads the jar aspm.cookiesdoes, and so throws wherepm.cookiesdoes.
Postman also writes a Using "postman.setEnvironmentVariable" is deprecated
warning to the console on first use; Vayu does not, for these methods or for
the globals below.
Postman's legacy globals¶
The values Postman binds beside postman run too (#2577), so the test script a
collection written before pm.* opens with passes as it did there:
tests["Status code is 200"] = responseCode.code === 200;
var jsonData = JSON.parse(responseBody);
tests["Has an id"] = jsonData.id !== undefined;
tests["Response time is less than 200ms"] = responseTime < 200;
postman.setEnvironmentVariable("token", jsonData.token);
Each is read once, when the script starts, off the pm.* member Postman names
as its replacement, so the two spellings answer alike. The second column is
what to write in a new script.
| Global | What it holds | pm.* spelling |
|---|---|---|
tests |
An object: each property assigned is a test result, named by its key and passed when its value is truthy | pm.test("name", function () { ... }) |
responseBody |
The body as text | pm.response.text(), or pm.response.json() for the parsed body |
responseCode |
{ name, detail, code, standardName }: the reason phrase, "", the status code and the registered phrase |
pm.response.code, pm.response.reason() |
responseHeaders |
An object of header name to value | pm.response.headers.get(name), which ignores case |
responseCookies |
The cookies the jar holds for this request's URL | pm.cookies.all() |
responseTime |
Milliseconds | pm.response.responseTime |
environment, globals |
The scope's variables as a plain object | pm.environment.toObject(), pm.globals.toObject() |
data |
The iteration's data row, {} outside a data-driven run |
pm.iterationData.toObject() |
iteration |
Which pass this is, 0-based, 0 where there is no run |
pm.info.iteration |
request |
{ id, name, headers, method, url, data } |
pm.request, pm.info.requestId, pm.info.requestName |
Postman's rules carry over with them:
testsis read once the script has finished. A row per key, in the object's key order, after thepm.testrows, so a key assigned twice is one result with its last value. A falsy value fails with Postman's message,AssertionError: expected false to be truthy. What was assigned before a throw is recorded, and the throw stays the script's error. The object read is the one bound, so a script that declares its owntests(var tests = []) records nothing through it.- The
response*values exist only in a test script. A pre-request script has no response, so it has none of the five; every other global is in both. environmentandglobalsare snapshots. Assigning to one changes no variable, andpm.environment.setdoes not update it. The legacy setters write through to it, as in Postman:postman.setEnvironmentVariable,clearEnvironmentVariableandclearEnvironmentVariableschange theenvironmentobject as well as the variable, and the four globals methods changeglobals.pm.environment.get(name)is the live read.responseHeaderskeeps each name as it arrived. The lookup is case-sensitive, as in Postman (responseHeaders['Content-Type']misses acontent-typeheader), and the last value of a repeated header wins. A load run's sampled response keeps only the folded, lower-cased names, so the object has those there.responseCookiesis read on first use. It is the listpm.cookies.all()answers, read when the script first touches it, so where there is no jar to read (a load run's deferred test script) that read throwspm.cookies' own refusal rather than answering an empty list.requestis a copy in Postman's legacy shape.headerslower-cases each name and holds a repeated one as the array of its values; they are the headers that were sent in a test script and the request's own before the send, aspm.request.headersreads them.datais a form body's enabled fields as an object (a repeated field as an array), a text body's text, and{}for no body, a file or GraphQL.idandnameare there inside a collection. Changing it changes nothing about what is sent; that ispm.request.- A script's own declaration wins. The engine runs a script inside a
function, so
const data = pm.response.json()orlet responseBody = ...is a local of the script's own. An assignment with no declaration (data = JSON.parse(responseBody)) writes the global, as in Postman.
responseCode.detail is the one value that differs: Postman fills it with a
paragraph describing the status, from its http-reasons table, which Vayu does
not carry; it is the empty string, Postman's own fallback.
Visualizer (pm.visualizer)¶
Postman's pm.visualizer.set(template, data, options) draws a Handlebars
template over the response in its Visualize tab. Vayu has no such tab, so the
calls are accepted and draw nothing (#2577) - a script that has one keeps
running, and the pm.test calls after it still run:
pm.visualizer.set("<p>{{name}}</p>", { name: pm.response.json().name });
pm.test("runs after the visualizer", function () {
pm.expect(pm.response.code).to.equal(200);
});
pm.visualizer.clear();
Each call leaves one console.warn, visualizer not rendered: ..., in either
script; nothing else is recorded, and the template and its data are not kept.
template must be a string: anything else (or no argument)
throws a TypeError naming pm.visualizer.set. data and options are
accepted as given and not read. clear() takes no argument.
Not (yet) supported¶
These Postman APIs are not implemented. A script that calls one throws; a
read of one of the properties returns undefined, and the visualizer is
accepted and warns:
pm.environment.name- the active environment's name- Dynamic variables via
pm.variables.get("$guid")- the getter does not fall through to the generator table; only{{…}}templates reach it. A script wanting a generated value usespm.variables.replaceIn("{{$guid}}")(see below) or writes the JavaScript for it. The supported set and the reasoning are in variable resolution pm.cookies.set(...)/.unset(...)/.clear()- the flat write half. Writing goes throughpm.cookies.jar(), which ships whole - see abovepm.request.clone(),.size()and.update()- each throws aTypeErrornaming itself and what to use instead (see Request methods)- The rest of postman-collection's
PropertyListon a header object -map,filter,find,idx,insert, the list-levelhas(item, value),assimilate,populate,clear,eachParent,toString. Only the read half and the three mutators named under Header methods ship - Drawing a visualization:
pm.visualizer.setand.clearare accepted and draw nothing, and each call logs oneconsole.warn, as above; there is no Visualize tab to show the template in. The script keeps running pm.test.skip,pm.test.index,pm.require,pm.execution.runRequest,pm.execution.locationandpm.response.dataURI()pm.request.url.variables(Postman's path-variable list,:idsegments) andpm.response.jsonp(...)- both read asundefined, so a call throws- A reviver passed to
pm.response.json(reviver)-json()takes no argument here, and one that is passed is ignored: the body is parsed as plain JSON and nothing throws, so a script that revives dates or big numbers gets the unrevived values. Parse the text yourself instead:JSON.parse(pm.response.text(), reviver). The same holds for the response apm.sendRequestcallback receives, which shares the implementation; the import notice cannot name that spelling, since the scan matches the written pathpm.response.jsonand not a callback's parameter console.debugand every other console method beyondlog,info,warnanderror(console.table,console.dir,console.time, ...) - useconsole.log. This holds withscriptEnableConsoleon or off: the four supported methods stay defined when it is off, and nothing else is addedrequire(...)of anything butcrypto-js,uuid,lodash,moment,csv-parse/lib/sync,xml2js,chai,ajvandtv4,script.packagesand the libraries Postman bundles beyondCryptoJS,_,xml2Jsonandtv4-cheerioandBackbone. The sandbox has no module system, only therequireshelf; the shelf'scrypto-jscovers the hashers and their HMACs and nothing else ofCryptoJS, so aCryptoJSmember outside that list is named by the import notice, also when it is read through an alias or a destructure ofCryptoJSorrequire('crypto-js'), and one inside it is not- The browser and Node globals
fetch,XMLHttpRequest,process,URL,URLSearchParams,TextEncoder,TextDecoder,structuredClone,localStorage,sessionStorage,window,documentandalert- the editor declares each as absent and names the replacement on hover Intl, and the locale and options arguments oftoLocaleDateString,toLocaleTimeString,toLocaleStringandNumber.prototype.toLocaleString, which run and ignore them. Unlike the globals above,Intlis not declared absent: the editor marks each bareIntlwith a warning and suggestsrequire('moment'), see Editor autocompleteBuffer- the sandbox is not Node. Usebtoa/atobfor base64 andpm.cryptofor hashing- Chai and chai-postman members outside the list in
Assertion chains, the
require()-able libraries off the shelf (cheerio, …) and chai-postman's ownpostmanRequest,postmanResponseandpostmanRequestOrResponse. Each throws aTypeErrorrather than reporting a pass. A flag that changes what the matcher after it asserts (any,own,ordered,itself) is never accepted as a no-op for that reason: it is either read by the matcher or it throws. The three chai-postman names are the only chai spelling a Postman import'smeta.unsupportedScriptApisnames; every other member of the list above runs
The editor underlines a use of any of the names above that the sandbox lacks (see Type declarations) and its hover gives the replacement Postman itself names.
A collection imported from Postman lists the requests whose scripts use these
under meta.unsupportedScriptApis (see
Postman import), but only the names in
the scan table (API_RULES in engine/src/core/script_api_scan.cpp), and only
when written out: pm.test.skip, pm.test.index, pm.require,
pm.execution.runRequest, pm.execution.location, pm.response.dataURI,
pm.response.jsonp, pm.response.json(reviver) (a call with an argument; the
empty json() runs and is not named), pm.response.headers.map,
pm.request.headers.map, pm.request.url.variables, pm.cookies.set,
pm.cookies.unset and pm.cookies.clear (each its own name; pm.cookies.jar()
is not among them), console.debug, console.table, console.dir and
console.time, fetch, XMLHttpRequest, URL, URLSearchParams,
TextEncoder, TextDecoder, structuredClone, localStorage and
sessionStorage, Buffer, the require and CryptoJS cases above, cheerio,
Backbone and chai-postman's three members. A host global the script declares
itself (const fetch = ...) is not named. These are not scanned, so a script
that uses them imports with no notice and throws at first run:
process,window,documentandalert, left out on purpose: they are common identifiers in a script's own code, and a notice that is wrong more often than right trains people to ignore it- console methods other than the four above (
console.trace,console.assert,console.group,console.count,console.timeEnd, ...) pm.environment.name,pm.request.clone()/.size()/.update(), thePropertyListmethods of a header object other thanmap, and a name read through an alias (const h = pm.response.headers; h.map(f)), which includes a reviver passed to thejson()of apm.sendRequestresponse
Postman's pre-pm.* globals and the postman.* methods are not named either:
they run (see above).
Request mutation & URL variables¶
A pre-request script can change the outgoing request. pm.request's url /
method / headers / body are copied out of the C++ Request into a plain JS object
(pm/pm_request_url.cpp, setup_pm_request), and after the script returns that object is
read back and applied to the same Request before client.send()
(apply_pm_request_writeback). In a test script it stays a read-only record: the
request has already gone out, so nothing is written back and a mutation there is discarded.
The two hooks therefore read different header sets, matching Postman: a pre-request
script sees the composed headers it is there to edit, and a test script sees the ones that
were actually sent - including the Content-Type the engine derives from the body mode and
the headers the engine adds itself: the
default User-Agent, the negotiated Accept-Encoding, and a correlation id where one is
switched on. None of those exists yet when the pre-request script runs (#483, #1229). A form-data Content-Type appears in neither, because libcurl writes that one
itself with the boundary.
pm.request.headers['X-Signature'] = sign(pm.request.body);
delete pm.request.headers['Authorization'];
pm.request.url = 'https://api.example.com/v2/users';
pm.request.method = 'POST';
pm.request.body = JSON.stringify({ n: 2 });
pm.request.addHeader({ key: 'X-Trace', value: 't-1' });
pm.request.auth = { type: 'bearer', bearer: [{ key: 'token', value: '{{token}}' }] };
- The object is authoritative, not a diff. Whatever
pm.request.headersholds at the end is the header set that is sent, which is what makesdeleteremove a header the engine applied. - The script wins over engine-applied auth.
build_requestresolves auth into the request before the script runs, so a script-setAuthorizationreplaces the resolved one. A credential still holding a{{name}}no variable defined at compose, or any name of a request a pre-request script runs before, is applied after the script instead (#2473, #2521), as Postman applies all auth; a script-setAuthorizationstill wins, since auth never replaces a header the request carries. pm.request.authreplaces the request's auth (#3131). It takes Postman's{ type, <type>: params }block, the params as[{ key, value }]or{ name: value }, and is read by the same reader aspm.sendRequest'soptions.auth:basic,bearer,apikeyandnoauthare composed by the engine's own resolver, a{{name}}in a credential resolved against the scopes the script left, and any other type,oauth2included, fails the write-back naming it, as does a parameter name the type does not take or a block with no credential in it. The credential the engine applied before the script is taken off first unless the script rewrote it; a header the engine did not write still wins, as it does over the Auth tab; and auth waiting on the script is not applied at all. Divergences, each deliberate:pm.request.authreadsundefineduntil the script assigns it (Postman's reads the request'sRequestAuth; here the engine's credential is visible as the header it wrote), so a liftedpm.request.auth.typeorpm.request.auth.bearer.get('token')throws an ordinaryTypeErrorbefore an assignment; and an assignment is a plain object rather than aRequestAuthwith methods, so its blocks have noget()either. Postman's precedence differs too: its auth helper replaces a typedAuthorization, where Vayu keeps the header the request carries (#2475). A refused assignment (anoauth2type, a parameter the type does not take, a{{name}}naming a column the bound data row lacks) applies nothing the script wrote topm.requestand the request is still sent with the Auth tab's own credential, the reason reported as the pre-request script error in the Console - unlikepm.sendRequest, which refuses to send a request whoseauthit cannot compose. The full rules are in scripting.md.- A value the engine cannot send is refused, not coerced.
methodmust be a string (one of the seven verbs);bodymust be a string, theRequestBodyobjectpm.request.bodyitself holds, or a Postman body description (below) - an object with nomode,{}included, is never sent as[object Object]; a header value may be a string, number or boolean. Anything else rejects the whole write-back - all or nothing - and surfaces aspreScriptError, which the response pane's Console tab shows.urlis refused a step earlier: assigning anything that is not a URL string throws at the assignment, so the script author is told which line was wrong rather than reading it off the write-back. urlis Postman'sUrlobject, not a string (#991 - the owner decision that compatibility wins over the shipped string shape).protocol,host,port,path,hash,querywithget/has/all/toObject/countand, since #3462, the rest of thePropertyListreads (each,map,filter,find,one,indexOf,idx), plusgetHost(),getPath(),getQueryString(),getPathWithQuery(),getRemote(),getRaw(),toString(),update(),addQueryParams()andremoveQueryParams(). It still behaves as a string in every context JavaScript allows - concatenation, template literals,==,String.prototypemethods,JSON.stringify,.length- and two things changed:===andtypeof. A{{variable}}in the scheme or host is read as opaque host text, as Postman's parser reads it (#3454): a pre-request script on the{{baseUrl}}/users?page=2an imported collection stores seesgetHost()'{{baseUrl}}',getPath()'/users'and the query, and its edits keep the token for the resolution after the script. Divergences: with no path after the token,getPath()is''where Postman answers'/'; the query's walks take a function only (Postman also takes an object or a property name as the rule),indexOfmatches a{key, value}on both fields rather than by identity; andgetRemote()takes noforcePort. The full surface and the migration note are in scripting.md.- The URL is writable a member at a time, not only whole (#1040).
pathandhostare arrays a script mutates in place (push,splice, index assignment, alengthtruncation);protocol/port/hashtake an assignment; and the query carries Postman'sPropertyListwriters -add,upsert,remove,clear. A URL nobody edited is sent as the exact bytes it arrived as, because the parts are recomposed only when a member actually changed.url.addQueryParams(params)andurl.removeQueryParams(params)take several at once. Two divergences, both deliberate: a leading?on anaddQueryParamsquery string is dropped (Postman keeps it in the first key), andremoveQueryParams({ key })outside an array throws aTypeErrorwhere Postman's matches nothing. bodyis Postman'sRequestBodyobject, not a string (#1003 - the same trade #991 made for the URL).mode(urlencoded/formdata/graphql/file/raw- every other content mode readsraw),raw, theurlencoded/formdatafield lists, thegraphqlpair and thefile, pluslength, all read-only; assigning the whole body or.raw, or calling.update(), are the writes. It still behaves as a string in every context JavaScript allows - concatenation, template literals,==,String.prototypemethods,JSON.stringify,.length- and three things changed:===,typeof, and assigning it straight into a header value, refused the same waypm.request.urlalready is. The full surface and the migration note are in scripting.md. Reading a form body never rewrites it: an unchanged value means untouched.-
All five of Postman's body modes are answered (#1111). A
graphqlbody readsmode === 'graphql'and answersbody.graphql.query/body.graphql.variables, derived from the stored string by the classifier the send itself uses. Two divergences inside that mode, both deliberate:variablesis the JSON value the envelope carries rather than the text of Postman's variables editor, which Vayu never stored - so a liftedJSON.parse(pm.request.body.graphql.variables)becomes a plain read - and a body that is envelope-shaped but does not parse, or is nested deeper than 128 levels, answersundefinedrather than a guessed pair, matching what the send does with it..rawstays defined here as it is for the form modes.A
binarybody - one file sent as the whole body - readsmode === 'file', Postman's name for it. One divergence: Postman'sbody.fileis{src}, the path, and Vayu never discloses a local path to a script, as for a form-data file part (#411).body.fileis{ name, size? }instead - the file name the request declares, else the last part of the path, and its length in bytes once the send has read the file - so a liftedbody.file.srcreadsundefined. The body's string view is@<name>, and assigning the body or.rawon a binary request is refused: a script never chooses the file. - Postman's body description is taken, for the body's own mode (#3131).pm.request.body.update(...)andpm.request.body = ...both take{ mode: 'raw', raw }and{ mode: 'urlencoded', urlencoded: [{ key, value, disabled? }] };update('...')is{ mode: 'raw', raw: '...' }, as in Postman. Each means what assigning its string to.rawmeans, so.rawand.urlencodedread the new body afterwards. One divergence: Postman'supdateswitches the body's mode, and here the mode must be the one the body already has (a request with no body takesraw, as text). The write-back keeps a request's mode, so{ mode: 'raw' }on a urlencoded body would otherwise be parsed back into form fields; another mode is refused by name, as areformdata,fileandgraphql. So a stringupdate('...')is refused on a urlencoded or GraphQL body, where assigning the same string to.rawis taken; on a GraphQL body the refusal names.raw. A second divergence: a description'soptionsis ignored, so noContent-Typeis derived fromoptions.raw.languageas Postman derives one; the request's own body type implies it (text/plainfor a body added to a bodyless request) unless the script sets the header. Postman'supdatewithout amodeis a silent no-op; here it throws. - Setting a variable re-renders the request's{{…}}placeholders, Postman's order (#1008, #2521).POST /compose(engine-side since #226) resolves them at compose time unless a pre-request script runs before the send - an enabled, non-blankscript.preon the request, a folder or the collection. Then it leaves every name a scope answers written, and so does it a name it could not answer (#1009), and they are resolved after the pre-request script and before the send, against the scopes as the script left them. Sopm.environment.set("host", …)reaches a{{host}}in the same request's URL, on every run, and a script that replaces a stored token sends the new one. In the script,pm.request.urlandpm.request.headershold the{{host}}as written. A request no pre-request script runs before keeps the old rule: a value composition substituted is finished text, not re-resolved, andpm.request.urlis how a script changes it. In a collection run, every step defers when any step's script or extractor writes a variable before a send (script.teardownaside), so a token a login's test script stores reaches a later step'sBearer {{token}}on every run.{{data.*}},$names and a file path are never deferred. - Load tests do not run pre-request scripts at all, so this is a Send / Design Mode capability.
This goes further than Postman on the URL, method and body, which Postman's docs mark immutable or provide no mutators for.
Header methods¶
Both header objects carry get(name), has(name), and the read half of a Postman
PropertyList - each(fn, thisArg?), all(), count(), toObject(excludeDisabled?,
caseSensitive?), one(name) and indexOf(name); pm.request.headers also carries the
three mutators, upsert, add and remove. They are non-enumerable properties of the
header object itself, which is what makes them safe: apply_pm_request_writeback reads
that object's own enumerable string properties as the outgoing header set, so an
enumerable method would be read as a header whose value is a function and would fail the
whole write-back. Being on the same object is also what makes a method call and a plain
assignment agree - there is one property set, not two views of one.
pm.request.headers.get('authorization'); // case-insensitive
pm.request.headers.has('Authorization');
pm.request.headers.upsert({ key: 'X-Trace', value: id }); // or ('X-Trace', id)
pm.request.headers.add({ key: 'X-New', value: '1' }); // throws if already set
pm.request.headers.remove('Authorization'); // no-op if absent
pm.request.headers.all(); // [{key, value}, ...]
pm.request.headers.count(); // how many there are
pm.request.headers.one('Content-Type'); // {key, value}, or undefined
pm.request.headers.toObject(); // lower-cased keys
pm.request.headers.indexOf('Content-Type'); // position in all(), or -1
pm.request.headers.each(function (header, index, all) {
console.log(header.key, header.value, index, all.length);
});
toObject() lower-cases every key, which is what Postman does whenever the list
it is called on is indexed case-insensitively - a header list always is - so
toObject()['content-type'] reads the header whatever casing it was set with.
A truthy second argument (toObject(false, true)) keeps the stored spelling.
The first argument is Postman's excludeDisabled and decides nothing here, as
do the two it does not take: these objects hold no disabled row, no duplicate
name and no empty one.
Five deliberate divergences from Postman:
- The methods are case-insensitive, indexing is not.
upsert('authorization', v)replaces an existingAuthorizationinstead of adding a second spelling - which the write-back would refuse as a clash, sinceHeadersis a case-insensitive map. addrefuses a name that is already present and namesupsertin the error. Postman'sHeaderListholds duplicates andaddappends one; a single-valuedHeadersmap cannot represent that, and silently behaving asupsertwould hide the difference rather than report it.- A header field literally named after one of the methods wins. Entries are defined over the method, attributes included, so the header still reaches the wire and the shadowed method throws loudly. A dropped header would be the worse failure.
all()reports this object's key order, not wire order, and can never report a duplicate. Postman'sHeaderListkeeps both; aHeadersmap cannot, because it is single-valued and case-insensitive, so a name set twice already collapsed into one entry before any script runs.indexOfmatches a{ key }member by itskey, not by identity. Postman finds a member by identity in its own list; the members handed out here are built fresh on every call, so identity would answer-1for a member of the very list it came from. Matching the key answers what Postman answers for that case, and-1for an object naming a header this list does not hold.
Bad input fails loudly: a name must be a non-empty string, a value a string, number or
boolean (the set plain assignment already accepts), each throws if its first argument
is not a function, and calling a method detached from its object throws rather than
answering as though the header were missing.
Request methods¶
Postman's Request carries writes of its own, and a lifted script calls them on
pm.request itself (#3131). Each is the member method it names, looked up when it is
called, so it writes the object the write-back reads and refuses bad input with that
method's error:
| Request method | Is |
|---|---|
addHeader(header) |
headers.upsert |
upsertHeader(header) |
headers.upsert |
removeHeader(name) |
headers.remove |
forEachHeader(fn, thisArg?) |
headers.each |
getHeaders(options?) |
headers.toObject(false, !options.ignoreCase) |
addQueryParams(params) |
url.addQueryParams |
removeQueryParams(params) |
url.removeQueryParams |
toJSON() |
{ url, method, header: [{ key, value }], body?, auth? }, also what JSON.stringify(pm.request) writes |
authorizeUsing(type, options?) |
assigns pm.request.auth: ('basic', { username, password }), ({ type, ...options }) or the block itself; null removes it |
pm.request.addHeader({ key: 'X-Trace', value: 't-1' });
pm.request.removeHeader('Authorization');
console.log(pm.request.getHeaders()['X-Trace'], pm.request.toJSON().method);
Divergences, each deliberate:
addHeaderreplaces a header the request already carries - it isupsert, notadd. Postman's appends a second line, which a request holding one value per name cannot represent, and a liftedaddHeaderis usually called on a header the request may already set.headers.addstill refuses an existing name.removeHeaderis case-insensitive, like every header method here; Postman's matches the case unless itsignoreCaseoption says otherwise.toJSON().urlis the URL string, whatpm.request.url.toJSON()answers, where Postman's is its Url object's parts.headerandbodyare Postman's shapes, read frompm.requestas the script has left it;bodyis absent for a request with none,authfor a script that assigned none.authorizeUsingthrows on a type it cannot compose, naming it, at the call; Postman's ignores an invalid type and sends the request with no auth.clone(),size()andupdate()throw by name with what to use instead, rather than the barenot a functionan unbound name gives.
The methods are non-enumerable, so Object.keys(pm.request) is still the four members,
and auth once the script assigns it.
Editor autocomplete¶
The full completion set (labels, snippets, signatures, docs) is generated server-side by
the engine and served at GET /scripting/completions
(engine/src/http/routes/scripting.cpp). This endpoint is the single source of truth
for what the editor advertises, and it is fetched once on startup and cached
(app/src/queries/script-completions.ts).
The script editors are mounted via the shared CodeEditor
(app/src/components/ui/code-editor.tsx) with language="javascript".
useScriptCompletionProvider (app/src/hooks/useScriptCompletionProvider.ts, called once
in App) registers the cached completions with Monaco's JavaScript language via
registerCompletionItemProvider (trigger character .), so typing pm. surfaces the
pm.* entries and snippets alongside Monaco's built-in JavaScript IntelliSense. The
registration is global per language, so one call covers every script editor instance.
The
kindfield on each completion usesmonaco.languages.CompletionItemKindnumeric values (Function = 1, Field = 3, Variable = 4, Snippet = 28); changing the engine constants requires an engine rebuild for new icons to take effect.
A kind: 28 (Snippet) entry carries two members no other entry does:
context ("pre", "test" or "both") says which script kind the template
belongs in, and group ("Variables", "Request", "Response", "Tests",
"Signing" or "Logging") is the heading it is listed under. These are what
the script panels' insertable snippets surface is built from, so a template
added to the engine table is what a script author finds there - reachable
from the panel it actually runs in, filed under its heading, with nothing
maintained twice. A script.setup / script.teardown editor runs outside any
request, so it is offered only the "both" templates.
Type declarations (hover, signature help)¶
A completion list can only fill a dropdown. Hover documentation over an existing call and
signature help while typing arguments come from Monaco's TypeScript worker, which
wants a .d.ts - served at GET /scripting/types and generated from the same
completion table, so the surface stays declared once. useScriptTypeDefinitions
(app/src/hooks/useScriptTypeDefinitions.ts, called once in App) registers it with
addExtraLib.
It also configures the worker to match the sandbox: lib: ["esnext"] with no dom,
because the runtime has no fetch or URL and the editor must not offer them (the
timers it does have are declared by the engine's file, with the sandbox's own
documentation); and target: ESNext, because an older lib or target would flag
Object.hasOwn, Array.prototype.at, toSorted, Object.groupBy and
Promise.withResolvers, which quickjs-ng runs fine (see docs/engine/scripting.md).
The newest library members, RegExp.escape, Math.sumPrecise, JSON.rawJSON,
JSON.isRawJSON and the Uint8Array base64 and hex methods, are not in the TypeScript
that Monaco bundles, so esnext alone would underline each as "Property does not exist"
though the engine runs it. The engine's file declares them as interface augmentations
(LIBRARY_GAPS in script_types.cpp); script_types_test.cpp runs every one in the
script engine, so a declared member the runtime lacks fails there. The set retires with a
Monaco upgrade: script-typedefs.docs-compile.test.ts compiles the bare lib and fails
when it declares one, naming the row to delete.
Semantic diagnostics are on, which is what makes pm.response.staus squiggle with a
"Did you mean 'status'?" - and, through the same analysis, what makes quick fixes, rename,
find-references and go-to-definition work inside a script. Those providers all default to
enabled in Monaco; useScriptTypeDefinitions sets them explicitly so a changed default
cannot remove them silently.
Exactly two diagnostics are suppressed (diagnosticCodesToIgnore), because a correct
script in this editor produces them:
| Code | Message | Why it is wrong here |
|---|---|---|
1108 |
A return statement can only be used within a function body |
The engine wraps every script in an async IIFE before running it, so a top-level return to bail out early is legal |
2304 |
Cannot find name x |
An assignment to an undeclared name (jsonData = pm.response.json()) creates a global in the sloppy-mode IIFE, which the engine runs; and quickjs-ng provides four globals the esnext lib does not declare |
2304 was once suppressed for a different reason, that a collection-level script part
is joined to the request's before the engine runs it. That no longer holds: each script
element runs in a context of its own, so a name declared in the collection's script is
not visible in the request's (see Isolation between
scripts). The deferred load-test
replay runs each script.post element on its own too (#3125).
Un-suppressing 2304 was weighed and declined. Typing an undeclared name would then be
an error, which is the more useful behaviour, but it would flag correct code, and it
costs more than it returns today:
- Implicit globals run.
jsonData = pm.response.json();with novaris legal in the engine's sloppy-mode wrapper and is a common habit in scripts imported from Postman. Each use would be underlined. - Four runtime globals are missing from
lib.esnextand would each need declaring, and holding to the runtime by a test of their own:queueMicrotask,performance,DOMExceptionandInternalError. A quickjs-ng upgrade can add more. - The examples on this page and in
scripting.mdelide their placeholders (value,id,token). Compiled as written, the corpus draws 89 diagnostics, all of them 2304.
What suppressing it costs is that an undeclared name draws nothing. So the engine
declares the names a script is likeliest to reach for that the sandbox lacks
(ABSENT_GLOBALS in script_types.cpp), and the editor underlines a use:
- the host globals of a browser or Node:
fetch,URL,Buffer, ... - the libraries Postman bundles that the
requireshelf does not carry:cheerioandBackbone(CryptoJS,_,tv4,xml2Jsonandrequireare declared as the real thing, withdeclare module 'crypto-js',declare module 'uuid',declare module 'lodash',declare module 'moment',declare module 'csv-parse/lib/sync',declare module 'xml2js',declare module 'chai',declare module 'ajv'anddeclare module 'tv4'so eachrequire(...)of them types; all come from the oneSHELF_MODULEStable inscript_types.cpp, andrequiretakes only the names on it._and themomentmodule are declaredany: their members are not restated, and a partial list would underline the rest on correct code.csv-parse/lib/syncis the parse function, taking a string and any options object and answeringany, becausecolumnsandobjnamechange the records' shape.momentandcsv-parse/lib/synchave no global declaration, as Postman has no global. Thexml2jsmodule declares its members, andxml2Jsonis declared as the functionxml2Json(xml: string): any. Thechaimodule declares its top-level members (expect,assert,should,use,config,AssertionError, ...) and answersanyfor an assertion chain, whose members are not restated; it has no global, as in Postman.shouldon a value is not declared, because it exists only afterchai.should()runs. Theajvmodule declares theAjvconstructor, an instance's methods, the validator and itserrors;tv4is declared as the object with its members, anddeclare module 'tv4'is that same object, as at run time)
Hover names the replacement Postman itself gives (cheerio's is
require('cheerio'), which Vayu's require does not load either) and says what
Vayu has instead. The postman object is
declared as the methods it has, each hover naming the pm.* method it aliases, and
Postman's pre-pm.* globals (tests, responseBody, ...) as the values they are
(string, number, an object), so JSON.parse(responseBody) and responseTime < 200
are correct code to the editor as they are to the engine.
A name is declared never, so a call, a member access or an assignment is an error
(cheerio.load(...)). never is assignable to everything, so a bare read
into something that takes anything (console.log(cheerio)) is left unflagged: hover
still names the replacement there.
A script that declares one of these names itself is not flagged. const data =
pm.response.json() and var request = pm.request are common and correct: the engine
runs the script inside a function, where they are local. The editor compiles each script
as a module (moduleDetection: Force in SCRIPT_COMPILER_OPTIONS) so the declaration
shadows the global. Compiled as a global script, the same line reported "Cannot
redeclare block-scoped variable" (2451), and did for const URL or function fetch
before these names were added. A module is strict-mode to TypeScript, so a script that
runs sloppy draws TypeScript's strict-mode errors on with, delete name, an octal
literal, yield or let as a name, and a top-level this. A top-level await draws
nothing: the engine's wrapper is an async function, and SCRIPT_COMPILER_OPTIONS sets
module to ESNext, the setting under which a module accepts one.
An entry leaves ABSENT_GLOBALS in the commit that makes the runtime provide the name,
and a test that executes typeof <name> in the real script engine for every entry holds
the list to the sandbox: it caught queueMicrotask, which quickjs-ng does provide, on
its first run.
Intl is flagged without being declared absent (#3129). The worker resolves it
against the stock esnext lib and reports nothing, and ABSENT_GLOBALS is left as it
is, so the warning comes from the script editor instead: ScriptElementForm attaches
attachIntlDiagnostics (app/src/lib/script-intl-diagnostics.ts), which scans the
model's text and writes a warning marker on every bare Intl under an owner of its own ("vayu-script-intl",
never the worker's "javascript", whose markers the worker replaces). The message
points at require('moment') and says the toLocale* methods ignore their options. The
scan skips strings, template text (not its ${...} expressions), comments and regex
literals, and leaves obj.Intl, x?.Intl, MyIntl and an object-literal key alone;
a script that declares its own Intl is not marked at all. The runtime is unchanged and
installs no Intl. Read-only JavaScript viewers do not get the marker: it is attached by
the script form's onMount, not by CodeEditor.
Narrow the suppression list rather than widening it: each code on it is a real mistake going unreported in exchange for not crying wolf on correct code.
Every pm.* example on this page is compiled against those declarations¶
script-typedefs.docs-compile.test.ts takes every ```javascript block that mentions
pm. in this page and
docs/engine/scripting.md, compiles each against the generated
.d.ts, and requires zero errors - with SCRIPT_COMPILER_OPTIONS and
SUPPRESSED_DIAGNOSTICS read from useScriptTypeDefinitions.ts rather than restated, so
it checks them the way the editor does. Four defects had survived the engine's
substring-based guards, because a declaration can carry every right name and still not
type-check (#463).
The declarations reach it as engine/tests/fixtures/script-typedefs.d.ts, checked in and
pinned to the generator by the engine suite - vitest cannot run the C++ generator, and
ctest has no TypeScript compiler, so the two halves meet at one artifact. See
api-reference.md
for the regeneration command.
A consequence worth knowing before editing either page: a pm.* example here is now
checked, so an example that is wrong fails CI rather than misleading a reader.
The corpus is whatever the two pages currently hold, and the guard beside the
compile asserts a floor rather than a count, deliberately - an added or
deleted example is an ordinary docs edit and must not fail an assertion in a
.test.ts. Which is also why this page no longer states how large that corpus
currently is: a count written into prose is a fact with nothing holding it
true, and the one that used to sit here had drifted by a third. The figures in
the strictNullChecks note below are dated for the same reason.
Optional members, and why the editor states them without enforcing them¶
A completion entry says a member may be absent by ending its detail in
| undefined. The generator reads that one convention in two places: a leaf keeps the
union (iteration: number | undefined), and a surface that has members of its own has no
union to carry it, so the optionality moves onto the property name -
pm.iterationData is declared iterationData?: { ... }, because it is undefined
outside a data-driven run or a send-with-row.
That marker shows in hover, and deliberately does not produce a squiggle: the worker
runs with strictNullChecks off, and without it an optional property is
indistinguishable from a required one at a use site. So a plain request script calling
pm.iterationData.get('x') gets no editor error for something that throws at run time -
the guard the docs recommend (pm.iterationData ? ... : ...) is advice, not a rule the
type system enforces.
That is a decision (#443), not an oversight, and useScriptTypeDefinitions now sets
strictNullChecks: false explicitly rather than relying on the default, so a strict:
true arriving through the spread of Monaco's existing options cannot turn it on as a side
effect. It was taken on a count, and the count is a measurement from when the
decision was made rather than a live property of the corpus: compiling the
57 scripts the two pages then held - 54 pm.* examples plus three realistic
ones - with the flag on added 13 diagnostics:
| What | Count | Verdict |
|---|---|---|
pm.iterationData.get/has/toObject unguarded |
7 | Correct inside the data-driven run those examples are about |
An optional string used straight - pm.environment.get(...) into .trim() and pm.crypto.hmacSha256, pm.request.body into JSON.parse |
4 | A real crash when the value is absent, and the idiom every script uses |
pm.info.iteration > 0 |
1 | Works: the comparison is false outside a run |
pm.response.errorMessage after a truthy pm.response.errorCode |
1 | Correlated siblings, which no narrowing can see |
Eight of the thirteen land on lines these docs publish as the way to use the API. Nor can
the noise be suppressed away while the catch is kept: 18048 is the code for
pm.iterationData.get(...) - the case the flag was wanted for - and for token.trim(),
and the remaining code is 2345, which is the argument checking the whole feature exists
to provide. A script editor is JavaScript, so there is no ! for an author to say "I know
it is set"; the escape is restructuring the code.
So the trade is the one the suppression list above already makes, one level up: a real mistake goes unreported in exchange for not crying wolf on correct code. Revisiting it means re-running that count, not re-arguing it.
pm.execution has the mirror-image limitation and no fix at all: it is always bound, and
its methods throw outside a collection run, which no type can express.
The second consumer: MCP agents¶
The completion set is no longer only an editor concern. An MCP agent writes scripts too -
run_request takes a preRequestScript and both it and start_load_run take a
postRequestScript - and it reaches the same sandbox, since the sandbox belongs to the
engine and has no per-client gate. What gates it is the user's reveal setting: with Reveal
secrets to agents off, those two tools refuse a script the agent supplies (#1834).
So the MCP server re-serves this endpoint as the vayu://scripting/completions resource
(app/electron/mcp/resources.ts), trimmed to label / detail / documentation - see
docs/engine/mcp.md. The reason it reads
the endpoint rather than describing the surface in its own prose is the one this page
already demonstrates: a hand-written copy drifts, and the app's own pre-request quick
reference had drifted into claiming "No crypto, base64 or URL in the sandbox" before
pm.crypto landed. Adding a name to the completion table therefore reaches Monaco, the
.d.ts and every agent at once - do not add a fourth place that lists pm.* names.
Where it lives¶
| Concern | Location |
|---|---|
pm runtime (QuickJS bindings) |
engine/src/runtime/script_engine.cpp (the engine and the pm composer), engine/src/runtime/pm/ (the surfaces) |
| Completion metadata endpoint | engine/src/http/routes/scripting.cpp |
| Type declaration generator | engine/src/http/routes/script_types.cpp |
| Generated declarations (pinned) | engine/tests/fixtures/script-typedefs.d.ts |
| Docs-compile guard | app/src/hooks/script-typedefs.docs-compile.test.ts |
| Type declaration fetch + cache | app/src/queries/script-types.ts |
| Monaco type registration | app/src/hooks/useScriptTypeDefinitions.ts |
| Completion fetch + cache | app/src/queries/script-completions.ts |
| Monaco completion provider | app/src/hooks/useScriptCompletionProvider.ts |
| Shared editor wrapper | app/src/components/ui/code-editor.tsx |
| Script editor panels | app/src/modules/request-builder/components/RequestTabs/panels/script/ScriptPanel.tsx + script-variants.tsx, app/src/modules/collections/CollectionDetail/ScriptTab.tsx |