Bookmarks
ReferenceTesting (QA)Verified

API testing

API testing — checking an HTTP API with direct requests. In this reference: response checks, JSON Schema and OpenAPI, authorisation, contract testing, Postman.

checked 1 Nov · next check 8 Nov · 46 min read

Sections
12
Reading
46 min
Languages
RU · UZ · EN
Written from
learning.postman.com/docs

Check status of the reference

Verified 1 Nov · next check 8 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What API testing is and how it works

API testing is checking an HTTP API directly, without a user interface: a test sends a request and compares the status code, headers, body and response time against expectations. Faults in the service surface earlier and more precisely this way than through the interface.

Five things are checked in an API. Functionality: the operation does what it promises. Contract: the response matches the specification and the schema. Authorisation: anonymous and third-party requests are rejected. Error handling: an invalid request receives the right refusal. Side effects: the data has actually changed. By purpose, such tests are integration, end-to-end and regression tests; behaviour under load is checked separately — that is the subject of the “Load testing” reference.

Every check is an exchange of HTTP messages: a request (method, address, headers, body) and a response (status code, headers, body). Methods, codes and headers as such are described in the “HTTP and REST” reference; here the point is how to check them.

The work runs as a pipeline. An OpenAPI specification describes the operations and response schemas. Test conditions are selected from it using test design techniques. The conditions turn into requests with checks — a Postman collection or tests in code. The suite runs in CI on every change, and the report shows which check failed.

Expectations come from the specification, not from what the service returned last time.

Postman, tests in code or Playwright

ToolWhat tests look likeWhen to choose it
Postmanrequests in a collection, checks written as JavaScript scripts; run in the app or through the Postman CLIAPIs are tested by testers, a quick start is needed, and requests are shared with the team
pytest and httpxtests in Python in the service’s repositorytests are written and maintained by developers alongside the code; details in the “pytest” reference
Playwrightrequests through the request fixture in the same tests as the browserdata needs to be prepared through the API before a UI test, or the server checked after actions in the browser

What to check does not depend on the tool: the syntax changes, not the set of checks. Use the tool your team already writes on.

What to know in advance

  • HTTP: methods, status codes, headers — the “HTTP and REST” reference
  • Choosing checks: equivalence classes and boundary values — the “Test design” reference
  • The JSON format: objects, arrays, value types
  • JavaScript basics — for Postman scripts, the “JavaScript” reference

Section sources

the section is written from these pages

Checklist

Work through the list for every API operation — a method and path pair, such as POST /orders — before counting it as tested. Every item is explained in the sections of the reference.

Successful response

  • Check the exact status code: 201 after creation, 200 after reading, 204 after deletion without a body — not “any 2xx”.
  • Check the Content-Type header: application/json or the type from the specification.
  • Check the values of required fields, not just that the body is not empty.
  • After 201, check the Location header and read the resource at that address.

Schema

  • Check the body against the schema from the specification — for every response code, including errors.
  • Make sure the response does not return extra properties: passwords, internal flags, other users’ data.

Errors

  • Send a body without a required field and with a wrong type: expect 400 or 422 — the code stated in the specification.
  • Send a body with an unsupported Content-Type: expect 415.
  • Request a resource that does not exist: 404. Call a method that is not allowed: 405 and the Allow header.
  • Create a conflict with the current state of a resource, for example pay for a cancelled order: 409.
  • If the specification has a rate limit, exceed it: expect 429 and, if the API returns one, the Retry-After header.
  • Check the format of the error body: problem details come with the application/problem+json type, and their status field, if present, matches the response code.
  • Make sure the error does not expose a stack trace or the internals of the server.

Authorisation

  • Send a request without a token: expect 401 and the WWW-Authenticate header.
  • Send an expired or corrupted token: 401 again.
  • Send a token with insufficient permissions: 403.
  • Request another user’s object by its id: 403 or 404, but not 200 with the data.
  • Call an administrator operation as an ordinary user: 403.

Data

  • Create the data a test needs inside the test itself and delete it afterwards.
  • Generate unique values — an email, a number — on every run.
  • Run the test on its own and in a different order with the rest: the result does not change.

Idempotency

  • Repeat PUT with the same body: the state of the resource is the same as after the first request.
  • Repeat DELETE: the resource remains deleted, although the code of the second response may differ, for example 404.

Automation

  • Run the suite in CI on every change so that a failed check stops the build.
  • Take addresses and secrets from CI environment variables and secrets rather than writing them into requests.
  • Save the run report together with the build.

Section sources

the section is written from these pages

Response checks

An assertion is a statement about the response you have received: the status code, a header, a field value, the time. In Postman, checks are written in JavaScript in the post-response script: pm.test gives the check its name, and pm.expect is the assertion itself, in Chai syntax.

The post-response script runs once the response has arrived, and the result of each pm.test is visible on the “Test Results” tab. A single pm.test can hold several assertions: the check passes only when all of them hold. Check the status code first, then Content-Type, then the body: with the wrong code, field checks would only clutter the report.

Worked example: creating an order

The request creates an order. By the specification, the service responds with 201 Created, the Location header carries the address of the new order, and the body contains the order with its id and the status new.

httpthe request in Postman
POST {{baseUrl}}/ordersContent-Type: application/jsonAuthorization: Bearer {{accessToken}} {"sku": "BOOK-42", "quantity": 2}
javascriptthe request’s post-response script
pm.test("status is 201", () => {  pm.response.to.have.status(201);}); pm.test("body is JSON", () => {  pm.expect(pm.response.headers.get("Content-Type"))    .to.include("application/json");}); const order = pm.response.json(); pm.test("Location points to the new order", () => {  pm.expect(pm.response.headers.get("Location"))    .to.include(`/orders/${order.id}`);}); pm.test("order fields", () => {  pm.expect(order.id).to.be.a("string");  pm.expect(order.status).to.eql("new");  pm.expect(order.quantity).to.eql(2);}); // later requests in the scenario need the idpm.collectionVariables.set("orderId", order.id);

