Our API has three main consumers: a web app, an Android app and an iOS app, each owned by a different team. For years we tested the boundary between them the usual way: the API had its own tests, each client mocked the API in theirs, and a shared staging environment was supposed to catch everything else.
It did not. We kept shipping changes that passed every test suite and still broke a client: a removed field, a renamed enum value, a date format change. The problem was that each side tested against its own idea of the contract, and nothing checked that the two ideas matched.
Consumer-driven contract tests fix exactly that gap. This post covers how we set them up with Pact, how they run in CI, and what they do not catch.
What a contract test checks
A contract test sits between unit tests and end-to-end tests:
| Test type | Checks | Runs against |
|---|---|---|
| Unit test in client | client logic, with a hand-written mock API | the client's own mock |
| Unit test in API | API logic | the API in isolation |
| Contract test | the requests a client sends and the response shape it needs | client side: a mock generated from the contract; API side: the real API |
| End-to-end test | a full user journey | deployed services |
"Consumer-driven" means the client writes the contract. Each consumer records the requests it actually makes and the parts of the responses it actually reads. The provider (API) then proves it satisfies every consumer's contract. The API team learns precisely which fields and endpoints each client depends on, which is information they never had before.
Writing a contract on the consumer side
The web app is TypeScript. A consumer test describes one interaction and runs the client code against a mock server that Pact starts:
import { PactV4, MatchersV3 } from "@pact-foundation/pact";
const { like, eachLike, regex } = MatchersV3;
const provider = new PactV4({ consumer: "web-app", provider: "shipments-api" });
test("lists shipments for the current account", () =>
provider
.addInteraction()
.given("account A1 has 2 shipments")
.uponReceiving("a request for shipments")
.withRequest("GET", "/v2/shipments", (b) =>
b.headers({ Authorization: like("Bearer token") }).query({ limit: "20" }))
.willRespondWith(200, (b) =>
b.jsonBody({
data: eachLike({
id: like("S-1001"),
status: regex("pending|in_transit|delivered", "in_transit"),
eta: regex(/^\d{4}-\d{2}-\d{2}T/.source, "2026-11-20T10:00:00Z"),
}),
next_cursor: like("abc"),
}))
.executeTest(async (mock) => {
const api = new ShipmentsClient(mock.url, "token");
const page = await api.list({ limit: 20 });
expect(page.items[0].status).toBe("in_transit");
}));
Some points that took us a while to learn:
- Only include what the client reads. The real response has 30 fields; the web app uses three. If the contract lists all 30, the API cannot remove any field without breaking the contract, even fields no client uses. Smaller contracts give the provider more freedom.
- Use matchers, not literal values.
like("S-1001")means "a string", not "exactly S-1001". Contracts with literal values become brittle test data, not a description of the interface. - Run the real client code. The test calls
ShipmentsClient, the same class the app uses. If the client builds the URL wrongly, the mock server rejects it and the test fails.
Running the test produces a JSON pact file, which CI publishes to a Pact Broker along with the consumer's version (the git commit) and branch.
Verifying on the provider side
The API is Python. Provider verification starts the real API with a test database, fetches the relevant pacts from the broker, replays each request and compares the response to the contract:
from pact import Verifier
def test_provider_honours_consumer_contracts(live_api_url):
verifier = Verifier(provider="shipments-api", provider_base_url=live_api_url)
success, _ = verifier.verify_with_broker(
broker_url=os.environ["PACT_BROKER_URL"],
broker_token=os.environ["PACT_BROKER_TOKEN"],
publish_version=os.environ["GIT_SHA"],
provider_version_branch=os.environ["GIT_BRANCH"],
consumer_version_selectors=[
{"mainBranch": True},
{"deployedOrReleased": True},
],
provider_states_setup_url=f"{live_api_url}/_pact/provider-states",
publish_verification_results=True,
)
assert success == 0
Two parts deserve explanation.
Provider states. given("account A1 has 2 shipments") in the consumer test is a named precondition.
The API exposes a test-only endpoint that receives the state name and seeds the database accordingly. That
endpoint is only mounted when the app runs in the test environment, and the router refuses to register it
otherwise.
Consumer version selectors. We verify against the contracts from each consumer's main branch and from every version currently deployed or released. For mobile, "released" includes every app version still in the stores and in use. That is what protects old app versions: if the API change breaks the contract of Android 6.0, which is still released, verification fails even though Android's main branch has moved on.
Gating deploys with can-i-deploy
Verification results go back to the broker. Before any deploy, of the API or a client, CI asks the broker whether this version is compatible with everything already in the target environment:
pact-broker can-i-deploy \
--pacticipant shipments-api --version "$GIT_SHA" \
--to-environment production
CONSUMER | C.VERSION | PROVIDER | P.VERSION | SUCCESS?
-----------------+-----------+----------------+-----------+---------
web-app | 4f2a91c | shipments-api | 9be03d1 | true
android-app | 6.4.2 | shipments-api | 9be03d1 | true
android-app | 6.0.4 | shipments-api | 9be03d1 | false
Computer says no. There are failed verification results.
After a successful deploy, CI records it (pact-broker record-deployment for the API and web,
record-release for app store versions), so the broker always knows what is live where.
Handling a deliberate breaking change
Contract tests do not prevent change; they make it explicit. When the API team wants to remove a field:
- Check which consumers' contracts include it. The broker shows this per field.
- Ask those consumers to stop reading it and publish new contracts.
- Wait until no deployed or released consumer version needs it (for mobile, until old versions drop out of support).
- Remove the field. Verification passes because no live contract references it.
Before contract tests, step 1 was a message in a chat channel asking "does anyone use legacy_tier?".
What contract tests do not catch
This is the part teams tend to oversell. Contract tests check the shape of the interface for the interactions consumers wrote down. They do not check:
- Business logic. A contract can say
totalis a number. It cannot saytotalis the right number. That stays in the API's own tests. - Interactions nobody recorded. If the iOS app calls an endpoint without a contract test for it, nothing protects that call. We track contract coverage per client as a list of endpoints with and without interactions.
- Behaviour across several requests. "After POST, GET returns the new item" spans two interactions and depends on state. We cover a few critical flows with end-to-end tests.
- Performance, timeouts and rate limits. Nothing about latency is in a pact.
- Third-party APIs you do not control. A provider has to run verification. Payment or mapping vendors will not run your pacts. For them we use recorded-response tests and the vendor's own sandbox.
- Authorization semantics. The contract shows a request with a token gets a 200. It does not prove a different user's token gets a 403. Those are policy tests on the API side.
What changed for us
| Measure | Before | After (6 months) |
|---|---|---|
| Client breakages caused by API deploys | 9 per half-year | 1 (an interaction nobody had recorded) |
| Time to answer "who uses this field" | days of asking around | seconds in the broker |
| Shared staging environment needed for API/client compatibility | yes | no, staging now only runs end-to-end smoke tests |
The cost was real: about two weeks to set up the broker and CI steps, plus ongoing time to keep provider states working. Provider states turned out to be the main source of flaky verification, mostly from tests that depended on IDs created by previous states. Seeding fixed IDs per state, in a fresh transaction, solved it.
Summary
- Contract tests check that what each client sends and reads matches what the API serves.
- Consumers record only the fields they use, with matchers rather than literal values.
- The provider verifies against main branches and every deployed or released consumer version, which protects old mobile versions.
can-i-deployturns the results into a deploy gate.- They do not test business logic, authorization, multi-step behaviour or performance. Keep those tests.
References: Pact documentation, Consumer version selectors, can-i-deploy, Provider states.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.