Notes
All notes

API Testing (API Design #12)

Friday, 16:40. You merge a “safe” change: the orders service now returns total_cents instead of total. Your tests pass. Monday, 09:15: three partner integrations are broken, because their code reads total — and nothing in your test suite knew that. Your tests verified what you meant to ship; nobody verified what your consumers depend on.

That gap — between a service’s intentions and its consumers’ expectations — is why API testing is its own discipline, not just “unit tests, but with HTTP.” This chapter covers the testing pyramid for APIs: unit, integration, functional/end-to-end, contract testing, mocking as the connective tissue, and load testing as the gate before production.

By the end you will be able to place any test on the pyramid, write a contract test that would have caught the total rename, and explain why ten well-placed tests beat a hundred misplaced ones.

The pyramid, API edition

Tests get slower, flakier, and more realistic as you climb — so you want many at the bottom and few at the top:

\begin{tikzpicture}[font=\rmfamily]
  \fill[blue!15]   (-3,0) -- (3,0) -- (2,1) -- (-2,1) -- cycle;
  \fill[green!15]  (-2,1) -- (2,1) -- (1.2,2) -- (-1.2,2) -- cycle;
  \fill[orange!20] (-1.2,2) -- (1.2,2) -- (0.5,3) -- (-0.5,3) -- cycle;
  \fill[red!15]    (-0.5,3) -- (0.5,3) -- (0,3.9) -- cycle;
  \node[font=\rmfamily\small] at (0,0.5) {unit — pure functions, ms};
  \node[font=\rmfamily\small] at (0,1.5) {integration — API + real DB};
  \node[font=\rmfamily\small, align=center] at (0,2.5) {contract /\\functional};
  \node[font=\rmfamily\small, align=center] at (0,3.35) {E2E +\\load};
  \node[font=\rmfamily\scriptsize, anchor=west] at (3.3,0.5) {fast, many, catch logic bugs};
  \node[font=\rmfamily\scriptsize, anchor=west] at (2.3,1.5) {slower, catch wiring bugs};
  \node[font=\rmfamily\scriptsize, anchor=west] at (1.4,2.5) {slowest, catch assumption bugs};
\end{tikzpicture}

Each layer catches a different bug class. The anti-pattern — the “ice-cream cone” — inverts it: a hundred Selenium-style end-to-end tests, each 45 seconds, each broken by a CSS change, while the pricing function ships untested.

Unit tests: the logic, isolated

The bottom layer tests pure behavior with no network and no database: input validation, the token bucket from Chapter 10, the cursor codec from Chapter 3, the authorization function from Chapter 6:

def test_token_bucket_denies_after_burst():
    b = TokenBucket(rate=10, burst=5)
    assert all(b.allow() for _ in range(5))   # burst drains the bucket
    assert not b.allow()                      # sixth request: 429

def test_cursor_roundtrip():
    c = encode_cursor("inv_000250")
    assert decode_cursor(c) == {"last": "inv_000250"}

These run in milliseconds, fail deterministically, and point at a line. If a unit test is slow or flaky, it’s secretly an integration test — it touched something outside the process.

Integration tests: the API, really running

One level up: boot the real application against a real (disposable) database and call it over HTTP. FastAPI’s TestClient or a pytest fixture against Postgres-in-Docker:

from fastapi.testclient import TestClient

def test_create_then_get_invoice(client: TestClient, auth_headers):
    r = client.post("/invoices", json={"total": 1999}, headers=auth_headers)
    assert r.status_code == 201
    assert "Location" in r.headers                    # contract, not just body

    inv = r.json()
    r2 = client.get(f"/invoices/{inv['id']}", headers=auth_headers)
    assert r2.json()["total"] == 1999

def test_other_tenants_invoice_is_404(client, auth_headers, other_invoice):
    r = client.get(f"/invoices/{other_invoice.id}", headers=auth_headers)
    assert r.status_code == 404                       # BOLA regression (Ch. 9)

This layer catches what unit tests structurally cannot: serialization shapes, status codes, middleware order, the authz check that exists but runs after the database write. Notice the second test — security regressions are integration tests, because the bug lives between authentication and the handler.

The unglamorous hero of this layer is test data. Hand-inserted rows rot as schemas evolve; a factory (make_invoice(status="sent", total=1999)) builds valid fixtures with named overrides, so tests state only what they exercise. Factories plus a database reset between tests (transactions rolled back, or a truncated schema per run) buy you isolation: tests that pass in any order, in parallel, on a clean checkout.

Functional and end-to-end tests: the user’s story

Functional tests verify a whole business flow through the public API only: register → create invoice → send → mark paid → ledger balances. End-to-end adds the real client (browser, mobile build) on top. These are the few, precious tests that answer “does the product work” — keep them to the critical paths (signup, checkout, the flow that pays your salary), because each one costs minutes and flakes at the worst times. A good heuristic: if a failing E2E test wouldn’t page anyone, it shouldn’t be an E2E test.

Contract testing: the layer that catches renames

Back to the opening story. Contract testing flips the direction of verification: consumers publish their expectations (“I call GET /orders/42 and read total, an integer”), and the provider proves it still satisfies every expectation. Pact is the standard tool; the flow is:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.7cm, minimum height=0.72cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (c) at (0,0) {consumer tests};
  \node[b, fill=orange!20] (b) at (4.4,0) {pact broker\\(shared contracts)};
  \node[b, fill=green!10] (p) at (8.8,0) {provider verification};
  \draw[a] (c) -- node[above, font=\rmfamily\scriptsize] {publish expectations} (b);
  \draw[a] (b) -- node[above, font=\rmfamily\scriptsize] {replay against real API} (p);
  \draw[a, dashed] (p.south) to[bend left=25] node[below, font=\rmfamily\scriptsize] {fail the build on mismatch} (c.south);
\end{tikzpicture}

Renaming total to total_cents now fails the provider’s build before merge, with a message naming the three consumers that break. The same idea applies to your OpenAPI spec (Chapters 3, 8): diffing the spec in CI catches breaking changes even for consumers without pact tests. Two safety nets, one principle: consumers define the contract; the provider proves it.

There’s an economic formula behind the shape. If a test at layer \(\ell\) costs \(c_\ell\) to write and run and catches bug class \(B_\ell\), suite time and coverage trade off as

\[ T_{\text{CI}} = \sum_\ell n_\ell \, t_\ell, \qquad \text{coverage} = \bigcup_\ell B_\ell \]

Unit tests cost milliseconds, so \(n\) can be huge; E2E tests cost minutes, so \(n\) must stay tiny. A suite that violates this — thousands of slow tests — gets deleted by the team it annoys, which is how ice-cream-cone suites end: not wrong, just unsustainable.

Property-based and fuzz testing: let the spec generate cases

Hand-written examples test what you thought of. Property-based testing generates hundreds of inputs and checks invariants — “any accepted cursor decodes back”, “any valid invoice serializes to the schema”. For APIs there’s a sharper tool: Schemathesis reads your OpenAPI spec and fuzzes every endpoint with generated data, checking that the server never 500s and always responds in-schema:

schemathesis run openapi.yaml --base-url http://localhost:8000 \
  --checks all --hypothesis-max-examples 200

This is the spec paying off yet again (Chapters 3, 8): the same document that generated docs and mocks now generates attacks. Teams routinely find their first 500-on-weird-input bug within minutes of running it.

Mocking: speed with a price

Mocks and stubs let a consumer test against a fake provider — instant, deterministic, offline. The price is fidelity: a mock answers what you programmed it to answer, including your own misunderstandings. The discipline that keeps mocks honest:

Record/replay tools (VCR-style cassettes) split the difference: real responses captured once, replayed deterministically thereafter.

A note on coverage metrics: line coverage over API code measures “did a request pass through”, which is weakly correlated with correctness. More useful is contract coverage — which documented paths, statuses, and schema branches were exercised. An endpoint hit 50 times with the same happy path contributes less than one request per documented error shape.

Load testing: the gate before production

Chapter 10’s k6 script belongs in this pyramid too — as the final gate, run against staging before launch and after risky changes. The assertions that matter are the SLOs: p(95) < 500 ms, error rate under 1%, and behavior at 2× expected peak. Load tests answer the question no functional test can: not “is it correct?” but “is it correct while busy?” — the race condition that needs 200 concurrent requests, the connection pool that exhausts at 50, the cache stampede at expiry.

Pitfalls

QQuestionSelf-check

Place these on the pyramid: a cursor codec test; a “tenant A can’t read tenant B’s invoice” test; a full checkout flow through the browser. Which layer would have caught the total → total_cents rename, and why didn’t the provider’s own integration tests catch it? When is a hand-written mock acceptable?

ASolution

The codec is unit (pure function, no I/O); the cross-tenant check is integration (real app + real DB + auth middleware, exercising the object-level rule); the browser checkout is E2E (reserve for critical paths only). Contract testing catches the rename: consumers publish that they read total, and provider verification fails on the rename before merge. The provider’s own tests passed because they test what the provider intends to return — nothing encoded what consumers depend on. A hand-written mock is acceptable at a stable, simple boundary with low drift risk (a legacy third party with no spec); even then, keep one thin test against the real service, and prefer contract-generated mocks whenever a spec or pact exists.

Next: Observability (API Design #13) — logs, metrics, traces, and the SLO math that tells you when to wake someone up.