OpenAPI contract testing compares real HTTP traffic with the published document. Validate request bodies, response bodies, status codes, headers, and content types against the OpenAPI 3.1 schemas, run the same checks for providers and consumer-driven contracts, lint with Spectral, and diff each change against the released baseline so breaking changes fail CI before deployment.
- A contract test proves that requests and responses at the HTTP boundary match the published OpenAPI document, not that the business logic behind them is correct.
- OpenAPI 3.1 uses JSON Schema 2020-12, so nullable disappears, type accepts arrays, exclusiveMinimum takes a number, and $ref siblings are evaluated.
- Provider conformance catches documentation drift; consumer-driven contracts catch the assumptions a specific client makes, and mature systems need both.
- Lint and diff every change in CI: a removed field or a tightened enum is cheap to catch before release and expensive to diagnose in production.
- Generated clients, examples, and documentation are outputs of the contract, never substitutes for testing the contract itself.
An OpenAPI document is a promise about HTTP behavior: which paths exist, what a request may contain, which status codes return, and what each body looks like. Contract testing turns that promise into an executable check: capture or generate traffic, validate it against the document, and fail when the two disagree. The hard part is deciding which parts are contract, which are documentation, and where drift is allowed.
Teams learn that distinction after an incident: a field renamed, an unexpected null, or an HTML error where JSON was promised. Provider tests passed because they asserted what the provider already did; clients broke because nobody tested the promise.
What OpenAPI contract testing actually proves
A contract test compares observable HTTP messages with the published document in both directions. On requests, it checks path, query, header, and cookie parameters, then validates each body against its media type schema. On responses, it checks status codes, headers, content types, and bodies for every documented outcome, errors included. The test is symmetric: clients must not send what the contract forbids, and servers must not return what the contract never promised.
The scope is narrow. A contract test does not prove correct pricing, enforced authorization, idempotent retries, or acceptable latency; those need business, security, and load tests. It proves that the interface behaves as advertised, the layer clients build against and the layer that changes most often without a corresponding test. A suite that exercises only the happy path is a smoke test with better marketing: expensive failures live in undocumented branches, such as a 409 without its error schema or a 204 with a body.
Why OpenAPI 3.1 changes the schema rules
OpenAPI 3.0 schemas were not JSON Schema but a Draft-04-inspired subset with vendor keywords such as nullable, and many tools still treat that subset as the definition of OpenAPI. Version 3.1 replaced it with JSON Schema Draft 2020-12, changing what you can express and how validators interpret it; a document valid under 3.0 can fail validation or mean something different under 3.1.
Four differences dominate contract tests. nullable no longer exists, so null is expressed through a type array. exclusiveMinimum and exclusiveMaximum are numbers, not booleans. Keywords next to $ref are evaluated rather than ignored. The default dialect is declared at the document root, while individual schemas can opt into another with $schema. Tuples use prefixItems, definitions live under $defs, and dependentRequired replaces dependencies.
openapi: 3.1.0
info: { title: Orders API, version: 2.4.0 }
jsonSchemaDialect: https://json-schema.org/draft/2020-12/schema
paths:
/orders/{orderId}:
get:
operationId: getOrder
parameters:
- name: orderId
in: path
required: true
schema: { type: string, format: uuid }
responses:
"200":
description: Order found
headers:
ETag: { required: true, schema: { type: string } }
content:
application/json:
schema: { $ref: "#/components/schemas/Order" }
"404":
description: Order not found
content:
application/problem+json:
schema: { $ref: "#/components/schemas/Problem" }
components:
schemas:
Order:
type: object
required: [id, status, total]
additionalProperties: false
properties:
id: { type: string, format: uuid }
status: { enum: [pending, paid, cancelled] }
total: { type: number, exclusiveMinimum: 0 }
coupon: { type: [string, "null"] }
Problem:
type: object
required: [type, title, status]
properties:
type: { type: string, format: uri-reference }
title: { type: string }
status: { type: integer, minimum: 400, maximum: 599 }
The fragment encodes three deliberate decisions. coupon may be a string or null without nullable. additionalProperties: false closes Order, so every future field becomes breaking for strict clients. exclusiveMinimum: 0 is numeric and valid in 2020-12. A linter, mock server, or generator that only understands 3.0 may silently drop these keywords, so pin the OpenAPI and validator versions and validate against the 3.1 meta-schema before any behavioral test.
Validating requests, responses, headers, and status codes
Request validation belongs at the boundary, before business logic. Reject unsupported content types with 415, malformed syntax with 400, and schema violations with 422 when semantic errors are distinguished from syntax. Validate path and query parameters as rigorously as bodies; a UUID declared as a string still needs its format checked if the handler relies on it. Cookie parameters are easy to forget because frameworks parse them first.
Response validation is usually test-time, with production sampling where affordable. Every documented status code needs a fixture that reaches it and a schema that accepts the body. A default response is a catch-all, not an excuse to leave 409 or 429 undocumented: clients branch on status codes, and an unexpected one becomes a parsing failure. Headers and media types are part of the contract too. A JSON response delivered as HTML, a 201 without Location, a 204 with a body, or a missing ETag are violations. Header names are case-insensitive, but presence and values are not optional. Content-Type is described through content, including charset.
| Layer | Typical defect | What the assertion must cover |
|---|---|---|
| Status code | Undocumented 409, or 500 returned as 200 | Every documented response plus default |
| Content type | HTML error where JSON was promised | Request Accept and response Content-Type |
| Required header | Missing Location or ETag | Presence and schema of each documented header |
| Body shape | Null in a non-nullable field | Full recursive validation of the resolved schema |
| Unknown fields | A typo silently accepted | One additionalProperties policy |
| Error envelope | Different fields per error code | A shared problem schema |
Provider contracts and consumer-driven contracts
Provider contract testing asks whether a service behaves the way its own document says. The tests live with the provider, run against a preview or in-process server, and validate real responses. They catch documentation drift, serialization bugs, framework defaults leaking into responses, and error handlers that bypass the documented envelope. Typical tools are schema-aware clients, property-based generators, and proxy validators.
Consumer-driven contract testing asks whether a service still satisfies what a particular client needs. The consumer records the interactions it depends on, publishes them, and the provider verifies them before release. This catches assumptions the public document never described: a field the client parses that the provider considers internal, a status code the client retries, or an accidental ordering guarantee. Neither approach subsumes the other. A provider can conform perfectly to OpenAPI and still break a consumer that relied on undocumented behavior, while a consumer contract can pass even though the public document is wrong for everyone else. Use OpenAPI as the public contract and consumer-driven contracts for internal dependencies; bi-directional testing, which compares consumer contracts with the document, is a reasonable middle ground.
Nullability, additionalProperties, and schema drift
Nullability is where 3.0 habits produce silent bugs. In 3.1, type: [string, "null"] allows a string or null, while required separately controls whether the property may be absent. Those are different states: optional properties can be missing, required nullable properties must be present and may be null, and required non-nullable properties must always carry a value. Test all three; an enum that includes null must list it explicitly.
additionalProperties is the second silent bug. JSON Schema defaults it to true, so a request with a misspelled field is valid, the server ignores it, and the client believes the value was applied. Setting it to false on requests turns that into a 400 or 422, usually right for writes. On responses, false promises that no field will ever be added, making every additive change breaking for strict clients. Most public APIs keep responses open, document an extension policy, and require clients to ignore unknown fields. With allOf, additionalProperties only sees properties declared in the same schema object; unevaluatedProperties: false evaluates across the composition.
Schema drift is the gap between document and code. Code-first frameworks generate a document from annotations, so a refactor changes the output without review. Hand-written documents are updated after the code, often not at all. A runtime-generated document changes with the application, so a regression rewrites contract and documentation together and the diff looks intentional. Commit the document as a reviewed artifact, regenerate it in CI, and fail when the committed copy differs. Drift should be a visible diff, not a production surprise.
Breaking changes and versioning decisions
A breaking change is any change that can make an existing conforming client fail. Removing an operation, renaming a field, changing a type, narrowing an enum, adding a required request property, removing a documented success code, or changing a response content type all qualify. Adding an optional response field is usually safe for tolerant clients but breaking for strict validators and closed record types. Changing a default can be breaking even when the shape is unchanged, because behavior changed.
| Change | Request impact | Response impact | Release action |
|---|---|---|---|
| Add optional request field | Compatible | None | Minor release |
| Add required request field | Breaking for callers | None | Major release or new endpoint |
| Remove or rename response field | None | Breaking for readers | Major release with deprecation |
| Add response enum value | None | Breaking for exhaustive clients | Deprecate, then major |
| Narrow request enum | Breaking for existing values | None | Major release |
| Add error status code | None | Breaking for status switches | Document, then release |
| Change media type | Breaking | Breaking | New path or major version |
| Tighten bounds | Breaking if inputs existed | None | Major release |
Versioning is the escape hatch, not a substitute for compatibility. A URL major version or versioned media type lets old and new shapes coexist while clients migrate. Deprecate explicitly: mark the operation or field deprecated: true, publish a timeline, and send a Sunset header where supported. Within a major version, prefer additive changes, keep response objects open, and never reuse a field name for a different meaning. The contract diff in CI turns that policy into an enforced rule.
Lint rules, Spectral, and CI gates
Linting catches defects behavioral tests cannot see: an operation without an operationId, a response without a schema, an unused path parameter, an example that fails its schema, a $ref with siblings only one tool interprets. Spectral ships an OpenAPI ruleset and supports custom functions. Start with spectral:oas, raise important rules to error, and add a handful of house rules rather than a hundred aspirational ones. Useful rules: every operation documents a 4xx; every response except 204 and 304 declares content; every schema states its additionalProperties policy; every example validates. Treat warnings as failures with --fail-severity=warn, or the ruleset becomes advice everyone ignores.
Run the pipeline from cheapest to most expensive: lint, meta-schema validation, bundling, breaking diff, then behavioral tests against a preview. A breaking diff should require an explicit approval and a version bump, not a silent merge.
set -euo pipefail
# 1. Lint; warnings fail the build, not just errors
npx spectral lint openapi.yaml --ruleset .spectral.yaml --fail-severity=warn
# 2. Bundle external $refs into one deterministic file
npx @redocly/cli bundle openapi.yaml --output build/openapi.yaml
# 3. Fail when a documented guarantee is broken
oasdiff breaking openapi.baseline.yaml build/openapi.yaml --fail-on ERR
# 4. Replay generated requests against the preview deployment
schemathesis run build/openapi.yaml --base-url "$PREVIEW_URL" --checks all
# 5. Validate every example in the document against its schema
npx openapi-examples-validator build/openapi.yaml
Each stage removes noise. There is no point running a long property-based suite against a document that fails lint, or diffing one whose references resolve differently on every machine. Publish the bundled document as a release artifact, tag it with the service version, and keep the previous baseline for the next diff.
Examples, $ref resolution, and documentation drift
Examples are fixtures, not decoration. A request example that no longer validates misleads everyone who copies it, and a response example missing a required field teaches the wrong shape. Validate every example in CI and generate examples from real contract tests where possible. In OpenAPI 3.1, examples is ambiguous: inside a Schema Object it is the JSON Schema keyword, an array of raw values; inside a Media Type Object it is a map of Example Objects with summary and value. A tool that confuses the two validates the wrong thing.
$ref resolution deserves its own gate. Internal references are stable; external references depend on network access, file layout, and the base URI set by $id. A document that works on a laptop can fail in CI because a relative reference resolves against a different root. Bundle external references into one deterministic file, and resolve relative paths from the document's location rather than the process directory. In 3.0, keywords next to $ref were ignored; in 3.1 they are evaluated, so a document that relied on the old behavior can change meaning after an upgrade. Circular references are legal but make some generators loop, so test the resolved document.
Documentation drift is the slow version of the same problem: a wiki page, a README, and an OpenAPI file describe three different APIs after six months. Keep one source of truth and render every surface from it. Generate the reference and client snippets from the document, and fail CI when the committed copy differs. If a hand-written guide must exist, link it to the operation and review it in the pull request that changes the schema.
Common mistakes and approach comparison
The same mistakes recur. Testing only the happy path leaves error handling unverified. Ignoring additionalProperties lets typos pass and makes response schemas silently permissive. Treating a generated client as the contract mistakes a parser for a test. Letting documentation drift turns the document into fiction. Generating mocks from the same document under test is a tautology: mock and assertion share the same wrong assumption. Using nullable in 3.1, asserting only 200, skipping content-type checks, and validating only in staging all test the implementation rather than the promise.
| Approach | What it verifies | What it misses | Best use |
|---|---|---|---|
| Runtime schema validation | Live traffic matches the document | Logic, auth, idempotency | Gateways and writes |
| Provider conformance | Documented responses for every status | Consumer assumptions | Public API release gate |
| Consumer-driven contracts | One client's interactions | The rest of the surface | Internal dependencies |
| Generated client tests | The generator can parse the document | Whether the service honors it | SDK smoke tests |
| Lint and breaking diff | Structure and compatibility | Runtime behavior | Fast pre-test gate |
The comparison points to a layered strategy, not a single tool. Lint and diff protect structure, provider conformance protects the public interface, consumer contracts protect the dependencies that matter most, and runtime validation protects production from traffic the tests never imagined. Each layer is cheap relative to the incident it prevents.
Verification checklist for contract pipelines
Verify from the outside, in the order a change travels. Open the document in the OpenAPI viewer to confirm that paths, operations, and components resolve as intended. Paste a captured response into the JSON Schema validator to check the exact body before blaming the service. Replay the failing request in the HTTP request workbench to compare status, headers, and body with the contract. These three checks settle most disagreements before a full suite runs.
Treat the pipeline as passing only when every row holds:
| Check | How to test | Pass criteria |
|---|---|---|
| Document validity | Validate against the 3.1 meta-schema | No errors, dialect and version pinned |
| Lint policy | Run Spectral on the bundled document | Zero errors and warnings |
| Reference resolution | Bundle twice without network | Byte-identical output |
| Breaking diff | Compare with the released baseline | No breaking entries or an approved bump |
| Provider conformance | Run against the preview deployment | Every documented operation and status |
| Consumer contracts | Verify recorded interactions | All consumers pass before deploy |
| Examples | Validate every example | Zero invalid examples |
| Runtime sampling | Validate production responses | Violations alerted, never dropped |
A contract that is never diffed is a snapshot, and a snapshot that is never validated is a wish. The pipeline is deliberately boring: lint, bundle, diff, exercise, sample. Its value comes from running on every change, failing loudly, and keeping the released document as the next baseline. When a failure appears, ask which side of the contract changed; the diff usually answers, and the fix belongs there.
Frequently asked questions
Is OpenAPI 3.1 schema syntax identical to JSON Schema 2020-12?
The Schema Object in OpenAPI 3.1 is based on JSON Schema Draft 2020-12, with a small OpenAPI vocabulary layered on top for things like discriminator and xml. The document root can declare jsonSchemaDialect, and individual schemas can declare $schema, so validators must load the right dialect instead of assuming draft-07 or draft-04.
Provider tests pass, but a consumer still breaks; why?
Provider conformance only proves that responses match the published document. A consumer can depend on an undocumented field, a status code the document never lists, or a null that the schema allows but the client cannot parse. Consumer-driven contract tests record those expectations; run them against the provider before deployment, and treat undocumented behavior as unsupported.
How should a nullable field be written in OpenAPI 3.1?
Use a type array that includes null, such as type: [string, "null"]. The nullable keyword belonged to OpenAPI 3.0 and is not part of JSON Schema 2020-12, so validators that follow the dialect will ignore it. Decide separately whether the property may be absent, which required controls, and whether null is a meaningful value or merely an accident.
Should response schemas set additionalProperties to false?
Only when the response is genuinely closed and every added field is allowed to break clients. In JSON Schema, additionalProperties defaults to true, which lets typos pass silently; false makes additive changes breaking. Most public APIs document an extension policy, keep response schemas open, and make clients ignore unknown fields, while request schemas can be strict to reject malformed input.
Do generated client SDKs make contract tests unnecessary?
No. A generated client proves that the generator can read the document, not that the service honors it. Generated code can still send fields the server ignores, miss new required fields, or break on a null the schema permits. Contract tests exercise the running service and the real HTTP boundary; generated code is a convenience built on top of the contract.
JsonMind guides are written and reviewed by the engineering team. We check each guide against the relevant RFC or vendor documentation, link the primary sources, and update the guide when behavior changes.
Primary sources are linked at the end of each guide.