The body is parsed once, outside pm.test, and order is available to every later check in the script. The last line passes the id on: the next request in the scenario addresses the order as {{baseUrl}}/orders/{{orderId}}. Write check names so that the report makes it clear what failed.

Common assertions

In the table, body is the result of pm.response.json().

What to checkHow to write it
A code from an allowed setpm.expect(pm.response.code).to.be.oneOf([200, 204])
A header is presentpm.response.to.have.header("ETag")
A field valuepm.expect(body.status).to.eql("paid")
A field typepm.expect(body.total).to.be.a("number")
A value from a listpm.expect(body.status).to.be.oneOf(["new", "paid"])
An object contains some of the fieldspm.expect(body).to.deep.include({ status: "new" })
None of the keys are in the responsepm.expect(body).to.not.have.any.keys("password")
A field equals nullpm.expect(body.paidAt).to.be.null
A substring in the bodypm.expect(pm.response.text()).to.include("BOOK-42")

eql compares deeply and strictly by type: the number 2 is not equal to the string "2". Without .deep, the include and members assertions compare objects by reference, so for objects write to.deep.include.

Arrays: length, elements, order

For a list, check that it is not empty and no longer than one page, that every element matches the filter and that the order matches what was requested. Order is checked by comparing against a sorted copy.

javascriptthe request’s post-response script
// GET {{baseUrl}}/orders?status=new&sort=total&limit=20const { items } = pm.response.json(); pm.test("page has 1 to 20 orders", () => {  pm.expect(items).to.be.an("array").that.is.not.empty;  pm.expect(items.length).to.be.at.most(20);}); pm.test("only new orders", () => {  items.forEach((o) => pm.expect(o.status).to.eql("new"));}); pm.test("sorted by total", () => {  const totals = items.map((o) => o.total);  pm.expect(totals).to.eql([...totals].sort((a, b) => a - b));});

to.include(x) checks that an element is present in the array, while to.have.members([...]) checks that the array consists of exactly those elements, in any order.

Response time

pm.response.responseTime is the time it took to receive the response, in milliseconds. A threshold in the test catches gross slowdowns, such as a request that suddenly started taking seconds. This is not a load test: a single request says nothing about behaviour under load — that is the subject of the “Load testing” reference.

javascriptthe request’s post-response script
pm.test("response time under 500 ms", () => {  pm.expect(pm.response.responseTime).to.be.below(500);});

The same test in pytest and httpx

If API tests live in the service’s repository, they are written as code. In httpx the response has status_code, headers and json(), and the checks are plain assert statements. Headers in httpx are case-insensitive: headers["content-type"] and headers["Content-Type"] are the same thing. Running tests, fixtures and parameterisation are covered in the “pytest” reference.

pythontests/test_orders.py
import os import httpx BASE_URL = os.environ["API_BASE_URL"]HEADERS = {"Authorization": f"Bearer {os.environ['API_TOKEN']}"}  def test_create_order():    response = httpx.post(        f"{BASE_URL}/orders",        json={"sku": "BOOK-42", "quantity": 2},        headers=HEADERS,    )    assert response.status_code == 201    content_type = response.headers["Content-Type"]    assert content_type.startswith("application/json")    order = response.json()    location = response.headers["Location"]    assert location.endswith(f"/orders/{order['id']}")    assert order["status"] == "new"    assert order["quantity"] == 2

Section sources

the section is written from these pages

Schemas: JSON Schema and OpenAPI

A schema describes what the structure of JSON should look like: types, required fields, allowed values. Validating a response against a schema catches what per-field checks miss: a field that has disappeared, null instead of a number, an unexpected property.

Schemas are written in JSON Schema. A schema is JSON too: keywords set constraints, and a response passes validation only if all of them hold. A keyword meant for a different type does not affect the value: minLength does not check a number, and format does not check an object. That is why the type is always set explicitly with type.

The keywords you need most often

KeywordWhat it checksExample
typethe type: string, number, integer, boolean, object, array, null; an array of types means any of them"type": ["string", "null"]
propertiesschemas for the individual fields of an object"properties": {"id": {"type": "string"}}
requiredfields that must be present"required": ["id", "status"]
additionalPropertiesfields not listed in properties; false forbids them"additionalProperties": false
itemsthe schema for each element of an array"items": {"type": "string"}
enum, consta value from a list; exactly one value"enum": ["new", "paid"]
minimum, maximumthe bounds of a number, inclusive"minimum": 1
minLength, maxLength, patternthe length of a string and a regular expression"pattern": "^[A-Z]+-[0-9]+$"
minItems, maxItems, uniqueItemsthe size of an array and the uniqueness of its elements"maxItems": 20
formatthe meaning of a string: date-time, email, uuid"format": "date-time"

integer is any number with a zero fractional part: 1 and 1.0 are the same to a schema.

A worked example: the order schema

In Postman, a response is checked against a schema with the assertion pm.response.to.have.jsonSchema(schema). The schema is declared in the script as an ordinary JavaScript object; Ajv options can be passed as a second argument.

javascriptthe request’s post-response script
// GET {{baseUrl}}/orders/{{orderId}}const orderSchema = {  type: "object",  required: ["id", "status", "sku", "quantity", "createdAt"],  properties: {    id: { type: "string", format: "uuid" },    status: { enum: ["new", "paid", "shipped", "cancelled"] },    sku: { type: "string", pattern: "^[A-Z]+-[0-9]+$" },    quantity: { type: "integer", minimum: 1 },    total: { type: "number", minimum: 0 },    createdAt: { type: "string", format: "date-time" },  },  additionalProperties: false,}; pm.test("order matches the schema", () => {  pm.response.to.have.jsonSchema(orderSchema);});

