Testing APIs

Scripts

JavaScript before a request and on its answer — Postman's pm.test and pm.environment, so scripts from Postman collections run as they are.

Most tests need no code: checks, saved values and built-in values cover them. When you need more — compute a value, sign something, test a rule that spans fields — open the Scripts tab. There are two:

  • Pre-request runs before the request is sent. It can set values, add or change headers, change the address or the body.
  • Tests runs on the answer. Each pm.test(…) counts like a check: on Send, in collection runs and CI, and for every request of a performance test, where the report shows its pass rate like any other check.

The scripts use Postman's pm object, so scripts from an imported Postman collection run as they are. The Add buttons above each script put in a working example to change.

// Tests
pm.test("status is 200", () => pm.response.to.have.status(200));
pm.test("has items", () => {
  const body = pm.response.json();
  pm.expect(body.items).to.be.an("array").that.is.not.empty;
  pm.expect(body.total).to.be.above(0);
});
// Keep the token for the requests after this one
pm.environment.set("token", pm.response.json().token);
// Pre-request
pm.environment.set("orderRef", "ord-" + Date.now());   // use it as {{orderRef}} in this request
pm.request.headers.upsert({ key: "X-Request-Id", value: "{{$uuid}}" });

What scripts can use

pm.test(name, fn)A test: passes unless fn throws. A failed one shows why, e.g. expected 404 to equal 200.
pm.expect(value)Assertions, as in Postman (Chai): .to.equal(x), .to.eql(obj) (deep), .to.be.above(n) / .below(n) / .within(a, b), .to.be.a("string"), .to.include(x), .to.have.property("id", 7), .to.have.lengthOf(3), .to.match(/re/), .to.be.oneOf([…]), .to.be.ok / .true / .null / .empty, and .not before any of them.
pm.response.code, .responseTime (ms), .json(), .text(), .headers.get(name); .to.have.status(200), .to.have.header(name), .to.be.ok. Tests only.
pm.request.method, .url.toString() / .url.update(…), .headers.get / .add / .upsert / .remove, .body.raw / .body.update(…). Changes count in the pre-request script.
pm.environment, pm.variables, pm.collectionVariables, pm.globals.get(name), .set(name, value), .unset(name), .has(name). They all read the same values: your environment, folder variables and saved values.
pm.info.requestName, .iteration (in a performance test, the count for this simulated user), .eventName.
pm.sendRequest(…)Make another request from the script — to sign in, look something up, or clean up. See below.
console.log(…)Shows under Console in the response (on Send).

Older Postman scripts work too: tests["name"] = true, responseBody, responseCode.code, responseTime, postman.setEnvironmentVariable(…).

Make a request from a script: pm.sendRequest

Sometimes a request needs something from another request first — most often a token. pm.sendRequest makes that other request from inside the script, and gives you its answer. It is Postman's, so scripts that use it run as they are.

Sign in before the request

The most common use: get a token in the pre-request script, then use it in the request.

// Pre-request
pm.sendRequest({
  url: "{{baseUrl}}/login",
  method: "POST",
  header: { "Content-Type": "application/json" },
  body: { mode: "raw", raw: JSON.stringify({ username: "{{user}}", password: "{{password}}" }) }
}, (err, res) => {
  if (err) throw err;                                   // the server couldn't be reached
  pm.environment.set("token", res.json().access_token);
});

Then on the Auth tab choose Bearer with {{token}} — the token is filled in after the script runs. (Auth is added after the pre-request script, so you set the value here, not the header.)

The two ways to write it

With a callback — the classic Postman way. The function gets an error (or null) and the answer:

pm.sendRequest("{{baseUrl}}/health", (err, res) => {
  pm.test("health is up", () => pm.expect(res.code).to.equal(200));
});

With await — shorter when you need the answer before the next line:

const res = await pm.sendRequest("{{baseUrl}}/orders/latest");
pm.environment.set("orderId", res.json().id);

With await, an address that can't be reached throws an error — the script stops there and says why. With a callback, the error comes to your function instead, so you can decide what to do.

A test can await too: pm.test("stock is there", async () => { const r = await pm.sendRequest(…); pm.expect(r.json().inStock).to.be.true; });

What you can send

Just an addresspm.sendRequest("https://api.example.com/health", cb) — a GET.
urlThe address. {{variables}} are filled in.
method"GET", "POST", "PUT", … (default GET).
header{ "Name": "value" }, or Postman's list [{ key, value }], or "Name: value" lines.
body{ mode: "raw", raw: "…" } for JSON or text; { mode: "urlencoded", urlencoded: [{ key, value }] } for a form (sets the content type for you); { mode: "graphql", graphql: { query, variables } }. Files can't be sent from a script — send them from a request's body.

