How do API contract tests catch breaking response changes early?
Question
Mobile checkout calls GET /v1/invoices/inv-42 and expects HTTP 200, Content-Type application/json, and a JSON object with:
id: non-empty stringamount_cents: integer (never a string or boolean)status: one of"open","paid","void"
Additive optional fields (like "currency": "USD") are safe. Last week a backend deploy changed amount_cents from 1999 to "1999" and broke mobile checkout with all unit tests green.
- Which response changes break consumers, and which are safe?
- Write
check_invoice(code, content_type, body)to catch bad status, header, missing keys, wrong types, and unknown enum values. - When do you use provider schema tests vs consumer-driven tests?
def check_invoice(code, content_type, body): # Check status, media type, required keys, types, and enum. # Allow extra additive fields. pass
Show hints (3)
- "PARSE MEDIA TYPE"
Servers often send
application/json; charset=utf-8. Split on;and compare the trimmed media type, not the full header string. - "WATCH PYTHON BOOLS"
isinstance(True, int)isTruein Python! Usetype(val) is intso a boolean never passes as an integer cent amount. - "ALLOW ADDITIVE KEYS"
Check
REQUIRED <= body.keys()instead ofbody.keys() == REQUIRED, so new optional fields do not cause false failures.
Show checked explanation
An API contract fixes the HTTP status, Content-Type, required fields, types, and allowed enum values. Validate responses against those rules while allowing extra additive keys. Run provider OpenAPI checks on every PR to catch schema drift, and add consumer-driven contracts when several teams depend on different subsets of the same endpoint.
ALLOWED_STATUS = {"open", "paid", "void"}
REQUIRED = {"id", "amount_cents", "status"}
def check_invoice(code, content_type, body):
assert code == 200, f"status {code}"
assert content_type.split(";")[0].strip().lower() == "application/json"
assert isinstance(body, dict) and REQUIRED <= body.keys()
assert isinstance(body["id"], str) and body["id"]
assert type(body["amount_cents"]) is int
assert body["status"] in ALLOWED_STATUS
good = {"id": "inv-42", "amount_cents": 1999, "status": "paid", "note": "ok"}
check_invoice(200, "application/json; charset=utf-8", good)
print("contract passed")contract passed
Executed the solution on CPython 3.12.10 and ran check_invoice over real HTTP against a local ephemeral http.server covering valid responses (including mixed-case Content-Type) plus 7 breaking mutations. Checked by an editor other than the author.
Walkthrough
Unit tests inside the billing service often mock serializers or assert on Python objects before JSON encoding. That is how amount_cents: "1999" or Content-Type: text/plain ships with a green build and crashes downstream parsers.
A response check should reject breaking changes while permitting safe evolution:
| Response change | Breaking? | Why |
|---|---|---|
Remove amount_cents | Yes | Consumer reads a missing required key |
Change 1999 to "1999" | Yes | Typed parsers fail on string instead of int |
Add enum "cancelled" | Yes | Strict consumer switches lack the new branch |
Return 201 or text/plain | Yes | Client checks 200 and JSON media type |
Add "currency": "USD" | No | Tolerant consumers ignore unknown fields |
Look closely at two details in check_invoice. First, content_type.split(";")[0].strip().lower() accepts Application/JSON; charset=utf-8 (RFC 9110 media types are case-insensitive) while rejecting text/plain. Second, type(body["amount_cents"]) is int blocks booleans, because isinstance(True, int) evaluates to True in Python.
Provider schema checks vs consumer-driven contracts. Start with provider schema tests: validate real HTTP responses from your test server against your OpenAPI 3.1 spec on every PR. That catches missing fields, type flips, and status bugs fast with one source of truth. Add consumer-driven contracts (such as Pact) when several separate teams consume your API. Each consumer publishes the exact fields and status codes it relies on. The provider runs those expectations in CI so it learns right away which change breaks a live client.
Common mistakes
- Asserting exact key equality (
body.keys() == REQUIRED). That makes safe additive fields break CI and pushes teams to disable tests. - Using
isinstance(val, int)in Python without excludingbool. A JSONtruesilently passes as1cent. - Validating only the JSON body while ignoring HTTP status codes and
Content-Type. Returning200withtext/htmlon a proxy error still breaks JSON clients. - Mocking the HTTP response inside the provider test instead of calling a real server route and deserializing the wire bytes.
Follow-up questions
- "Is adding a new value to a response
enumreally a breaking change?" Yes for strict consumers that deserialize into a closed enum or exhaustiveswitch. Adding an enum value to a request is backwards-compatible, whereas adding an unexpected enum value to a response can crash older mobile clients unless they explicitly handle unknown values. - "How do you safely rename
amount_centstototal_centswithout breaking older mobile versions?" Use expand-and-contract. First deploy bothamount_centsandtotal_centstogether (additive, safe), migrate and wait for old clients to age out, and only removeamount_centsonce consumer contracts and telemetry confirm zero callers. - "Do contract tests replace end-to-end integration tests?" No. Contract tests prove wire compatibility quickly without spinning up every service. Keep a small set of end-to-end smoke checks for auth, routing, and real data flow across deployed environments.
What a strong answer covers
Separates breaking response changes from safe additive fields. Checks HTTP status, media type, required keys, exact types (excluding bool), and enums over real HTTP, and contrasts OpenAPI checks with consumer-driven contracts.
Open in interactive practice deck →