How to validate API contracts
· Category: API & REST
Short answer
Contract testing verifies that API consumers and providers adhere to a shared agreement, catching breaking changes before deployment.
Steps
- The consumer writes a pact defining the expected request and response.
- A mock provider verifies that the consumer can handle the defined interactions.
- The pact is published to a broker for sharing with the provider team.
- The provider runs pact verification against its actual implementation.
- Both teams are notified of contract violations in CI/CD.
Tips
- Focus on consumer-driven contracts that reflect actual usage rather than exhaustive specs.
- Integrate pact verification into pull request checks.
- Use tags and branches in the pact broker to manage multiple environments.
- Keep contracts focused on the fields consumers actually need.
Common issues
- Providers breaking untested parts of the contract not covered by pacts.
- Out-of-date pacts causing false negatives after intentional changes.
- Difficulty maintaining contracts in rapidly evolving APIs.
- Coordination overhead between consumer and provider teams.
Example
curl -X GET https://api.example.com/users -H "Accept: application/json" -H "Authorization: Bearer $TOKEN"
This curl command demonstrates a standard GET request with headers for content negotiation and bearer token authentication.