API Contract Testing: Catching Breaking Changes With Agents
A breaking API change rarely looks dramatic in the pull request. A field gets renamed, a nullable value starts arriving as null, an ID switches from integer to string, or a new required parameter appears. Unit tests pass, the service's own integration tests pass, and the first sign of trouble is a consumer failing somewhere downstream.
Contract tests exist to catch exactly that. They describe what consumers rely on, separately from the code that produces it, and fail when the producer stops honouring it. That separation is the whole point, and it has become more important now that coding agents edit API code. An agent asked to rename a field will often update the handler, the serializer and the existing tests in one tidy change. Everything stays green, because the tests moved with the code. A contract that the agent is not allowed to edit is what stops that change from slipping through.
In this article I'll show what breaking changes actually look like, how I write contract assertions in Python and Behave, how I wire them into CI, and how the same idea applies to the APIs your agents call as tools.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
What a breaking change actually looks like
From a consumer's point of view, a change is breaking if code that worked yesterday can fail today without the consumer changing anything. In API responses the usual suspects are:
- Removed or renamed fields.
customer_namebecomescustomerName. - Type changes. An
idmoves from integer to string, or a price from number to a formatted string. - Nullability changes. A field that was always present can now be
nullor missing. - Narrowed enums or new values without notice. A
statusgains a value that consumers don't handle. - New required request fields. Old clients start getting 400s.
- Changed error shapes or status codes. A 404 becomes a 200 with an error object, and client error handling silently stops working.
Adding a new optional field is usually not breaking, and a good contract test shouldn't fail on it. That's a design decision you need to make deliberately: contract tests protect what consumers depend on, not every byte of the current response.
Writing contract assertions in Python
The simplest useful contract is a JSON Schema per response, kept in the repository and validated in tests. I use the jsonschema package and collect every error rather than stopping at the first, so one failing run shows the whole picture:
import json
from pathlib import Path
from jsonschema import Draft202012Validator
CONTRACTS = Path(__file__).parent / "contracts"
def assert_matches_contract(body, name):
schema = json.loads((CONTRACTS / f"{name}.schema.json").read_text())
validator = Draft202012Validator(schema)
errors = sorted(validator.iter_errors(body), key=lambda e: list(e.absolute_path))
if errors:
lines = [f"{'/'.join(map(str, e.absolute_path)) or '(root)'}: {e.message}" for e in errors]
raise AssertionError(f"{name} contract violated:\n" + "\n".join(lines))
def test_get_order_honours_contract(api, order_id):
response = api.get(f"/orders/{order_id}")
assert response.status_code == 200
assert_matches_contract(response.json(), "order")
The schema states what consumers rely on: required fields, their types, which ones may be null and which enum values exist.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "status", "total", "customer"],
"properties": {
"id": {"type": "integer"},
"status": {"enum": ["pending", "paid", "cancelled"]},
"total": {"type": "number"},
"customer": {
"type": "object",
"required": ["id", "name"],
"properties": {
"id": {"type": "integer"},
"name": {"type": "string"}
}
}
}
}
Note that I don't set additionalProperties to false here. That would make every new optional field a failure, which trains people to ignore the test. If you want to know about additions, report them separately as information rather than failing the build. For more on wiring schemas into a suite, see validating API response schemas automatically.
The same contract in Behave
If your acceptance tests are in Behave, the contract check becomes a reusable step so scenarios stay readable:
from behave import then
from support.contracts import assert_matches_contract
@then('the response matches the "{name}" contract')
def step_matches_contract(context, name):
assert_matches_contract(context.response.json(), name)
Now a product-facing scenario can end with Then the response matches the "order" contract, and the detail lives in one place.
Fitting contract tests into CI
Contract tests are cheap, so run them on every pull request against the service built from that branch. I mark them so they can run on their own early in the pipeline:
pytest -m contract -q
Register the marker in your pytest configuration so typos fail loudly instead of silently selecting nothing. Two rules make the CI stage meaningful:
- Schema changes need their own review. Put the
contracts/directory under a CODEOWNERS entry so a change to a contract requires approval from someone who owns the consumer relationship. - A contract change and a code change in the same PR is a flag. Sometimes it's legitimate, for a planned version bump. Often it's someone, or something, making the build green.
When a breaking change is intentional, it should arrive as a new version with both contracts tested side by side for a while. I go into that structure in designing test suites that survive an API version bump.
Contracts as the guardrail for coding agents
When an agent works on your API, the contract is the specification it must not quietly rewrite. I state that explicitly in the repository instructions, whether that's .github/copilot-instructions.md for Copilot or the equivalent file for another agent:
## API contracts
- Files in contracts/ describe what consumers depend on. Do not edit them
to make a test pass.
- If a change would violate a contract, stop and explain the conflict in the PR.
- Renaming or removing a response field is a breaking change and needs a new
API version, not an in-place edit.
Instructions aren't enforcement, which is why the CODEOWNERS rule matters. The instruction stops most attempts; the review requirement catches the rest.
The same thinking applies in the other direction, when agents are the consumers. If an agent calls your API as a tool, through an MCP server or a function-calling definition, the tool's input and output schema is a contract too. A renamed field there doesn't just break a client; it can make the agent pass wrong arguments or misread a result without any error. I test those tool definitions the same way: validate the arguments the agent produces against the tool's input schema, and validate the API's response against what the tool description promises.
Contract tests are one of the highest-value, lowest-cost layers in an API suite, and they become more valuable as more of your code is written by something that will happily update the tests to match. For the broader picture of where they sit, see my API testing guide. If you want to build schema checks and Behave steps like these from scratch, my API testing courses cover it in Python and Node.