How do you validate that an API's actual behavior matches its published OpenAPI specification, preventing documentation drift?
Short answer
Contract testing tools (like Pact, or OpenAPI-specific validators like Spectral for linting the spec itself, or Prism for mocking/validating against a spec) can programmatically compare actual API responses against the documented schema in CI, catching cases where the…
Advertisement
AModel answer
Contract testing tools (like Pact, or OpenAPI-specific validators like Spectral for linting the spec itself, or Prism for mocking/validating against a spec) can programmatically compare actual API responses against the documented schema in CI, catching cases where the implementation has silently diverged from its documented contract -- since Swashbuckle/OpenAPI generation reflects the code's current actual behavior automatically, drift more commonly arises from hand-maintained specs or when documentation intentionally diverges from implementation for legacy reasons.
Example
# Using Spectral to lint an OpenAPI spec for quality/consistency issues spectral lint https://api.example.com/swagger/v1/swagger.json # Contract testing validates actual runtime responses match the documented schema # as part of a CI pipeline step, failing the build on mismatch
Real-world example
A CI pipeline adds a contract validation step confirming that a newly deployed API version's actual JSON responses still conform exactly to its published OpenAPI schema, catching a case where a developer accidentally changed a field's type without updating documentation.
Likely follow-ups
- Since Swashbuckle generates docs FROM code, how can drift still occur?
- How does this differ for a hand-maintained OpenAPI spec used as a design-first contract?
Related topics