Contract testing and schema validation focus on the โshapeโ of API requests and responses rather than every detail of behaviour. They help ensure that changes in one service do not break consumers unexpectedly. This is especially important in microservice and multi-team environments.
API Contracts and Schemas
Contracts describe the expected endpoints, methods, parameters, and response structures. They can be written in formats like OpenAPI (Swagger) or JSON Schema. Schema validation tests check that actual responses conform to these definitions, catching breaking changes early.
{
"type": "object",
"properties": {
"id": { "type": "string" },
"email": { "type": "string", "format": "email" },
"createdAt": { "type": "string", "format": "date-time" }
},
"required": ["id", "email", "createdAt"]
}
Consumer-driven contract testing goes a step further by letting client teams define the aspects of the contract they depend on. Providers then run these contracts in their pipelines to verify they still satisfy consumer expectations after changes.
Where to Apply Schema Validation
You can validate responses at the API gateway, within service tests, or in dedicated contract test suites. Choose locations that provide fast feedback while reflecting real integration points. For internal services, schemas may evolve quickly; external-facing APIs usually require stricter compatibility promises.
Common Mistakes
Mistake 1 โ Relying solely on informal documentation
Documentation can drift away from reality.
โ Wrong: Only checking API docs manually without verifying actual responses.
โ Correct: Use machine-readable contracts and automated schema checks.
Mistake 2 โ Making schemas too rigid or too vague
Both extremes reduce usefulness.
โ Wrong: Schemas that either accept almost anything or fail on insignificant cosmetic changes.
โ Correct: Model required structure and constraints that matter to clients.