Scripts

JavaScript can run in four places. All of it runs in a sandbox with no file, network or process access, and a script that runs longer than 2 seconds is stopped.

WhereWhat it is for
Pre-request script (API Client)Change the request before it is sent: add a signature or a timestamp, set a variable.
Test script (API Client)Check the response with test(...) and expect(...), and keep values for the next request.
Scripted response (mock endpoint)Decide an answer from the request, when rules and templates are not enough.
Custom fault (mock endpoint)Decide whether and how a request fails. See Faults.

Trust

A script is code, so it stays off until you trust the project: the Trust scripts button in the dashboard, or zyvra trust (--revoke undoes it). Trust only projects whose scripts you have read. Until then, scripted responses answer with an error and request scripts do not run.

Help while you write

The editors suggest what a script can use as you type (request., vars., response., expect(…)., state., jwt., fault.), and hovering a name shows what it does. Scripts imported from Postman keep working through a pm.* layer.

Start from an example is in every script editor. The pre-request and test script examples include:

  • a timestamp or a unique request id in a header, an HMAC-SHA256 signature of the body, a short-lived JWT, a saved token;
  • checks that the status is a success, that the response is fast, that the body is JSON with an id, or a non-empty list;
  • keeping an id or token from the response for the next request.

Choosing one asks first only if it would replace something you wrote.

A small test script

test('created', () => {
  expect(response.status).toBe(201)
  expect(response.json).toHaveProperty('id')
})
vars.set('orderId', String(response.json.id))   // the next request can use {{orderId}}