download

How do API contract tests catch breaking response changes early?

Testing~9 minReviewed 2 Dec 2026Free · No sign-in

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 string
  • amount_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.

  1. Which response changes break consumers, and which are safe?
  2. Write check_invoice(code, content_type, body) to catch bad status, header, missing keys, wrong types, and unknown enum values.
  3. When do you use provider schema tests vs consumer-driven tests?
"CODE · PYTHON"
def check_invoice(code, content_type, body):
    # Check status, media type, required keys, types, and enum.
    # Allow extra additive fields.
    pass
Show hints (3)
  1. "PARSE MEDIA TYPE"

    Servers often send application/json; charset=utf-8. Split on ; and compare the trimmed media type, not the full header string.

  2. "WATCH PYTHON BOOLS"

    isinstance(True, int) is True in Python! Use type(val) is int so a boolean never passes as an integer cent amount.

  3. "ALLOW ADDITIVE KEYS"

    Check REQUIRED <= body.keys() instead of body.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.

"SOLUTION · PYTHON"
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")
"OUTPUT"
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 changeBreaking?Why
Remove amount_centsYesConsumer reads a missing required key
Change 1999 to "1999"YesTyped parsers fail on string instead of int
Add enum "cancelled"YesStrict consumer switches lack the new branch
Return 201 or text/plainYesClient checks 200 and JSON media type
Add "currency": "USD"NoTolerant 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 excluding bool. A JSON true silently passes as 1 cent.
  • Validating only the JSON body while ignoring HTTP status codes and Content-Type. Returning 200 with text/html on 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 enum really a breaking change?" Yes for strict consumers that deserialize into a closed enum or exhaustive switch. 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_cents to total_cents without breaking older mobile versions?" Use expand-and-contract. First deploy both amount_cents and total_cents together (additive, safe), migrate and wait for old clients to age out, and only remove amount_cents once 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 →

Original OfferVibe question. OpenAPI 3.1.1 Specification · RFC 9110 HTTP Semantics · Python http.server.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.