additionalProperties: false forbids fields that are not in properties: the test will notice if the response starts returning anything extra, such as an internal flag. But a legitimate new field will fail the check too, so only close the schema if the specification closes it as well.

A schema from an OpenAPI specification

In OpenAPI, the response schema sits in the operation description: paths → path → method → responses → status code → content → media type → schema. Usually that is a $ref to a shared schema in components/schemas. For a test, take the schema of the status code you expect: 200 and 404 have different schemas.

yamlopenapi.yaml
paths:  /orders/{id}:    get:      responses:        "200":          description: Order found          content:            application/json:              schema:                $ref: "#/components/schemas/Order"        "404":          description: No such order          content:            application/problem+json:              schema:                $ref: "#/components/schemas/Problem"

In OpenAPI 3.2, the Schema Object is a superset of JSON Schema 2020-12: all of its keywords plus a few of its own, such as discriminator and xml. The example field is deprecated; examples from JSON Schema replaces it. When you move a schema from such a specification into Postman, leave out the keywords newer than draft-07, or validate responses against it in code with a 2020-12 validator. The structure of an OpenAPI document is covered in the “HTTP and REST” reference, section “OpenAPI”.

Validating the specification itself

An error in the specification becomes an error in the expectations of every test. Spec Hub in Postman checks the specification’s syntax as you edit it. From an OpenAPI specification it generates a collection with folders, requests and response examples, and the collection can be updated to keep up with the specification. Spec Hub works with OpenAPI 2.0, 3.0 and 3.1; version 3.2 is not among the supported formats.

Section sources

the section is written from these pages

Authorisation in tests

An API test deals with authorisation twice. It obtains and sends the credentials itself to reach the operation, and separately checks that the API refuses requests without them, with someone else’s and with insufficient permissions. How OAuth and OIDC work is described in the “OAuth and OIDC” reference.

How credentials are passed

TypeWhere it is passedHeader example
API keyin a header or a query parameter; the API sets the nameX-API-Key: {{apiKey}}
BasicAuthorization: the login and password in Base64Authorization: Basic YWxpY2U6Y2hhbmdlLW1l
Bearer tokenAuthorization with the Bearer schemeAuthorization: Bearer {{accessToken}}
OAuth 2.0the token is obtained from the authorisation server and passed as BearerAuthorization: Bearer {{accessToken}}

In Postman, you choose the type on the “Authorization” tab of a request, folder or collection, and Postman adds the header itself. Keep the values — the key, the password, the token — in variables, not in the requests themselves. If the API expects a different prefix instead of Bearer, choose the “API Key” type with the key Authorization.

Bearer token and refusal responses

RFC 6750 requires servers to support tokens sent in the Authorization header with the Bearer scheme. A token should not be passed in the address (?access_token=): addresses end up in logs and browser history. The server explains a refusal with the WWW-Authenticate header:

SituationCodeWhat is in WWW-Authenticate
No credentials401Bearer realm="orders" with no error code
The token is expired, revoked or malformed401error="invalid_token"
Insufficient permissions (scope)403error="insufficient_scope"
The request is malformed400error="invalid_request"
httpresponse to an expired token
HTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer realm="orders",                  error="invalid_token",                  error_description="The access token expired"

To send a request without a token, choose “No Auth” on its “Authorization” tab and check both the code and the header:

javascriptthe request’s post-response script
// request without an Authorization headerpm.test("401 with a Bearer challenge", () => {  pm.response.to.have.status(401);  pm.expect(pm.response.headers.get("WWW-Authenticate"))    .to.include("Bearer");});

OAuth 2.0 token in Postman

With the “OAuth 2.0” type, Postman obtains the token itself. Choose the grant type: authorization code, including with PKCE, client credentials, or another one. Then enter the token endpoint address, the client ID and secret, and click “Get New Access Token”. If the server issued a refresh token, Postman renews the access token in the background before it expires.

For service tests, the client credentials grant is usually enough: the token is issued to the application, not to a user. A collection’s pre-request script runs before each of its requests, so it fetches a new token only when the saved one has expired:

javascriptthe collection’s pre-request script
// collection pre-request script: a client credentials token with cachingconst env = (name) => pm.environment.get(name);const saved = pm.collectionVariables.get("tokenExpiresAt"); if (Date.now() >= Number(saved || 0)) {  const response = await pm.sendRequest({    url: env("tokenUrl"),    method: "POST",    body: {      mode: "urlencoded",      urlencoded: [        { key: "grant_type", value: "client_credentials" },        { key: "client_id", value: env("clientId") },        { key: "client_secret", value: env("clientSecret") },      ],    },  });  const token = response.json();  pm.collectionVariables.set("accessToken", token.access_token);  // renew one minute before expiry  const ttl = (token.expires_in - 60) * 1000;  pm.collectionVariables.set("tokenExpiresAt", Date.now() + ttl);}

The collection’s requests use Bearer {{accessToken}}. The script reads clientSecret from the environment: locally it is the variable’s local value, in CI — the CI secret. Do not put the secret into the collection itself: when you hand the collection to someone else, the secret goes with it.

What to check

RequestExpected response
Without Authorization401, WWW-Authenticate: Bearer
With an expired or malformed token401, error="invalid_token"
With a token without the required scope403, error="insufficient_scope"
User B reads user A’s order403 or 404, no order data in the response
User B changes or deletes A’s order403 or 404; a GET as A shows that the order has not changed
A regular user calls an administrator operation403

