API and contract tests
Test the service through its front door, then test the one thing a mock cannot: that both sides of a wire still agree about what crosses it
Ojaline's checkout service calls a payment provider. The provider changes the type of amount_kobo in its response from an integer to a string, and adds a new field fee_kobo. The checkout client reads only id and status from the response. Which of these checks goes red? (A) the provider's own contract test, written from everything it promises; (B) a test that checks only the fields the checkout client reads; (C) a unit test of place_order with a mocked client.
Testing through the front door
A unit test calls a function. An API test calls the service the way a client does: it sends an HTTP request and checks the HTTP response. In Python with FastAPI the request does not need a network. TestClient from fastapi.testclient runs your ASGI app in the same process and gives you an httpx-style client for it. The request still passes through routing, request validation, the endpoint, the exception handlers and JSON serialisation. Only the socket is missing.
That is the layer you cannot see from a unit test. place_order returns a dict. It does not know that the route is POST /orders, that the Idempotency-Key header is required, that qty: 0 is rejected before your code runs, or that OutOfStock becomes a 409 with a body {"error": "out_of_stock", "detail": "..."}. Those facts are the service’s interface, and a client written by another team depends on every one of them.
In the lab, checkout/api.py has a create_app(db, payments, clock, index) function that takes its dependencies as arguments. That is the seam from Fakes, stubs and mocks, used a second time. The test builds an app with a temporary database and the stub payment client from tests/conftest.py, so the API test exercises everything except the provider.
What to assert
An API test has four things to check, in this order of importance.
| Check | Example from POST /orders |
Why it matters |
|---|---|---|
| Status code | 201 for a new order, 200 for a replay of the same key, 402, 404, 409, 422, 502 for each failure | Clients branch on it. A 200 where there should be a 201 changes retry behaviour. |
| Shape of the body | id, status, total_kobo, charge_id, created_at, lines are present and typed |
Clients parse it. A missing field is an exception in someone else’s code. |
| The few values that carry the rule | total_kobo == 902_500 for the fixed cart |
One number proves pricing is wired through. |
| Side effects through the interface | the same key replays the first order and charges once | The retry promise is the point of the header. |
Do not compare the whole body for equality when it contains an id and a timestamp that change every run. Assert on the fields that carry meaning, and check the others by type or pattern (ord_ followed by 12 hex characters). A test that compares a 40-line JSON blob fails for reasons nobody can read, which is the opposite of the advice on a clear failure in What a good test looks like.
Status codes deserve a test each because they are the part of an API that people forget is a promise. The checkout API’s table is short.
| Outcome | Status | error code |
|---|---|---|
| Order created | 201 | none |
| Same key again | 200 | none |
| Unknown product | 404 | unknown_product |
| Not enough stock | 409 | out_of_stock |
| Card declined | 402 | payment_declined |
| Provider down or timing out | 502 | payment_unavailable |
Bad request (missing key, qty below 1) |
422 | FastAPI’s own validation body |
One line of the table is not like the others. The 422 body comes from the framework, not from Ojaline, and its shape is FastAPI’s. If a client parses it, an upgrade can change it. Decide whether you promise it. If you do not, test the status and leave the body alone.
The part of the wire a mock cannot see
An API test of the checkout service still replaces the payment provider with a stub, because the provider is somebody else’s service and the test should be fast. That is the right trade. It leaves one question open that Fakes, stubs and mocks ended on: the stub says the provider answers {id, status}, and nothing checks that the provider does.
// The consumer's test owns the mock. Nothing ties it to the provider.
const mockBilling = { id: 'inv_101', amount: 48200, status: 'paid' };
test('shows the amount', () => {
const page = render(mockBilling);
expect(page.total).toBe('₦482.00'); // green forever
});// The consumer writes down what it relies on. The provider's pipeline
// verifies its real response against it before every deploy.
const contract = { id: 'string', amount: 'number', status: { enum: ['paid', 'pending'] } };
// consumer tests use a mock generated from the contract
// provider CI: verifyContract(contract, await realResponse('/invoices/inv_101')) Run the sim’s additive scenario first. A field is added and production keeps working, which is the usual kind of provider change and one that nobody should have to coordinate. Then run the rename and the type change with a new status value. The unit tests are green in both, and production fails in both. What the sim does not show is who writes down the list that the check compares against. That choice is the rest of this chapter.
Two contracts, written by two people
A contract is a written description of the messages two systems exchange: the request fields, the response fields, their types, and the allowed values. A contract test takes a real message and checks it against that description. It tests shape, and only shape.
There are two ways to write the description, and they answer different questions.
A provider contract is written by the provider and lists everything it promises. The lab’s fake_provider/contract.json is one: a JSON Schema for each endpoint and status, with the charge shape defined once and reused. It answers the provider’s question: do my answers still match what I published? It cannot tell the provider which fields anyone reads, so every field looks equally important, and a change to any of them looks equally risky.
A consumer-driven contract, the pattern Ian Robinson described in the article in the reading list, is written by each consumer and lists only what that consumer uses. The provider collects them and checks its real answers against every one before it ships. Now the provider can see that Consumer A reads id and status and Consumer B reads id, amount_kobo and reference. It can see that currency is read by nobody, so it can be reshaped freely, and that status is read by A, so the rename needs a conversation first. The consumer’s list is also small enough to review.
Pact is the best-known tool for this. A consumer records its interactions as it tests its client against a mock; the recorded file is the contract; the provider replays each recorded request and checks that the response contains at least the data described. The Pact documentation puts the rules as: focus on the messages, not the provider’s behaviour, and keep checks independent of the data the provider happens to return. The lab does not use Pact, which needs a broker or file exchange between repositories and is a chapter on its own. It uses the same idea with plain JSON Schema and one file in each direction, which is enough to see the mechanism.
What counts as breaking
The rule that decides the design of a check is that additions are safe and removals are not, as long as consumers read only what they need. Fowler’s note on the Tolerant Reader names the reader’s side of this discipline: take what you need and ignore the rest.
| Provider change | Breaks a consumer that reads the field? | Should the contract check fail? |
|---|---|---|
| Add an optional response field | No | No. Extra fields must pass. |
| Remove or rename a response field | Yes | Yes |
| Change a response field’s type (integer to string) | Yes | Yes |
| Add a value to a response enum that clients switch on | Possibly: the client’s if may have no branch for it |
Fails only where the contract lists the allowed values |
| Make a request field newly required | Yes | Yes, for the request schema |
| Change the meaning of a field, same name and type | Yes, silently | No. A shape check cannot see this. |
The last row is the limit of the technique. If amount_kobo switches from kobo to naira with the type unchanged, every shape check stays green. That is a job for the integration and end-to-end tests in the rest of this module, and for the provider’s release notes.
Making the check strict enough, and no stricter
Two mistakes recur. Both are about how tight the schema is.
Too strict. "additionalProperties": false on a response schema makes every added field a failure. The first harmless addition blocks a release, the team asks for an exception, and within a quarter the check is skipped. You will watch this in the lab. Leave the response schemas open. Be strict where being strict protects someone: required for the fields consumers read, type for each, enum for values a client branches on.
Too loose. {"type": "object"} passes everything and protects nothing. A schema written by copying one response and loosening it until it stops failing is usually here. Write down each field that is read, and its type.
A third mistake is quieter: the contract and the provider drift together. In the lab the contract file sits next to the app, so one engineer can change both in a single commit and the provider’s own contract test stays green. That is why the consumer’s list matters. It lives in the consumer’s repository, and changing the provider’s file cannot make it pass. The lab shows this too.
A last caution is the one the Pact documentation makes. Contract tests are for messages. If you find yourself asserting that the provider computes the right fee, you are writing a functional test of the provider inside a contract test. Keep them apart: a contract test fails when the shape changes, a functional test fails when the logic does, and mixing them makes the first kind fail for reasons that are not changes in shape.
Where it sits in the suite
A contract test is cheaper than an integration test and catches a different thing.
| Test | What runs | Catches | Typical cost |
|---|---|---|---|
| Unit test with a double | One function; the neighbour is faked | Logic errors | Milliseconds |
| API test | Your service’s whole HTTP layer, in process; neighbours faked | Routing, validation, status codes, body shape | Milliseconds to tens of milliseconds |
| Contract test | A real message from one side checked against the written shape | The two sides drifting apart | Milliseconds if run against an in-process provider; a call if run against a sandbox |
| Integration test | Your service with a real database or real neighbour | Wiring and behaviour that doubles hide | Seconds |
| End-to-end test | The deployed system through its UI or public API | Whether the journey works | Seconds to minutes |
Run the provider contract test in the provider’s pipeline, on every change, because that is where a breaking change is introduced. Run the consumer’s check in the consumer’s pipeline against the provider’s published contract or a sandbox. A third-party provider you cannot gate, such as a payment provider, can still be checked on a schedule: a nightly job that makes one real sandbox call and validates the response against the consumer’s list turns a surprise on Monday into a failure on Sunday night. For the API Design course’s treatment of the same ground from the designer’s side, see testing-apis (planned). To see the framework’s own description of your service to compare against, FastAPI serves it at /openapi.json; comparing that file between commits is a cheap breaking-change detector for your own API.
The lab in one paragraph
You will write three small files. The first tests Ojaline’s checkout API through TestClient. The second checks the fake provider’s answers against fake_provider/contract.json, the provider’s contract. The third checks them against a list of only what Ojaline’s payments_client.py reads, runs the real client against the provider app in process, and keeps one create_autospec unit test beside them for comparison. Then you break the provider four ways and note which checks notice.
Everything runs in process, so you do not need to start the servers on 8094 and 8095. The tests use temporary databases and the provider app’s in-memory state, which each test resets, so nothing here touches data/. Work from labs/testing.
cd labs/testing
.venv/bin/pytest -q23 passed, 1 skipped, 1 deselected. The starter suite on clean code. The skip is the browser test.1. Test POST /orders and GET /orders/{id}.
Create tests/api/__init__.py as an empty file, then tests/api/test_orders_api.py:
"""POST /orders and GET /orders/{id}, in process, with a stubbed payment client."""
import pytest
from fastapi.testclient import TestClient
from jsonschema import validate
from checkout.api import create_app
from checkout.payments_client import ChargeResult
from checkout.search_index import SearchIndex
CART = {"lines": [{"product_id": 2, "qty": 2}], "distance_km": 3} # N7,000 of shea butter + N1,500 delivery
TOTAL = 902_500 # kobo: 700,000 net + 52,500 VAT + 150,000 delivery
@pytest.fixture
def client(db, payments, clock):
return TestClient(create_app(db, payments, clock, SearchIndex()))
def place(client, key="key-1", body=CART):
return client.post("/orders", json=body, headers={"Idempotency-Key": key})
def test_a_new_order_is_201_and_charges_the_total_once(client, payments):
resp = place(client)
assert resp.status_code == 201
order = resp.json()
assert order["id"].startswith("ord_")
assert order["status"] == "paid"
assert order["total_kobo"] == TOTAL
assert order["charge_id"] == "ch_stub"
assert payments.calls == [("key-1", TOTAL, "key-1")]
def test_get_returns_the_order_that_post_created(client):
created = place(client).json()
resp = client.get(f"/orders/{created['id']}")
assert resp.status_code == 200
assert resp.json() == created
def test_the_same_key_replays_the_first_order_with_200(client, payments):
first = place(client)
second = place(client)
assert (first.status_code, second.status_code) == (201, 200)
assert second.json()["id"] == first.json()["id"]
assert len(payments.calls) == 1
def test_an_unknown_order_is_404_with_an_error_body(client):
resp = client.get("/orders/ord_000000000000")
assert resp.status_code == 404
assert resp.json() == {"error": "not_found", "detail": "ord_000000000000"}
def test_a_missing_idempotency_key_is_422(client):
resp = client.post("/orders", json=CART)
assert resp.status_code == 422
def test_a_zero_quantity_is_422_and_charges_nothing(client, payments):
body = {"lines": [{"product_id": 2, "qty": 0}]}
assert place(client, body=body).status_code == 422
assert payments.calls == []
@pytest.mark.parametrize(
"lines, provider_says, status, code",
[
([{"product_id": 99, "qty": 1}], None, 404, "unknown_product"),
([{"product_id": 3, "qty": 6}], None, 409, "out_of_stock"), # product 3 has 5 in stock
([{"product_id": 2, "qty": 1}], ChargeResult("", "declined", "insufficient_funds"), 402, "payment_declined"),
],
ids=["unknown-product", "out-of-stock", "declined"],
)
def test_errors_use_the_documented_status_and_body(client, payments, lines, provider_says, status, code):
if provider_says:
payments.result = provider_says
resp = place(client, body={"lines": lines})
assert resp.status_code == status
body = resp.json()
assert body["error"] == code
assert isinstance(body["detail"], str)
ORDER_SHAPE = {
"type": "object",
"required": ["id", "status", "total_kobo", "charge_id", "created_at", "lines"],
"properties": {
"id": {"type": "string", "pattern": "^ord_[0-9a-f]{12}$"},
"status": {"type": "string", "enum": ["paid"]},
"total_kobo": {"type": "integer", "minimum": 1},
"charge_id": {"type": "string"},
"created_at": {"type": "string"},
"lines": {"type": "array", "minItems": 1},
},
}
def test_the_order_has_the_shape_our_own_consumers_rely_on(client):
validate(place(client).json(), ORDER_SHAPE).venv/bin/pytest tests/api -q -p no:randomly10 passed. The first test shows the whole request path: status 201, an ord_ id, the total in kobo, and the stub provider called once with the key as reference and idempotency key. The replay test shows the retry promise at the API. The parametrised test covers 404, 409 and 402 in one table. Cases that need the stub to answer differently set payments.result, the attribute the lab’s StubPayments returns.2. Check the provider against its own contract.
Create tests/contract/__init__.py as an empty file, then tests/contract/test_provider_contract.py:
"""The provider's answers against its published contract (fake_provider/contract.json)."""
import json
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from jsonschema import validate
from fake_provider.app import app as provider_app
CONTRACT = json.loads((Path(__file__).resolve().parents[2] / "fake_provider" / "contract.json").read_text())
def check(endpoint, status, body):
"""Validate a response body against the contract's schema for this endpoint and status."""
responses = CONTRACT["endpoints"][endpoint]["responses"]
assert str(status) in responses, f"{endpoint} answered {status}; the contract does not list it"
schema = dict(responses[str(status)], definitions=CONTRACT["definitions"]) # so '#/definitions/charge' resolves
validate(body, schema)
@pytest.fixture
def provider():
client = TestClient(provider_app)
client.post("/_admin/reset")
yield client
client.post("/_admin/reset")
PAYLOAD = {"reference": "key-1", "amount_kobo": 902_500, "currency": "NGN"}
@pytest.mark.parametrize("mode, status", [("ok", 201), ("decline", 402), ("500", 500)])
def test_create_charge_answers_as_the_contract_says(provider, mode, status):
resp = provider.post("/v1/charges", json=PAYLOAD, headers={"X-Fake-Mode": mode, "Idempotency-Key": "k"})
assert resp.status_code == status
check("POST /v1/charges", resp.status_code, resp.json())
def test_a_repeated_key_answers_200_in_the_same_shape(provider):
headers = {"Idempotency-Key": "k"}
provider.post("/v1/charges", json=PAYLOAD, headers=headers)
again = provider.post("/v1/charges", json=PAYLOAD, headers=headers)
assert again.status_code == 200
check("POST /v1/charges", 200, again.json())
def test_get_charge_answers_as_the_contract_says(provider):
made = provider.post("/v1/charges", json=PAYLOAD, headers={"Idempotency-Key": "k"}).json()
found = provider.get(f"/v1/charges/{made['id']}")
check("GET /v1/charges/{id}", found.status_code, found.json())
missing = provider.get("/v1/charges/ch_nope")
assert missing.status_code == 404
check("GET /v1/charges/{id}", missing.status_code, missing.json())The check helper adds the contract’s definitions to each schema so that the pointer #/definitions/charge resolves. Without that, jsonschema cannot find the target of the reference.
.venv/bin/pytest tests/contract/test_provider_contract.py -q -p no:randomly5 passed. The provider’s ok, decline and 500 modes, a repeated key, and a lookup of a charge that exists and one that does not, each checked against the schema for that endpoint and status. A status the contract does not list fails with a message that says so.3. Check only what Ojaline reads.
Create tests/contract/test_consumer_needs.py. NEEDS is the consumer’s list, written from reading checkout/payments_client.py: id and status on 200 and 201, and code on 402. client_for runs the real PaymentsClient against the provider app, using httpx.MockTransport to hand each request to the provider in process.
"""What the checkout service reads from the provider, and nothing more."""
from unittest.mock import create_autospec
import httpx
import pytest
from fastapi.testclient import TestClient
from jsonschema import validate
from checkout.orders import place_order
from checkout.payments_client import ChargeResult, PaymentsClient, PaymentUnavailable
from fake_provider.app import app as provider_app
# payments_client.py reads body['id'] and body['status'] on 200 and 201, and body.get('code') on 402.
# It reads nothing from a 5xx body. No 'additionalProperties': false, so extra fields are allowed.
NEEDS = {
201: {"type": "object", "required": ["id", "status"], "properties": {"id": {"type": "string"}, "status": {"type": "string"}}},
200: {"type": "object", "required": ["id", "status"], "properties": {"id": {"type": "string"}, "status": {"type": "string"}}},
402: {"type": "object", "properties": {"code": {"type": "string"}}},
}
PAYLOAD = {"reference": "key-1", "amount_kobo": 902_500, "currency": "NGN"}
@pytest.fixture
def provider():
client = TestClient(provider_app)
client.post("/_admin/reset")
yield client
client.post("/_admin/reset")
def client_for(provider, mode="ok"):
"""The real PaymentsClient, with its HTTP calls answered by the provider app in this process."""
def handler(request):
resp = provider.request(request.method, request.url.path, content=request.content, headers=dict(request.headers))
return httpx.Response(resp.status_code, content=resp.content, headers={"content-type": "application/json"})
return PaymentsClient("http://provider", transport=httpx.MockTransport(handler), headers={"X-Fake-Mode": mode})
@pytest.mark.parametrize("mode, status", [("ok", 201), ("decline", 402)])
def test_the_provider_answers_with_the_fields_we_read(provider, mode, status):
resp = provider.post("/v1/charges", json=PAYLOAD, headers={"X-Fake-Mode": mode})
assert resp.status_code == status
validate(resp.json(), NEEDS[status])
def test_the_real_client_reads_a_real_provider_answer(provider):
result = client_for(provider).charge("key-1", 902_500, "key-1")
assert result.status == "succeeded"
assert result.id.startswith("ch_")
def test_the_real_client_reads_a_decline(provider):
result = client_for(provider, "decline").charge("key-2", 902_500, "key-2")
assert (result.status, result.code) == ("declined", "insufficient_funds")
def test_the_real_client_treats_a_provider_500_as_unavailable(provider):
with pytest.raises(PaymentUnavailable):
client_for(provider, "500").charge("key-3", 902_500, "key-3")
def test_place_order_with_a_mock_client_stays_green(db, clock):
payments = create_autospec(PaymentsClient, instance=True)
payments.charge.return_value = ChargeResult("ch_mock", "succeeded")
order, created = place_order(db, payments, clock, [{"product_id": 2, "qty": 2}], "key-4", distance_km=3)
assert created and order["charge_id"] == "ch_mock".venv/bin/pytest -q44 passed, 1 skipped, 1 deselected: the 23 starter tests, ten API tests, five provider-contract tests and six consumer tests. The consumer’s schema does not mention amount_kobo, currency or reference, because the client never reads them. Notice that the real client is exercised against the provider’s real code here, which a Mock cannot do.4. The provider renames a field, and forgets the contract.
Edit fake_provider/app.py only. Change the line "status": "succeeded", to "state": "succeeded",. Leave contract.json alone.
.venv/bin/pytest -q -p no:randomly --tb=no5 failed, 39 passed, 1 skipped, 1 deselected. Three failures are in test_provider_contract.py (the provider no longer matches what it published: 'status' is a required property) and two are in test_consumer_needs.py (the schema check, and the real client, which dies with KeyError: 'status' at checkout/payments_client.py line 47). All ten API tests and test_place_order_with_a_mock_client_stays_green pass. They never see the wire, so the outage you would have on Monday is invisible to them. That is the Thursday of Fakes, stubs and mocks again, the same status to state rename, caught this time by the provider’s own check.5. The provider renames the field and updates its contract.
Now do what a careful engineer on the provider side would do. Keep the app change and also edit fake_provider/contract.json: replace both quoted "status" strings (in required and in properties) with "state".
.venv/bin/pytest -q -p no:randomly --tb=no2 failed, 42 passed, 1 skipped, 1 deselected. The five-test provider check is green, because the provider is consistent with its own new contract. Only the two consumer tests fail. A contract that lives with the provider cannot protect a consumer from its provider’s decision. The consumer’s list can, and the failure names the consumer and the field. In a real pipeline this failure blocks the provider’s release until Lwazi’s team and Ojaline’s agree on a migration.Undo both edits before the next step: git checkout fake_provider/ in a clone of the lab, or put the two lines back by hand.
6. Two changes that must not look the same.
First, add a field. In fake_provider/app.py, add the line "fee_kobo": 0, after the line that sets "reference" inside the charge dictionary.
.venv/bin/pytest -q -p no:randomly --tb=no44 passed, 1 skipped, 1 deselected. An extra field passes both checks, because neither schema forbids one. Now remove that line and change "amount_kobo": body.amount_kobo, to "amount_kobo": str(body.amount_kobo),. The run gives 3 failed, 41 passed, 1 skipped, 1 deselected. Only the three provider-contract tests fail ('902500' is not of type 'integer'). The consumer tests stay green, because Ojaline’s client never reads amount_kobo. That is the right answer for this consumer, and the provider’s own check still stops the change from shipping.fake_provider/app.py, then add "additionalProperties": false, as the second line inside the charge definition in fake_provider/contract.json (after "type": "object",), and add the "fee_kobo": 0, line to the app again. Run the suite: 3 failed, 41 passed, 1 skipped, 1 deselected. The three provider-contract tests fail on an addition that harms nobody, and the consumer tests stay green. Now picture that on the Friday before a holiday, with a deploy waiting. Decide whether you would loosen the schema or override the check, and notice that overriding is what teams do. Then undo every edit to fake_provider/ and delete the three new test files if you do not want to keep them; the next chapters build on a clean lab.Put the lab back. Run git checkout fake_provider/, then delete the folders tests/api/ and tests/contract/. The project at the end of the module builds its own tests/contract/test_provider_contract.py from a clean lab, and it will not find yours.
Ferrowave has 210 business customers, and about 30 of them have written their own client for the payouts API. Lwazi wants a check that stops a breaking change before it ships. Isatou says customers will not write contract files, and that the provider's own JSON Schema should be enough. Ferrowave also publishes an official SDK that most customers use. What do you propose?
- POST Consumer-Driven Contracts: A Service Evolution Pattern Ian Robinson, 2006
The origin of the pattern this chapter used. Read the sections on provider contracts, consumer-driven contracts and breaking changes; the Schematron material is dated and can be skipped.
- DOC How Pact works
The Pact tool's own account of consumer tests, provider verification and the rule that checks should follow messages and not behaviour. Read it to see what the lab's two files would turn into with a tool and a broker.
- POST Contract Test Martin Fowler, 2011
A short note on contract tests as the check that your test doubles still match the real service. It is the idea behind step 3. Five minutes.
- POST Tolerant Reader Martin Fowler
The reader-side half of the rule that additions are safe: take only what you need and ignore the rest. Read it before you write a consumer's schema.
- DOC Learn JSON Schema: getting started step by step
Enough of the schema language (type, required, properties, enum, minimum) to write and read every schema in this chapter. Skip the sections on advanced composition on a first pass.
- DOC python-jsonschema documentation
The library the lab uses. Read the pages on validate and on how references are resolved, which explain the definitions trick in step 2.
- DOC HTTPX: Transports
The page behind httpx.MockTransport, which let the real client talk to the provider app without a network. Read the section on mock transports and skip the proxy and Unix-socket material.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.