Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 30 ยท Projects and Practice

Postman and API testing cheat sheet

A one-page Postman and API testing cheat sheet: pm.* snippets, status codes, variable scopes, Newman flags, shortcuts and a test checklist.

This is a reference page to keep open while you work. It collects the snippets, tables and checklists from the whole track in one place, with links back to the lessons that explain each idea. It assumes you already know the basics; if something looks unfamiliar, follow the link.

Every Postman script and Newman command below is read-only: Postman and Newman cannot run on this site. Two small runnable stand-ins at the end let you practice looking up status codes and resolving variables in plain JavaScript.

What is on this page

Snippets pm.test, pm.expect, variables.
Status codes The ones you meet daily.
Scopes Which variable wins.
Newman Flags and exit codes.
1 / 2

Test snippets (Tests tab)

JavaScript
// Status
pm.test("status is 200", () => pm.response.to.have.status(200));
pm.test("status is one of 200 or 201", () => pm.expect(pm.response.code).to.be.oneOf([200, 201]));

// Response time budget
pm.test("fast enough", () => pm.expect(pm.response.responseTime).to.be.below(500));

// Headers
pm.test("is JSON", () => pm.response.to.have.header("Content-Type"));
pm.test("content type", () =>
  pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json"));

// Body
const body = pm.response.json();
pm.test("has id", () => pm.expect(body).to.have.property("id"));
pm.test("name matches", () => pm.expect(body.name).to.eql("Ada"));
pm.test("items is a non-empty array", () => pm.expect(body.items).to.be.an("array").that.is.not.empty);
pm.test("body contains text", () => pm.expect(pm.response.text()).to.include("created"));

// Skip a test when it does not apply
pm.test.skip("not ready yet", () => {});

Learn more: Writing tests with pm.test and Chai.

Pre-request snippets

JavaScript
// Timestamps and dynamic data
pm.variables.set("now", new Date().toISOString());
pm.variables.set("uniqueEmail", "user-" + Date.now() + "@example.test");

// Read what the request is about to send
console.log(pm.request.method, pm.request.url.toString());

// Add a header from a variable
pm.request.headers.add({ key: "X-Request-Id", value: pm.variables.replaceIn("{{$guid}}") });

Learn more: Pre-request scripts.

Variables

JavaScript
// Set, get, remove (one scope each)
pm.globals.set("name", "value");
pm.collectionVariables.set("name", "value");
pm.environment.set("name", "value");
pm.variables.set("name", "value");          // local, this run only

pm.environment.get("name");
pm.variables.get("name");                    // resolves through all scopes
pm.environment.unset("name");
pm.variables.replaceIn("{{baseUrl}}/users"); // resolve placeholders in a string

// Data from the Collection Runner file (one row per iteration)
pm.iterationData.get("qty");

// Built-in dynamic variables (use as {{$name}})
// {{$guid}}  {{$timestamp}}  {{$randomInt}}  {{$randomEmail}}
Scope Lives Priority (1 = wins) Typical use
Local One request or run 1 Throwaway values
Data One iteration of a run 2 CSV or JSON rows
Environment Until you change it 3 Base URL, credentials per stage
Collection With the collection 4 Tokens and ids made during a run
Global Everywhere 5 Rare, shared values

Learn more: Environments and variables.

Flow control

JavaScript
pm.execution.setNextRequest("Request name"); // jump (Runner, Newman, monitors only)
pm.execution.setNextRequest(null);           // stop after this request

Always cap loops with an attempt counter. Learn more: Chaining requests and workflows.

Status codes you meet every day

Code Meaning Test it when
200 OK A read or update succeeded
201 Created A POST created a resource (also check Location or the body id)
204 No Content A delete succeeded; the body is empty
301 / 302 Redirect Moved resources; check the Location header
304 Not Modified Caching with ETag
400 Bad Request Malformed JSON or syntax
401 Unauthorized Missing, expired or bad credentials
403 Forbidden Known user, no permission
404 Not Found Missing resource, or a deleted one
409 Conflict Duplicate or version clash
422 Unprocessable Content Valid JSON, invalid data
429 Too Many Requests Rate limit; look for Retry-After
500 Server Error A bug; should never be the expected result
503 Service Unavailable Overload or maintenance

Methods: GET, HEAD, PUT, DELETE and OPTIONS are idempotent; POST is not. GET and HEAD are safe (they change nothing). See HTTP and REST in ten minutes.

Authentication quick reference

Type What goes on the wire
API key A header such as X-API-Key: value or a query parameter
Basic Authorization: Basic base64(user:password)
Bearer Authorization: Bearer <token>
OAuth 2.0 A bearer access token obtained from an authorization server; refresh when it expires

Basic is only encoded, not encrypted, so use it over HTTPS. See Authentication in Postman.

Newman

Terminal
# Install and run (real commands, read-only here)
npm install -g newman
newman run collection.json
newman run collection.json -e staging.json
newman run collection.json -d data.csv -n 3
newman run collection.json --folder "Order life cycle"
newman run collection.json --env-var "token=$API_TOKEN"
newman run collection.json --delay-request 200 --timeout-request 5000
newman run collection.json --bail
newman run collection.json --reporters cli,junit --reporter-junit-export results.xml
Flag Meaning
-e, --environment Environment file
-g, --globals Globals file
-d, --iteration-data CSV or JSON data file
-n, --iteration-count Number of iterations
--folder Run only a folder
--env-var Override one variable
--bail Stop at the first failure
--delay-request Milliseconds between requests
--timeout-request Per-request timeout
--reporters cli, json, junit, html (html needs an extra package)

Exit code 0 means all passed; non-zero means a failure, which is what fails a CI job. Learn more: Newman, the CLI and CI/CD.

Handy shortcuts

Shortcuts differ slightly between systems; on macOS use Cmd instead of Ctrl. These are common defaults in the desktop app:

Action Shortcut
Send request Ctrl+Enter
New request tab Ctrl+T
Close tab Ctrl+W
Open the Console Ctrl+Alt+C
Search Ctrl+K
Toggle sidebar Ctrl+\

If one does not work in your version, look in Settings, Shortcuts.

Test design checklist

  • Happy path returns the right status and body.
  • Required fields missing: expect a clear client error.
  • Wrong types and invalid values: expect 400 or 422.
  • Boundaries: just below, on and just above each limit.
  • Authentication: no token, bad token, expired token.
  • Authorization: another user's resource must not be reachable.
  • Idempotency: repeat PUT and DELETE; check the result.
  • Lists: empty, one item, a full page, the next page.
  • Created data is deleted at the end; test data is unique per run.
  • Every loop has a limit, and no test depends on another run's leftovers.
  • Secrets are in current values or the CI secret store, never in the repository.

See API testing strategy and test design.

Two stand-ins to practice with

Looking up the meaning of a code is a tiny task, but it is the sort of helper you end up writing in scripts.

JS Status code lookup

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

No output.

Resolving {{variables}} through scopes is the other classic. This version walks the scopes in priority order and reports where each value came from.

JS Resolve variables by scope priority

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which status code best fits valid JSON that fails a business rule, such as a negative amount?

    422 means the request was understood but the data is invalid. 400 is also used for malformed syntax.
  2. 2. Which Newman flag stops a run at the first failing test?

    --bail stops the run on the first failure. The other flags set delays, pick a folder or choose report formats.
  3. 3. A variable exists in the environment and as a local variable. Which value is used?

    Local variables take priority over data, environment, collection and global ones.
  4. 4. What does setNextRequest(null) do in a script?

    Passing null ends the collection run after the current request, in the Runner, Newman and monitors.

Summary

  • Keep the pm.test and pm.expect snippets for status, headers, timing and body checks.
  • Variables resolve local, data, environment, collection, global, in that order.
  • Know your status codes, especially 401 versus 403 and 400 versus 422.
  • Newman runs collections in CI; a non-zero exit code fails the job, and --env-var passes secrets at run time.
  • Use the checklist to review a suite: negative cases, boundaries, authorization, cleanup and finite loops.
  • The Postman scripts and Newman commands here are read-only references; only the two stand-ins run.

You have reached the end of the track. Revisit Practice exercises with solutions whenever you want more practice.