Access to someone else’s object (BOLA)

Broken Object Level Authorization (BOLA) is the top risk in the OWASP API Security Top 10 2023. The API takes the object id from the request and does not check that the object belongs to the user. Comparing the user id from the token with a request parameter is not enough — that closes only some of the cases. The check needs two users: A creates an object, and B reaches it by id with every method that accepts this id.

javascriptthe request’s post-response script
// GET /orders/{{orderId}} with user B’s tokenpm.test("user B cannot read the order of user A", () => {  pm.expect(pm.response.code).to.be.oneOf([403, 404]);});

OWASP explicitly advises writing tests for the authorisation mechanism and not shipping changes where they fail.

Section sources

the section is written from these pages

Test data, variables and environments

A variable in Postman is a named value that gets substituted into a request as {{baseUrl}}. URLs, credentials and test values go into variables so that one collection works against dev and stage without editing requests.

Variable scopes

A variable lives in one of five scopes. If a name exists in several, the narrowest one wins. Values are stored as strings: objects and arrays are turned into a string with JSON.stringify() before being written, and parsed with JSON.parse() when read.

Scope, from broadest to narrowestWhere it is setWhat it is for
Globalthe whole workspace; pm.globalsquick experiments; in collections you actually work with — narrower scopes
Collectionthe collection; pm.collectionVariablesscenario values: orderId, a token
Environmentan environment, one active at a time; pm.environmentwhat differs between test environments: baseUrl, accounts
Datathe run’s CSV or JSON file; pm.iterationDatainput values, one set per iteration
Locala script, pm.variables.set(); lives until the end of the request or runa temporary value on top of all the others

In a script, pm.variables.get("baseUrl") returns the value from the narrowest scope that has this name. By default, a variable’s value is the local value: it is stored only in your Postman and is not synchronised. A shared value goes to Postman Cloud and is visible to the team. Cloud-based features use the shared value too: scheduled runs, monitors and Postman CLI.

Dev and stage environments

An environment is a set of variables. One environment is active at a time, and when you switch, all {{…}} in requests and scripts take their values from it. Create environments with the same variable names and different values:

Variabledevstage
baseUrlhttp://localhost:8080https://stage.api.example.com
tokenUrlhttp://localhost:8081/tokenhttps://auth.stage.example.com/token
clientIdorders-tests-devorders-tests
clientSecretlocal value onlylocal value only; in CI — the CI secret

In a request, a variable is written in double curly braces — {{baseUrl}}/orders; in a script it is read with pm.environment.get("baseUrl").

Secrets

Do not share a secret’s value: the shared value is synchronised to Postman Cloud and visible to the team. Mark passwords, keys and tokens that get substituted into requests as {{…}} with the “Secure” button next to the environment variable name. To keep secrets separate from collections and environments, Postman has Postman Vault: local or shared with the team. Scripts read secrets from it with pm.vault methods, not pm.variables.

Data files: one test, many data sets

A CSV or JSON data file defines iterations: the collection runs once per row, and the columns become variables — {{sku}}, {{quantity}}. This way a single test covers the equivalence classes and boundary values from test design. Attach the file in Collection Runner (custom data files there are available on paid plans) and in Postman CLI.

csvorders.csv
sku,quantity,expectedStatusBOOK-42,1,201BOOK-42,100,201BOOK-42,0,422BOOK-42,101,422NO-SUCH-SKU,1,422

Here the quantity is valid from 1 to 100: the rows cover both boundaries and the values just past them. The request body references the columns — {"sku": "{{sku}}", "quantity": {{quantity}}} — and the test asserts on the expected code:

javascriptThe request’s post-response script
const quantity = pm.iterationData.get("quantity");const expected = Number(pm.iterationData.get("expectedStatus")); pm.test(`quantity ${quantity} gives ${expected}`, () => {  pm.response.to.have.status(expected);});

Unique values: dynamic variables

Dynamic variables generate a value on every request: {{$guid}} is a UUID v4-style GUID, {{$randomEmail}} a random email, {{$timestamp}} the current Unix time in seconds. Substitute them into fields that must be unique, so that a re-run does not fail on data left over from the previous run. In a script, get the value like this: pm.variables.replaceIn("{{$randomEmail}}").

The test creates and removes its own data

A scenario starts with a request that creates the data it needs (POST) and ends with a request that removes it (DELETE); the id of the created object is passed between them in a collection variable. The test then does not depend on what others left behind in the environment, and can be run on its own.

Section sources

the section is written from these pages

Negative tests and errors

A negative test sends a request that the API must reject and checks that the rejection is correct: the right 4xx status code, a readable error body and unchanged data. Invalid values and boundary cases are selected using the techniques from the “Test design” reference.

By RFC 9110, for a client error (4xx) the server should return an explanation: what is wrong and whether the error is temporary. The test checks the exact status code from the specification, not “any 4xx”: 400 and 422 mean different things.

What to send and what to expect

What is sentCodeWhat to check
Malformed JSON in the body400the error body; nothing has been created
The required field sku is missing400 or 422 — whichever the specification saysthe error names the field
Wrong type: "quantity": "two"400 or 422the error names the field
Boundary: "quantity": 0422no order is created
Content-Type: text/plain instead of JSON415an Accept header with the list of supported types may be returned
DELETE /orders without an id405an Allow header listing the methods
An order that does not exist404an error body matching the schema
Paying for a cancelled order409the body states what prevents the request from being carried out
Too many requests within a minute429Retry-After, if the API provides it
A field the client is not allowed to set: "status": "paid"per the specification: a refusal, or the field is ignoredno order is created, or one is created with the status new

