Scripting API

Libraries

The JavaScript libraries bundled with Relay and how scripts load them.

Declaration

const _ = require("lodash");
const { v4: uuidv4 } = require("uuid");

Overview

Relay bundles the libraries that Postman scripts use most, so scripts can use them without a network connection or a package manager. Load one with require, or use its global name where it has one. A library loads the first time a script uses it in a send.

const signature = CryptoJS.HmacSHA256(relay.request.body.raw, relay.environment.get("webhookSecret"))
  .toString(CryptoJS.enc.Hex);
relay.request.headers.upsert({ key: "X-Signature", value: signature });

const tomorrow = moment().add(1, "day").format("YYYY-MM-DD");
relay.variables.set("startDate", tomorrow);

Topics

Bundled libraries

LibraryVersionrequire nameGlobalUse it for
Ajv6.12.6ajvValidating values against JSON Schemas (draft-07).
chai4.5.0chaichaiAssertions; expect and assert are built on it.
cheerio1.0.0cheeriocheerioQuerying HTML with jQuery-style selectors.
crypto-js4.2.0crypto-jsCryptoJSHashes, HMACs, AES and encodings.
lodash4.17.21lodash_Utilities for objects, arrays and strings.
moment2.30.1momentmomentParsing, formatting and doing arithmetic with dates.
uuid9.0.1uuidGenerating UUIDs, such as with v4().
xml2js0.6.2xml2jsParsing XML into objects and building XML from them.

require("atob") and require("btoa") return the global atob and btoa functions.

Loading a library

require(module)

require(module: string): any

Returns the library called module. Asking for any other module throws an error that lists the available ones.

Examples

Validate a value with Ajv

const Ajv = require("ajv");
const ajv = new Ajv({ allErrors: true });
const valid = ajv.validate({ type: "array", items: { type: "string" } }, relay.response.json().tags);
assert.isTrue(valid, ajv.errorsText());

To validate the whole response body, relay.response.to.have.jsonSchema(schema) is shorter.

Read an HTML page with cheerio

const $ = cheerio.load(relay.response.text());
relay.environment.set("csrfToken", $("meta[name=csrf-token]").attr("content"));

Parse XML with xml2js

const xml2js = require("xml2js");
xml2js.parseString(relay.response.text(), (error, result) => {
  if (error) throw error;
  console.log(result);
});

For a quick synchronous parse, use the global xml2Json(text).

Discussion

Scripts run without Node, so libraries that need Node's modules, process or Buffer aren't available, and you can't install others. moment includes only its English locale, and cheerio is its slim build, which parses HTML with htmlparser2.

See Also

  • Global functions: Timers, encoding, random values and the legacy Postman globals available to every script.
  • expect: A function that starts a chai or Jest-style assertion about a value.