Implement consumer-driven contract testing
Define a Pact contract between a Python consumer and a FastAPI provider for a user lookup endpoint. The consumer publishes the contract (its expectations of the API), the provider verifies against it. Run provider verification in CI and configure the build to fail when the provider makes a breaking change.
Why this matters
Integration tests catch breaking API changes; but only if you run them against a real provider. Contract testing inverts this: the consumer defines what it needs, and the provider verifies it can meet those needs. This eliminates the most common microservices failure mode: a provider team changes their API without knowing a consumer depends on the old format.
Before you start
- Python with pact-python installed
- A FastAPI application exposing a user lookup endpoint (GET /users/{id})
- Understanding of what a consumer and provider are in a microservices context
- pytest for running the consumer tests
Step-by-step guide
- 1
Write the consumer contract test
Use pact-python to define what the consumer expects: the consumer will call GET /users/123 and expects a 200 response with a JSON body containing id (integer), name (string), and email (string). Run the consumer test; it starts a mock provider and verifies your consumer code works against it, generating a pact file.
- 2
Publish the pact to a broker
Set up a Pact Broker (Pactflow has a free tier) and publish the generated pact file using the Pact CLI. The broker is the handshake point; the provider will pull contracts from here rather than needing access to the consumer's code.
- 3
Write the provider verification test
In the FastAPI provider repository, write a pytest test that starts the FastAPI app and runs pact.verify() against it, pointing at the broker URL. The verification test replays each consumer interaction against the real provider and asserts the response matches the contract.
- 4
Break the contract and verify the build fails
Change the FastAPI endpoint to return username instead of name in the response. Run the provider verification. It should fail with a clear message about the field name mismatch. This is the outcome you are building toward; catching breaking changes before deployment.
- 5
Add verification to CI
Add the provider verification test to your CI pipeline. Configure it to run on every PR that touches the API layer. The pipeline should block merge when verification fails. This is the enforcement mechanism; without it, contract tests are advisory rather than mandatory.