400 Bad Request means the request is malformed: the syntax or the boundaries of the message are broken. 422 Unprocessable Content — the content type is understood and the syntax is valid, but the content cannot be processed, for example a quantity outside the allowed range. Which code applies in which case is decided by the API specification, and the test checks exactly that one. For 405, the Allow header is mandatory.

Error format: problem details

RFC 9457 defines a common error format for HTTP APIs — problem details, served with the content type application/problem+json. It is a JSON object with the fields:

  • type — URI of the problem type, its main identifier; if the field is absent, the type is about:blank
  • title — a short description of the type; it does not change from one occurrence to another, apart from being translated
  • status — the status code; it must match the code of the response itself
  • detail — an explanation of this particular occurrence
  • instance — the URI of the specific occurrence

The API adds its own extension fields, for example an errors list with pointers to the offending fields. A client must skip unfamiliar extensions, so the test checks the fields it needs rather than the whole object.

httpa sample response
HTTP/1.1 422 Unprocessable ContentContent-Type: application/problem+json {  "type": "https://api.example.com/problems/validation-error",  "title": "Request body is not valid",  "status": 422,  "errors": [    {"pointer": "#/quantity", "detail": "must be at least 1"}  ]}
javascriptthe request’s post-response script
pm.test("422 with problem details", () => {  pm.response.to.have.status(422);  pm.expect(pm.response.headers.get("Content-Type"))    .to.include("application/problem+json");  const problem = pm.response.json();  pm.expect(problem.status).to.eql(pm.response.code);  pm.expect(problem.type).to.be.a("string");  const pointers = problem.errors.map((e) => e.pointer);  pm.expect(pointers).to.include("#/quantity");});

Security negative tests

OWASP API Security Top 10 2023 describes risks that are uncovered by negative requests. Access to other users’ objects (API1) is covered in the “Authorisation in tests” section; here are two risks that are checked by substituting bodies and parameters:

  • Object properties (API3:2023, Broken Object Property Level Authorization). Send fields the client is not allowed to change in a POST or PATCH request: status, total, role. The API must not accept them. Check separately that the response does not expose properties the user is not meant to see.
  • Resource consumption (API4:2023, Unrestricted Resource Consumption). Ask for more than is allowed: ?limit=100000, a file larger than the limit, a batch of thousands of operations. The API must refuse or cap the response at the limit set out in the specification.
httpa request with extra fields
POST {{baseUrl}}/ordersContent-Type: application/json {"sku": "BOOK-42", "quantity": 1, "status": "paid", "total": 0}
javascriptthe request’s post-response script
// per the specification, extra fields are ignoredpm.test("client cannot set status and total", () => {  pm.response.to.have.status(201);  const order = pm.response.json();  pm.expect(order.status).to.eql("new");  pm.expect(order.total).to.be.above(0);});

Rate limiting: 429

The 429 Too Many Requests status code (RFC 6585) means the user has sent too many requests in a given time window. The response should explain the limit and may contain Retry-After — how long to wait before retrying; such a response must not be cached. The server is not obliged to answer 429: under attack it may simply drop connections without a response. So take the expected behaviour from the specification, and do not run the limit test together with the rest of the suite: it interferes with neighbouring checks.

Section sources

the section is written from these pages

Contract testing

Contract testing checks the agreement on requests and responses between an API consumer and a provider without running the two together. It answers the question of whether a new version of a service will break whatever calls it, earlier and more cheaply than end-to-end tests.

A consumer is an application that sends an HTTP request, such as a web interface. A provider is a service that returns the response. In Pact the contract is called a pact and consists of interactions: an expected request and a minimal expected response — only the parts the consumer actually uses.

How Pact works

Pact is a consumer-driven contracts tool. The consumer’s tests produce a pact file, the provider verifies it against itself, and Pact Broker stores the contracts and verification results and tells you whether a version can be deployed.

The consumer and the provider don’t need to be up at the same time: the broker is the only link between them.
  1. The consumer tests its client code against a provider mock that Pact spins up: the mock matches the request against the expectation and returns the expected response. If the test passes, Pact records the interactions into a pact file (JSON).
  2. The consumer’s build publishes the pact file to Pact Broker.
  3. The provider’s build fetches the pact from the broker and replays each request against the running provider: the response must contain at least the described data.
  4. The verification result is published to the broker along with the provider version — this is how the matrix of compatible versions is built.
  5. Before deployment either side asks can-i-deploy: is this version compatible with everything already running in the environment.

Consumer test

The test drives the consumer’s own client code rather than sending requests by hand: the client talks to the mock at mockserver.url. The required provider state is described with given, for example “order 42 exists” — the provider will set it up before verification.

javascripttest/orders.pact.test.js
import { test } from "node:test";import assert from "node:assert/strict";import path from "node:path";import {  Pact,  Matchers,  SpecificationVersion,} from "@pact-foundation/pact";import { getOrder } from "../src/orders-client.js"; const { like, string } = Matchers; const provider = new Pact({  consumer: "shop-web",  provider: "orders-api",  dir: path.resolve("pacts"),  spec: SpecificationVersion.SPECIFICATION_VERSION_V4,}); test("reads an order", async () => {  await provider    .addInteraction()    .given("order 42 exists")    .uponReceiving("a request for order 42")    .withRequest("GET", "/orders/42", (builder) => {      builder.headers({ Accept: "application/json" });    })    .willRespondWith(200, (builder) => {      builder.headers({ "Content-Type": "application/json" });      builder.jsonBody({ id: string("42"), status: like("new") });    })    .executeTest(async (mockserver) => {      const order = await getOrder(mockserver.url, "42");      assert.equal(order.status, "new");    });});

The like and string matchers specify a type rather than an exact value: the provider may return a different status as long as it is a string. If the test passes, Pact appends the interaction to the pact file in the pacts directory. Clear this directory before each run, otherwise stale interactions will remain in the contract.

