Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 30 ยท Writing Tests and Scripts

Chaining requests and workflows

Learn to chain Postman requests: save tokens and ids from responses, reuse them in later requests, control order with setNextRequest and clean up.

Real APIs are rarely used one request at a time. You log in and receive a token. You create an order and receive its id. You use the token and the id to read, change and finally delete that order. Each step needs something that the previous step produced. Chaining means exactly this: a script in one request saves a value from its response, and the following requests use that value.

Chaining turns a pile of separate requests into a workflow: a short story such as "sign in, create, read, update, delete, confirm it is gone". Run from top to bottom, the story is one test of the whole life cycle of a resource, and it needs no copy-and-paste from you.

This lesson uses the scripting basics from Writing tests with pm.test and Chai and the variable scopes from Environments and variables. Postman itself cannot run here, so its scripts are shown in read-only blocks, and the runnable examples are stand-ins: a small in-memory API and a tiny runner written in plain JavaScript that copy the idea honestly, not the real product.

Saving a value from a response

Every request in Postman has a Tests tab (the script that runs after the response arrives). That is where you read the response and store what the next request needs. The usual tools are:

JavaScript
// Tests tab of the "Log in" request (real Postman script, read-only here)
const body = pm.response.json();

pm.test("login succeeded and returned a token", function () {
  pm.response.to.have.status(200);
  pm.expect(body.token).to.be.a("string").and.not.empty;
});

// Save it so later requests can use it.
pm.collectionVariables.set("token", body.token);

Which scope should you use? You met them before; for chaining the choice matters:

  • pm.collectionVariables.set(...) keeps the value for the whole collection. It is a good default for tokens and ids made during a run.
  • pm.environment.set(...) stores it in the active environment, which is handy when you want to look at it afterwards or share it between collections.
  • pm.variables.set(...) creates a local variable that lives only for the current request or run. It is the tidiest choice for throwaway values and never leaks into saved files.
  • pm.globals.set(...) is visible everywhere. Use it rarely, because anything can overwrite it.

Save only what you need. A response may contain fifty fields, but the next request usually needs one id and maybe one token. Small, well-named variables (orderId, not data) keep the chain readable.

Using the value in the next request

Saved values are inserted with double curly braces. In the request builder you write them in the URL, the headers, the body or the Authorization tab:

TEXT
GET  {{baseUrl}}/orders/{{orderId}}
Authorization: Bearer {{token}}

Before the request is sent, Postman replaces each {{name}} with the variable's current value. If a variable does not exist, the placeholder stays in the text as it is, so you would send a request to /orders/{{orderId}} and the server would answer with an error. Seeing a literal {{...}} in the Postman Console is the classic sign that an earlier request did not save its value (or ran in the wrong order).

The first stand-in shows both halves in miniature: a variable store, a resolve function that replaces placeholders, and three requests that depend on each other.

JS A chain: log in, create, read

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line sends a request whose URL still contains {{missingId}}. The fake server answers 404, and the printed URL shows the unresolved placeholder, exactly the symptom you would spot in a real console.

A CRUD workflow

The most common chain walks through the four CRUD operations (create, read, update, delete) on one resource and then proves the delete worked.

One resource, five requests

Log in Save the token.
Create Expect 201. Save the id.
Read Check the stored data.
Update Change a field. Check it.

Every step uses a value saved by an earlier step.

1 / 2

Order in a collection is simply the order of requests, top to bottom, within folders. A well-named folder such as "Order life cycle" holds the whole story. Give every request a name that says what it does ("Create order", not "Request 7"), because those names appear in run reports and, as you will see next, a script can jump to a request by name.

Each request should also carry its own tests. The create request checks for 201; the read request checks that the item matches what was sent; the final read checks for 404. Chaining is not a replacement for assertions; it only supplies the data that lets the assertions happen.

Controlling the order with setNextRequest

By default the runner goes through the requests in order. A script can change that with pm.execution.setNextRequest(...), which tells the runner which request to run next.

JavaScript
// Jump to a named request (real Postman script, read-only here)
pm.execution.setNextRequest("Check job status");

// Stop the whole run after this request
pm.execution.setNextRequest(null);

Rules worth remembering:

  • It only has an effect when the collection runs in the Collection Runner, in Newman or in a monitor. If you click Send on one request, nothing jumps anywhere.
  • The argument is the request's name (an id also works). Use unique names, so the target is unambiguous.
  • If a script calls it more than once, the last call wins.
  • Passing null ends the run after the current request.
  • You may still see the older form postman.setNextRequest(...) in old collections. It does the same job; prefer the pm.execution form in new work.

The most useful pattern is polling. Suppose creating an order starts a background job, and the order only becomes ready after a moment. Instead of guessing a delay, you repeat the status request until it says ready, with a limit so it cannot loop forever:

JavaScript
// Tests tab of "Check job status" (real Postman script, read-only here)
const body = pm.response.json();
const attempts = Number(pm.collectionVariables.get("attempts") || 0) + 1;
pm.collectionVariables.set("attempts", attempts);

if (body.status !== "ready" && attempts < 5) {
  pm.execution.setNextRequest("Check job status"); // try again
} else {
  pm.test("job finished in time", function () {
    pm.expect(body.status).to.equal("ready");
  });
  pm.collectionVariables.unset("attempts");
}
flowchart LR
  A["Create order"] --> B["Check job status"]
  B -->|"not ready and attempts below 5"| B
  B -->|"ready, or attempts used up"| C["Update order"]
  C --> D["Delete order"]
  D --> E["Confirm 404"]

The only arrow that goes backward is the retry loop. The attempt counter guarantees that it ends.

Use setNextRequest sparingly. A collection that jumps all over the place is hard to read and hard to run in the Collection Runner with a different order. Straight top-to-bottom flows, with polling as the one exception, are easier to maintain.

A complete flow in a stand-in runner

The next example is a mini runner. It holds a list of named requests, runs them in order, lets each script call setNextRequest, and keeps a variable store. It runs on the server-side Node runner, so it is also a good way to see the idea outside the browser. The "API" is an in-memory object, and the job becomes ready on the third status check, so the polling loop really repeats.

Node.js Walking a CRUD flow with polling and cleanup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the log. "Check job status" is sent three times because the script kept pointing back at itself until the order was ready. After the "Confirm it is gone" request, the script removes orderId, token and attempts, so the variables left over at the end are an empty object. That is the flow you would build in Postman, with the real pm object instead of this stand-in.

What is real and what is not: the variable resolution, the retry loop idea and the attempt counter are the same logic you use in Postman scripts. The runner, the pm object and the API are plain JavaScript written for this lesson. Postman's real runner has more features (iterations, data files, a results view) that the next lessons cover.

Cleaning up

A chain that creates data must remove it. Otherwise each run leaves an extra order in the test system, and later runs may fail because of leftovers (unique names clash, lists grow, counts stop matching).

  • Delete what you create. Put a "Delete order" request at the end of the flow, followed by a request that confirms the 404.
  • Make data unique per run. Dynamic variables such as {{$guid}}, {{$randomInt}} and {{$timestamp}} generate fresh values, so two runs (or two teammates) do not collide.
  • Clear variables. pm.collectionVariables.unset("orderId") stops a stale id from sneaking into the next run.
  • Plan for failure. If a run stops halfway (for example, with setNextRequest(null) after a failed login), the delete request never runs. For important suites, add a separate cleanup folder or a nightly job that removes leftover test data.

Common pitfalls

  • Wrong scope. A value saved with pm.variables.set in one request is not available in the next request of a later run. Use the collection or environment scope for values that must survive between requests.
  • Typing the wrong name. orderID and orderId are different variables. Look at the variable list in the Quick Look panel when something resolves to nothing.
  • Hidden dependencies. If the "Read" request only works after "Create" ran, say so in the request description, and keep the folder in order. Someone who runs one request alone should understand why it fails.
  • Unbounded loops. Every polling loop needs a maximum attempt count.
  • Saving secrets in shared places. A token is sensitive. Prefer a current value in an environment or a local variable over writing it into a collection that you share.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which line saves an order id from a response so a later request can use it as {{orderId}}?

    A variable is stored with a scope's set method. The value is read from the parsed response body, and later requests insert it with double curly braces.
  2. 2. You click Send on a single request whose script calls pm.execution.setNextRequest('Cleanup'). What happens?

    setNextRequest only controls the order during a collection run. For a single manual send it has no effect.
  3. 3. Why should a polling loop built with setNextRequest keep an attempt counter?

    Without a limit, a job that never finishes would make the runner repeat the same request endlessly.
  4. 4. A request URL appears in the console as /orders/{{orderId}}. What is the most likely cause?

    Unresolved variables stay in the text as written. A literal placeholder means no value was found for that name.

Summary

  • Chaining saves a value in one request's script (a token, an id) and uses it in later requests with {{name}}.
  • Pick the scope on purpose: collection or environment variables for values that must survive between requests, local variables for throwaway values.
  • A CRUD flow creates, reads, updates, deletes and then confirms the 404, with tests in every step.
  • pm.execution.setNextRequest(name) changes the run order, but only in the Runner, Newman and monitors; null stops the run.
  • Polling loops need a maximum attempt count.
  • Clean up what you create, make test data unique, and unset leftover variables.
  • The runnable examples are plain-JavaScript stand-ins; the real scripts are shown read-only.

Next: The Collection Runner and data-driven testing.