API Testing
Beginner 10 min read API Testing

Postman Workflows

Postman turns raw API calls into reusable collections with variables, environments, JavaScript test scripts and a runner. Chain requests so one response feeds the next, then run the same collection in CI with Newman.

PostmancollectionsenvironmentsNewmanpre-request scriptstest scripts
Prerequisites: API Testing Basics
Introduction

What is this?

Postman organizes API calls into collections: requests grouped in folders, parameterized with variables, and extended with JavaScript pre-request and test scripts. Environments swap base URLs, tokens and credentials between dev, staging and prod without touching the requests. Because collections are runnable files, the same workflows that document the API also regression-test it.

Motivation

Why do you need it?

  • Collections package the entire API surface into shareable files a whole team can import and run.
  • Environments swap base URLs, tokens and credentials between dev, staging and prod without editing requests.
  • Test scripts run JavaScript assertions after every response, so collections double as executable documentation.
  • The Collection Runner and Newman execute the same flows in CI, turning Postman into a real test harness.
  • Pre-request scripts generate signatures, timestamps or tokens before each request is sent.
Think about it

Mental model

Imagine

A flight checklist

Think of

A Postman collection

Pilots run the same numbered checklist every flight, ticking each item in order. A collection encodes the same discipline: every request, assertion and handoff between steps is scripted, repeatable, and can be run by anyone on the crew.

Mechanics

How it works

  • Design a request in Postman — method, URL, params, headers and body — stored inside a collection folder.
  • Define environments with variables for baseUrl, token and ids so the same request runs anywhere.
  • Attach pre-request and test scripts written in JavaScript to prepare data and assert on results.
  • Use pm.response.json() and pm.environment.set() to extract values from one response and feed the next request.
  • Run the whole collection in the Runner or via the Newman CLI and publish a pass/fail report.

A Postman workflow: request scripts extract values that later requests consume.

Runner / Newman
Login request
Token response
Authenticated request
Assertions
Report
Reference

Key commands

npm install -g newman

Install the Newman CLI so collections can run headless in CI.

newman run orders.postman_collection.json -e staging.postman_environment.json

Run a collection against a specific environment.

✔ auth (200)\n✔ create order (201)\n┌─────────────────────────┐\n│ iterations: 1           │\n│ assertions: 4/4 passed  │\n└─────────────────────────┘
newman run orders.postman_collection.json --folder auth

Run only one folder of a collection, useful for fast targeted checks.

newman run orders.postman_collection.json --env-var "token=abc123"

Override an environment variable for a single run.

newman run orders.postman_collection.json --reporters cli,html --reporter-html-export report.html

Generate an HTML report alongside the CLI output for publishing.

Hands-on

Examples

Login, extract a token, and reuse it

Login, extract a token, and reuse it
// ---- Pre-request script on the login request ----
pm.environment.set("requestTime", new Date().toISOString());
// ---- Response body from POST /auth/login ----
// { "token": "eyJhbGciOi...", "expiresIn": 3600 }
// ---- Test script on the login request ----
const json = pm.response.json();
pm.test("status is 200", function () {
pm.response.to.have.status(200);
});
pm.test("token is present", function () {
pm.expect(json).to.have.property("token");
});
pm.environment.set("accessToken", json.token);
// ---- Header on every later request ----
// Authorization: Bearer {{accessToken}}

The test script asserts the login response, then stores the token with pm.environment.set. Later requests reference {{accessToken}} in their Authorization header. When the token expires you rerun login first — the same variable is refreshed and every downstream request follows.

Real world

In production

  • Teams version-control exported collections and run them via Newman as smoke tests on every deploy.
  • New developers run the collection against staging to learn the API hands-on instead of reading docs.
  • Partner teams consume a published collection as the source of truth for how to call the API.
  • Postman Monitors schedule collections on an interval to alert on endpoint failures without a custom agent.
Guidelines

Best practices

  • Store secrets in environments, never inside request bodies, and keep sensitive environment files out of git.
  • Write one focused assertion per pm.test so a failing test names exactly what broke.
  • Chain data with variables instead of copy-pasting hard-coded ids and tokens.
  • Keep collections modular — one folder per resource or feature, with auth handled by a shared login request.
  • Add an auth pre-request script that refreshes a token so long runs do not fail from expiry.
Watch out

Common mistakes

  • Hard-coding a manually copied token, then wondering why the collection fails an hour later.
  • Cramming a request with dozens of assertions that are impossible to triage when one fails.
  • Committing the production environment file with live secrets into the repository.
  • Assuming a green run means the API is correct — Postman only checks what you actually assert.
Root cause analysis

Common issues

Error
ReferenceError: token is not defined
Root cause

The variable was never set, or it lives in a different scope than the one in use.

Fix

Run the login request first, or set the variable at environment or collection scope, then check the Console.

Error
401 in collection runs but 200 when tested manually
Root cause

The runner is using a different environment, or the stored token expired mid-run.

Fix

Confirm the environment selected in the runner matches, and add a token-refresh pre-request script.

Error
Newman: ENOENT, no such file
Root cause

The collection path is relative to a different working directory in CI.

Fix

Use an absolute path or set the working-directory of the CI job before invoking newman.

When things break

Debugging tips

  • Open View → Show Postman Console to see the exact request, response and timing of any call.
  • Check the Test Scripts tab for runtime errors — a typo in a variable name silently skips assertions.
  • Add console.log() calls in pre-request and test scripts to inspect variable values mid-flow.
  • Run a single failing request in isolation with the environment selected before running the whole suite.
Interviews

Interview checkpoint

Practice

Hands-on lab

Chain Login to an Authenticated Request
30 min · beginner
In progress
Objectives
  • Create a collection and an environment with variables
  • Write a test script that extracts a token from a login response
  • Reference the token from a later request header
  • Run the flow in the Runner and then headlessly with Newman

Chain Login to an Authenticated Request

30 min · beginner

0/5 steps
0%
sandbox · Linux sandbox
$
Try these commands
Test yourself

Quick quiz

0/3
1

Which Postman scope is designed to hold environment-specific values like baseUrl and API keys?

2

pm.response.to.have.status(200) is JavaScript that runs after the request completes.

3

A 40-request collection run fails at request 10 with 401. Which cause is most likely?

Quick reference

Cheat sheet

Newman CLI
newman run col.jsonRun a collection
newman run col.json -e env.jsonRun with an environment
newman run col.json --folder authRun one folder
newman run col.json --bailStop at first failure
newman run col.json --reporters junit,htmlEmit CI-friendly reports
Key pm.* APIs
pm.test('name', fn)Define an assertion block
pm.response.to.have.status(200)Assert the status code
pm.response.json()Parse the response body
pm.environment.set('k', v)Persist a value for later requests
pm.variables.get('k')Read any scoped variable
Go deeper

Official documentation