Each interaction stands on its own. Instead of “create an order, then read it back” you write two interactions, and the second one carries the “order exists” provider state.

bashConsumer CI
pact-broker publish ./pacts \  --consumer-app-version="$GIT_SHA" \  --auto-detect-version-properties \  --broker-base-url=https://pact-broker.example.com

The pact-broker command ships in the @pact-foundation/pact-cli package. It takes the broker credentials from the PACT_BROKER_USERNAME and PACT_BROKER_PASSWORD or PACT_BROKER_TOKEN environment variables.

Verification by the provider

Pact runs the provider verification end to end: it sends each request from the pact file to the running provider and compares the response against the minimal expectation. The verification passes if the response contains at least the described data; extra fields don’t get in its way. Before each interaction Pact sets up the provider state from given, and it publishes the result along with the provider version to the broker.

Can I deploy: can-i-deploy

The broker keeps a matrix: which versions of the consumer and the provider have been verified against each other, and with what outcome. Before a deployment, ask whether the version is compatible with everything already in the environment; exit code 0 means yes, 1 means no, and the pipeline will stop.

bashbefore deployment
pact-broker can-i-deploy \  --pacticipant orders-api \  --version "$GIT_SHA" \  --to-environment production
bashafter deployment
pact-broker record-deployment \  --pacticipant orders-api \  --version "$GIT_SHA" \  --environment production

Record deployments to test environments too, not just production: that way the broker knows which versions run where.

Contract from an OpenAPI specification

The second approach is a contract based on a schema: the OpenAPI specification serves as the agreement. The provider verifies its responses against the schemas in it, while consumers build clients and collections from it; Postman generates a collection from the specification and can update it as the specification changes. This approach also works where consumers cannot be named individually, such as a public API. But it only catches divergence from the specification, not what a specific client actually relies on.

ApproachWho writes itWhat it catches
Pact, a consumer contractthe consumer’s team; the provider verifies itthe provider changed something a specific consumer uses
A contract based on OpenAPIthe provider’s teamresponses have drifted from the specification
End-to-end teststest engineersfailures in how the whole system interacts, but slowly and late

When Pact doesn’t fit

  • The other side of the integration doesn’t write Pact tests
  • Consumers can’t be enumerated: a public API
  • The provider’s data can’t be set up without calling the same API under verification
  • Functional testing of the provider is needed: that is the job of its own test suite
  • Performance and load testing is needed
  • The API merely forwards the request without checking it

Contract tests check the format and content of requests and responses, not behaviour. Pact doesn’t verify the side effects of a request, so functional tests of the provider remain necessary.

Section sources

the section is written from these pages

Postman

Postman is an application for sending HTTP requests and checking them. Requests are saved into a collection, checks are written as JavaScript scripts, and the whole collection is run by the Collection Runner in the app or by Postman CLI in CI.

Collections, folders and requests

A collection is a group of saved requests arranged into folders; example responses, documentation and tests are stored in it as well. The layout for API testing: one collection per service, one folder per scenario, and each request carries its own checks.

textcollection
Orders API├── orders│   ├── Create order   POST   {{baseUrl}}/orders│   ├── Get order      GET    {{baseUrl}}/orders/{{orderId}}│   └── Delete order   DELETE {{baseUrl}}/orders/{{orderId}}└── negative    ├── Missing sku    POST   {{baseUrl}}/orders    └── No token       GET    {{baseUrl}}/orders/{{orderId}}

Scripts and their execution order

A pre-request script runs before the request is sent: data is prepared and a token is obtained in it. A post-response script runs after the response: it holds the checks. Collections, folders and requests each have scripts, and for every request Postman runs them down the hierarchy: first the collection’s, then the folder’s, then the request’s own. A folder script applies only to the folder’s direct child requests.

The order is the same for every request in the collection.
  1. The collection’s pre-request
  2. The folder’s pre-request
  3. The request’s pre-request
  4. Sending the request and receiving the response
  5. The collection’s post-response
  6. The folder’s post-response
  7. The request’s post-response

Hence the rule: shared logic goes at the top level. Obtaining a token goes in the collection’s pre-request, shared checks, such as a response time threshold, in its post-response, and the checks for a specific operation in the request. Scripts run in the Postman Sandbox, a JavaScript environment built on Node.js.

javascriptthe collection’s post-response
// runs after every request in the collectionpm.test("response time under 1 s", () => {  pm.expect(pm.response.responseTime).to.be.below(1000);});

Running a collection: the Collection Runner

The Collection Runner sends all or selected requests of a collection or folder in a set order and shows the result of every check. The order is changed by dragging, or from a script with pm.execution.setNextRequest().

SettingWhat it does
“Iterations”how many times to go through the collection
“Iteration data”a data file or a dataset: one row per iteration
“Stop run if an error occurs”stop the run on an exception in a script or a failed send; on by default
“Keep variable values”keep changed variables after the run; the local value is changed, not the shared value
“Add a delay of”a pause before each request, in ms
“Persist responses for a session”keep response headers and bodies for inspection; bodies up to 300 KB

In the results, errors and failed checks are different things. An error is a failure to execute, such as a timeout or a TLS failure; a failed check means the API responded differently from what was expected.

Mocks

A mock replaces an API that does not exist yet, or an external dependency. Postman has mocks with JavaScript handlers, which are run locally or deployed. There are also mock servers in Postman Cloud: they are created from a collection and respond with saved example responses.

Import: OpenAPI and curl

Files, folders, cURL commands, text, URLs and repositories can be imported. An OpenAPI specification is imported as a collection, or as a specification together with the collection. A curl command only needs to be pasted into the request URL bar — Postman parses it itself; the other way round, any request turns into a cURL command in the code panel. Postman no longer imports collections in the v1 format.

