API contract testing
The integration test passes, but the client crashes. That happens when the server changed the shape of the response and the test only checked for a 200. A contract test closes exactly that gap.
What a contract is
A contract is an agreement about the request and the response: paths, methods,
status codes, fields, types, requiredness, null, and the formats of dates and
errors. The contract does not describe how the server computes the data — only
what the client sees.
{
"order_id": 7781,
"customer": {"id": 7, "name": "Ann"},
"total": 1200,
"status": "paid"
}
The schema pins down: order_id is an integer, customer is an object with
required id and name, total is a number, status is one of the enum
values.
Three levels of checking
- Response schema. Validate a real response against a JSON Schema or
OpenAPI. Catches a missing field, a wrong type, an unexpected
null. - Consumer-driven contract. The client publishes which fields and status codes it actually uses. The provider verifies its build against those expectations. The tool does not matter here: Pact is popular, but not the only option.
- Version compatibility. Run the contracts of published client versions against the new server build. This is the step that catches a broken old mobile app.
What counts as a breaking change
- a field is removed or renamed;
- a type changed (
int→string); - a field was optional and became required;
- the set of allowed values got narrower;
- the meaning of
nullchanged (previously absent, nownullarrives); - the error code or the error body format changed.
Adding an optional field is usually safe. But if the client validates the
schema strictly (additionalProperties: false) or the field is required in its
model, even a "harmless" addition breaks it.
Wiring it into CI
- Keep the schema next to the code and version it.
- On the provider build, validate responses in every scenario, including errors and empty lists.
- Run the contracts of the latest supported client versions.
- Diff the new schema against the old one: a removal or a narrowing fails the build.
- Publish the contract version together with the release.
What a contract test does not do
It does not check business logic. A response can match the schema perfectly and still be wrong: the wrong amount, the wrong order. Contract and scenario tests complement each other; they do not replace each other.
Another boundary is behavioural compatibility. The schema allows
status: null, but the client cannot handle it. Such things are stated in the
contract explicitly: nullable: false or a dedicated test for that scenario.
A short checklist
- The contract covers success responses and errors.
- There is a test for a removed and a renamed field.
- Old client versions are checked in CI.
- A breaking change requires an API version or a transition period.
- The schema and the code are released together.