The answer is like pm.response: .code, .status, .responseTime, .json(), .text(), .headers.get(name).

How it's sent

  • With this request's settings: the same timeout, certificate check and client certificates, and the cookie jar — so a login that sets a cookie signs in the request after it.
  • Without auth of its own — put what it needs (an API key header, say) in header.
  • From the app, not from the script: the sandbox still can't reach the network itself; it asks the app, which sends the request and hands back the answer.
  • At most 20 per script run, and a script may take 60 seconds in all (the waiting for answers doesn't count towards the 2 seconds of running).

In a performance test

The script runs for every request, so a sign-in in the pre-request script would sign in every time — and your login server gets as much load as the API. Usually you want one token per simulated user, kept until you need a new one:

// Pre-request: sign in only when this simulated user has no token yet
if (!pm.environment.get("token")) {
  const res = await pm.sendRequest({ url: "{{baseUrl}}/login", method: "POST", body: { mode: "raw", raw: "{{credentials}}" }, header: { "Content-Type": "application/json" } });
  pm.environment.set("token", res.json().access_token);
}

Values a script sets are kept for each simulated user's next requests, so this signs in once per user. (Or use Run first, which signs in once before the whole test.)

Requests made with pm.sendRequest are left out of the load numbers — requests, requests per second, response times and errors are about the request you are testing only. Its checks and tests still count.

Scripts on folders

When many requests need the same script — sign in, add a signature header, check that every answer is JSON — write it once on their folder instead: ⋯ → Folder settings → Scripts on the folder. It has the same two scripts, Pre-request and Tests.

They run for every request inside the folder and its subfolders, in this order:

  1. the outer folder's script,
  2. then each folder inside it, down to the request's folder,
  3. then the request's own.

Pre-request scripts run in that order before the request is sent; tests scripts in that order after the answer. It's the order Postman uses for collection, folder and request scripts.

// Folder "Orders API" → Scripts → Pre-request: sign in once per run, for every request inside
if (!pm.environment.get("token")) {
  const res = await pm.sendRequest({ url: "{{baseUrl}}/login", method: "POST",
    header: { "Content-Type": "application/json" },
    body: { mode: "raw", raw: JSON.stringify({ username: "{{user}}", password: "{{password}}" }) } });
  pm.environment.set("token", res.json().access_token);
}

// Folder "Orders API" → Scripts → Tests: true of every answer
pm.test("answers in JSON", () => pm.response.to.be.json);
pm.test("answers within 1 s", () => pm.expect(pm.response.responseTime).to.be.below(1000));

Good to know:

  • Each script runs in its own block, so a folder's script and a request's can both declare const res without a clash. Values set with pm.environment.set are shared — that's how a folder's script hands a token to the request.
  • A request's Scripts tab says which folders' scripts run before it.
  • If a folder's pre-request script fails, the request isn't sent, and the error says which script failed.
  • Importing from Postman keeps scripts where they were: a collection's or folder's scripts go on that folder, a request's on the request.

Values scripts set

pm.environment.set("name", value) (or any of the others) gives {{name}} a value:

  • In the pre-request script, for this request — {{name}} in the address, headers or body is filled in after the script runs, as in Postman — and for the requests after it.
  • In the tests script, for the requests after it — like Save values. After a Send they show next to the environment picker as Saved from answers; in a collection run they go to the next requests.

Values are text; a number or object is stored as its JSON. They are not written into your environment file — like saved values, they last until you close the app (or the run ends). In a performance test each simulated user keeps its own.

Safe to run

Scripts run in a sandbox — a separate JavaScript engine (QuickJS in the app, k6's own in performance tests). A script sees the request, the answer and your values, and nothing else: not your files, not the network, not other programs, not the app. So a script inside a collection someone sent you can't harm your computer. A script may run for at most 2 seconds and use at most 64 MB; one that runs longer is stopped and reported.

Good to know

  • Auth is added after the pre-request script, so the script doesn't see the Authorization header and can't break signing (OAuth 1.0, AWS). It can still set a value that auth uses, like {{token}}.
  • A pre-request script that fails stops the request — the error says why. A tests script that fails counts as a failed test named Tests script; tests before the failure still count.
  • Not yet: require(…) of libraries, setTimeout, and pm.visualizer. Waiting for anything other than pm.sendRequest ends the script with “waiting for something that never happens”.
  • Performance tests: scripts run for every request, so keep them short. console.log isn't shown during performance tests.
  • Folders: a Postman collection's or folder's scripts become that folder's scripts, and run before each request's own — the order Postman runs them in.

Something unclear or missing? Write to support@apitestcenter.com — the guide improves with every question.