Section sources

the section is written from these pages

Automation: Postman CLI and CI

Postman CLI (postman) is the official Postman command-line tool. The postman collection run command runs a collection locally or in CI and exits with a non-zero code if any checks fail. CI uses this code to stop the build.

Installation and running

bashon your machine or in CI
npm install -g postman-cli

The CLI also comes with the Postman app.

bashrunning from a file
postman collection run tests/orders.postman_collection.json \  -e tests/stage.postman_environment.json \  --env-var "clientSecret=$ORDERS_CLIENT_SECRET"

From a file, the CLI runs the collection locally and prints the results to the terminal. For the results to reach Postman as well, you need to sign in — with the postman login --with-api-key "$POSTMAN_API_KEY" command, the --postman-api-key option or the POSTMAN_API_KEY variable — and run the collection by its ID. Pass the secret through --env-var from the CI secrets: then it never appears in the environment files.

OptionWhat it does
-e, --environmentenvironment: file path or UID
--env-var "key=value"environment variable; can be repeated
-d, --iteration-dataJSON or CSV data file, one iteration per row
-n, --iteration-countnumber of iterations
-ionly this folder or request; can be repeated
--bailstop the run at the first error
--delay-requestpause between requests, ms; 0 by default
--timeout-requesthow long to wait for a response, in ms
-r, --reportersreports: cli, json, junit, html
-x, --suppress-exit-codeexit code 0 even if checks fail
-k, --insecuredo not verify TLS certificates

Reports

You choose the report with the -r option: cli (to the terminal, the default), json, junit, html; several — as a comma-separated list. If you specify only -r junit, the terminal output disappears, so write -r cli,junit. By default, report files appear in the postman-cli-reports directory; the --reporter-junit-export option sets the JUnit report path.

bashJUnit report
postman collection run tests/orders.postman_collection.json \  -e tests/stage.postman_environment.json \  -r cli,junit \  --reporter-junit-export reports/api-tests.xml

A step in CI

The build runs the collection on every code change. If a single check fails, postman collection run returns a non-zero code and CI marks the build as failed; the JUnit report is saved in either case.

The exit code of the run decides, and the report shows which checks failed.

The GitHub Actions job installs the CLI, runs the collection on stage and saves the report as an artefact, even if checks fail. For pipeline syntax and CI secrets, see the “CI/CD” reference.

yaml.github/workflows/api-tests.yml
name: api-testson: [push] jobs:  postman:    runs-on: ubuntu-latest    steps:      - uses: actions/checkout@v7      - run: npm install -g postman-cli      - name: Run API tests on stage        env:          CLIENT_SECRET: ${{ secrets.ORDERS_CLIENT_SECRET }}        run: |          postman collection run tests/orders.postman_collection.json \            -e tests/stage.postman_environment.json \            --env-var "clientSecret=$CLIENT_SECRET" \            -r cli,junit \            --reporter-junit-export reports/api-tests.xml      - uses: actions/upload-artifact@v7        if: always()        with:          name: api-tests-report          path: reports/api-tests.xml

Tests written with pytest and httpx run in the same pipeline as a separate step. You can also check the specification there: postman spec lint openapi.yaml verifies it against the team’s rules.

Migrating from Newman

Newman is a command-line runner for Postman collections. It only understands the v2.1 format (JSON) and cannot run v3 collections (YAML), which Postman v12 uses in Local View mode and for Native Git. Postman recommends the Postman CLI: the options are almost the same, and the postman collection migrate command converts old collections to v3.

TaskNewmanPostman CLI
Runnewman run c.jsonpostman collection run c.json
With an environmentnewman run c.json -e env.jsonpostman collection run c.json -e env.json
One foldernewman run c.json --folder orderspostman collection run c.json -i orders
With datanewman run c.json -d data.csv -n 5postman collection run c.json -d data.csv -n 5
JUnit reportnewman run c.json -r junit --reporter-junit-export r.xmlpostman collection run c.json -r junit --reporter-junit-export r.xml
HTML reportexternal package newman-reporter-html, then -r htmlpostman collection run c.json -r html
Exit code 0 with failed checksnewman run c.json -xpostman collection run c.json -x

Section sources

the section is written from these pages

Common mistakes in approach

Useless API tests usually go wrong in the same ways: they check too little, depend on one another or on the data of the test environment, and fail when the API is not what is broken. Nine common mistakes — and how to fix them.

Only the 200 status code is checked

The test is green even though the API returned 200 with an error in the body, an empty list or someone else’s order: the code only says that the request was processed. Check the exact status code, Content-Type, the key fields and the response schema.

javascriptwhat not to do
pm.test("ok", () => {  pm.response.to.have.status(200);});
javascriptthe right way
const order = pm.response.json(); pm.test("order is paid", () => {  pm.response.to.have.status(200);  pm.expect(order.id).to.eql(pm.collectionVariables.get("orderId"));  pm.expect(order.status).to.eql("paid");});

pm.test has no name

If you omit the first argument — the check’s name — pm.test will not run the assertion, and the test passes even when it should fail. The name is required and must say what is being checked: it is how the check is located in the report.

javascriptwhat not to do
// passes every time: pm.test has no namepm.test(() => {  pm.expect(true).to.eql(false);});

The response is parsed inside a single check

A const declared inside one pm.test is not visible in the next one: the second check fails with ReferenceError: order is not defined, even though the API responded correctly. Parse the response once, at the start of the script. And remember that eql compares the type as well: pm.expect(1).to.eql("1") fails with AssertionError: expected 1 to deeply equal '1'.

javascriptthe right way
const order = pm.response.json(); pm.test("status is new", () => {  pm.expect(order.status).to.eql("new");}); pm.test("quantity is 2", () => {  pm.expect(order.quantity).to.eql(2);});

Tests depend on order and shared data

The “Get order” request takes the orderId that “Create order” from another folder or a previous run left behind. On its own, such a request will not run, and one failed check drags a chain of false failures behind it. Make each folder a complete scenario: it creates its own data, passes the id on through a collection variable and removes the data at the end.

Tokens and addresses are written straight into requests

A request like this cannot be switched to another environment, and the token goes to everyone the collection has been shared with. Move addresses and credentials into environment variables, and mark secrets with “Secure”.

httpwhat not to do
GET https://stage.api.example.com/orders/42Authorization: Bearer change-me
httpthe right way
GET {{baseUrl}}/orders/{{orderId}}Authorization: Bearer {{accessToken}}

No negative tests and no authorisation tests

A suite of happy-path scenarios alone will not notice that the API accepts invalid data or hands out objects that belong to other users — which is exactly what attackers look for. For every operation, add at least:

  • a request without a token — 401 is expected
  • a request for another user’s object — 403 or 404
  • a body missing a required field, or with the wrong type — 400 or 422, as the specification says
  • values at the boundaries of what is allowed and just beyond them

The response is compared as a whole

Comparing the entire body as a string (pm.response.to.have.body(...)) fails at the slightest change: a new field, a different order, a fresh timestamp. The test turns red on every release, and a real regression is impossible to see in all that noise. Check the schema and the key fields, and compare part of an object with deep.include.

javascriptthe right way
pm.test("order contains the expected fields", () => {  pm.expect(pm.response.json()).to.deep.include({    sku: "BOOK-42",    quantity: 2,    status: "new",  });});

Side effects and repeats are not checked

DELETE responded 204, yet the order can still be read; repeated, PUT changes more than it did the first time. By RFC 9110, PUT, DELETE and safe methods are idempotent: a repeat produces the same result on the server, although the response itself may differ. Check the result with a separate read, and repeat mutating requests.

javascriptthe request’s post-response script
// GET {{baseUrl}}/orders/{{orderId}} after the DELETEpm.test("deleted order is gone", () => {  pm.response.to.have.status(404);});

An asynchronous operation is checked straight away

The 202 Accepted status code means the request has been accepted, but processing is not finished. A test that reads the result straight away passes one moment and fails the next. Poll the status address until the operation completes, with a limit on the number of attempts. In a collection run, the request is repeated with pm.execution.setNextRequest(), and the pause between attempts is set by the run’s delay.

javascriptthe request’s post-response script
// post-response of the “Get export status” requestconst { state } = pm.response.json();const tries = Number(pm.collectionVariables.get("tries") || 0) + 1; if (state === "running" && tries < 10) {  pm.collectionVariables.set("tries", tries);  pm.execution.setNextRequest("Get export status");} else {  pm.collectionVariables.unset("tries");  pm.test("export finished", () => {    pm.expect(state).to.eql("done");  });}

setNextRequest only takes effect in a collection run; when a single request is sent with the “Send” button, it does nothing.

Section sources

the section is written from these pages

Standards and their status

Four documents define what API tests expect. OpenAPI 3.2.1 describes operations and schemas, JSON Schema 2020-12 sets the rules for validating JSON, RFC 9110 defines HTTP semantics and RFC 9457 defines the error format.

DocumentWhat it definesStatusReplaced or extended by
OpenAPI 3.2.1, 10 September 2026a description of an HTTP API: operations, parameters, schemas, securitylatest versiona patch release over 3.2.0; the latest versions of the earlier branches are 3.1.2 and 3.0.4
JSON Schema 2020-12JSON validation keywords: Core and Validationcurrent versionreplaced 2019-09
RFC 9110 HTTP Semantics, June 2022methods, status codes, headersInternet Standard, STD 97replaced RFC 7231, 7232, 7233, 7235 and others
RFC 9457 Problem Details for HTTP APIs, July 2023the error format application/problem+jsonProposed Standardreplaced RFC 7807

Authorisation in tests is checked against RFC 6750 on Bearer token usage, and security against the OWASP API Security Top 10 2023. The details are covered in the sections “Authorisation in tests” and “Negative tests and errors”.

What changed in OpenAPI 3.2

OpenAPI versions are numbered major.minor.patch: a minor version defines the feature set, while a patch only fixes and clarifies the text. A tool that supports 3.2 should understand any 3.2.x. Compared with 3.1, version 3.2 added:

  • Methods: the query field describes the QUERY operation, and additionalOperations covers operations with other HTTP methods
  • Parameters: the in: querystring location — the entire query string as a single value
  • Streaming responses: itemSchema describes each item of a sequence, such as SSE events
  • Examples: the dataValue and serializedValue fields in the Example object
  • Security: the OAuth Device Authorization flow (deviceAuthorization), a link to authorisation server metadata oauth2MetadataUrl and a deprecated flag on a security scheme
  • Tags: nesting through parent and the tag’s kind
  • Document: the $self field sets the document’s own URI

Outdated documents that are still cited

  • Swagger 2.0 — the predecessor of OpenAPI 3: in 2015 it was handed over to the OpenAPI Initiative, and on the specification website it is listed as version 2.0.
  • RFC 7807 — the first edition of problem details, replaced by RFC 9457. The new edition added a registry of problem types and rules for several errors in one response.
  • RFC 7231 — the former HTTP/1.1 semantics, replaced by RFC 9110: when referring to methods and status codes, cite the sections of RFC 9110.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 2 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

9 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “API testing” topic
12 sections
Another reference · Testing (QA)

Test design

Verified 1 Nov
All references · 61