Documentation and contracts: OpenAPI, JSON Schema, contract testing
Swagger/OpenAPI in testing
OpenAPI is a machine-readable YAML or JSON format for describing an HTTP API: paths, methods, parameters, schemas and response codes. Swagger is the set of tools around it, such as Swagger UI, and the old name of the specification before version 3.0. QA reads the specification as requirements and logs a mismatch with the server as a defect once it is clear which side is right.
API · Contracts
The docs say 400 but the server returns 422. Who is right, and why is it a bug anyway?
Swagger UI says an invalid POST /v1/transfers returns 400. You send a negative amount and get 422. Then a page loads a transfer whose status is reversed, while the documentation lists three values. Nothing crashed, but a front end written from the specification does not know the fourth status. The specification and the server have drifted apart, and QA is often first to see it.
This lesson covers what OpenAPI and Swagger are, how to read a specification as requirements, and what to do when it lies.
What it is and why it is built this way
OpenAPI (OAS) is a YAML or JSON format for describing an HTTP API: paths, methods, parameters, body schemas, response codes, authorisation. Swagger is the name of the toolset around it (Swagger UI, Swagger Editor, Codegen) and the old name of the specification before version 3.0. So "Swagger documentation" in practice means "an OpenAPI file shown by Swagger UI".
The idea is that the contract is machine-readable. A description that lives only in Confluence is read and understood differently by every person. A file can automatically become an interactive page, a request collection, types, mocks and response checks.
One file, many consumers
Figure 1. The specification feeds people (Swagger UI, Postman) and automation (schemas, types, linter).
The skeleton of an OpenAPI 3.x document: info (name, version), servers, paths (operations) and components (shared schemas, parameters, security schemes referenced through $ref). Version 3.1 aligned schemas with JSON Schema 2020-12, so nullable was replaced by a type array:
The docs say 400, the server gives 422 and problem+json. A second request shows a data mismatch:
GET /v1/transfers/tr_77 HTTP/1.1
HTTP/1.1 200 OK
Content-Type: application/json
{ "id": "tr_77", "status": "reversed", "amount": 150 }
The schema has three status values, the response has a fourth. How to read it: two mismatches of different weight. The first concerns an error code; a client usually reacts to the 4xx class, so the risk is moderate. The second is more dangerous: a client handling only known values does not know what to show.
The specification and the server: two mismatches
Per specification
Request POST /v1/transfers, amount: -5
Response 400 Invalid request
GET tr_77 status: pending, completed or failed
A client and tests written from the file expect exactly this.
Actual
Request POST /v1/transfers, amount: -5
Response 422 Unprocessable Content, problem+json
GET tr_77 status: reversed, the schema has no fourth value
Two different mismatches: the error code and the enum value. A client will not handle the second one.
Figure 2. Two requests in the documentation and on the server: each line is compared separately.
What next. First find out which side is right: ask the endpoint author or check the requirements. If the server is right, the bug is in the documentation (fix the specification and tell the consumers). If the documentation is right, the bug is in the code. Both cases are reported, because clients are written from the specification. Do not quietly adjust the test to the real behaviour: that hides the problem.
Limits and alternatives
A specification can be incomplete. Often only the success response is described, with no errors, headers or pagination. That is a finding in itself (a linter catches it with a custom rule: Spectral's built-in ruleset only requires a 2xx or 3xx), but testing from such a specification means skipping everything undescribed.
Code-first and design-first. In the first approach the file is generated from code (annotations, the framework); it is more exact about syntax but may describe things nobody intended. In the second the specification is written before the code and it really is the requirement. This decides whom to ask to fix a mismatch.
Swagger UI "Try it out" suits manual exploration but is not regression: nothing is saved. For repeatable checks import the file into Postman (Import) or automate it in tests.
Other formats. GraphQL has a schema (SDL) and introspection, gRPC has .proto, asynchronous APIs are described with AsyncAPI. The principle is the same: a machine-readable contract.
Typical mistakes
Treating the specification as truth without checking. People write the file too, and it goes stale. Consequence: tests are green against an outdated description while clients break.
Not reporting a mismatch because "it is only documentation". Front ends and partner integrations are written from it.
Checking only the success responses from the documentation. 4xx codes and their format are part of the contract too.
Mixing up required and nullable. A field can be required and still be null, or optional and not arrive at all. These are different cases and the specification must tell them apart.
Check yourself
The specification says an invalid request gives 400. The server returns 422. What is the next step?
Answer
Find out which side is right and report a bug in the right place: in the code if the rules describe 400, or in the documentation if 422 was intended. The test is not quietly adjusted to the real behaviour.
What is the difference between Swagger and OpenAPI?
Answer
OpenAPI is the specification (the format for describing an API). Swagger is the toolset around it, and also the old name of the specification before version 3.0.
Related lessons: “OpenAPI as a source of tests”, “Schema validation in code: ajv and zod”, “Error format and service response headers”.
In an interview.Junior: OpenAPI describes endpoints, parameters, schemas and response codes, and Swagger UI gives an interactive page. I can import the specification into Postman, and a mismatch between it and reality I report as a bug. Middle/Senior: The specification is a machine-readable contract: I take schemas for validation, types and collections from it. Before trusting it I check whether it is code-first or design-first, which OpenAPI version it is (3.0 or 3.1, since null and schemas differ) and whether errors are described. A mismatch between the file and the server is always a defect, I only need to establish which side it belongs to.
OpenAPI as a source of tests
A test should read the OpenAPI specification rather than a pasted copy of it, so there are not two sources of truth. From the specification you take types for compilation, negative cases from required, schemas for validating responses, a linter and version comparison for breaking changes. Of these, only schema validation checks a real response, and the specification describes shape rather than business rules, so functional tests are still needed.
API · Contracts
The schema in the test was copied by hand and the spec changed. How can the test notice by itself?
The tests hold a copy of the transfer schema made six months ago. Since then the specification added a field and changed an enum, and the tests stay green because they check a stale copy. This is the classic "two sources of truth" problem. The fix: a test reads the specification, not its imprint.
The lesson covers what you can take from OpenAPI for automated tests: schemas, types, negative cases, a linter and version comparison.
How it works: the specification as raw material
The specification already holds what a test wants to know: which fields are required (required), which types and bounds apply, which codes an operation returns, which values are allowed. Instead of duplicating that in a test, you can read the file and derive checks from it. Then when the contract changes, everything changes at once: a test or a new version produces an error or forces a rebuild.
Four ways to use it (the example below takes another order: types and negative cases first, then the linter and version diff; schema validation is covered in the next lesson):
What the specification gives automated tests in CI
Figure 1. Four layers of checks fed by one file. The third is closest to the real behaviour of the server.
The first layer works on the file itself and knows nothing about the server, the fourth compares two files. Only the third checks that a response really matches the schema, and that is what finds drift between code and documentation.
Example: from a schema copy to a source of truth
The bad variant. The test checks the structure by hand:
const body = await res.json();
expect(body.id).toBeDefined();
expect(body.amount).toBeDefined(); // passes for "150" and for null
Such a test does not know that amount must be a number or that status must belong to a list. If the field disappears from the contract, the test stays the same.
Step one: types from the specification. A generator takes the file and creates TypeScript interfaces:
importtype { components } from'./api';
typeTransfer = components['schemas']['Transfer'];
test('created transfer is pending', async ({ request }) => {
const res = await request.post('/v1/transfers', { data: VALID });
const body = (await res.json()) asTransfer;
const expected: Transfer['status'] = 'pending'; // 'pendng' will not compileexpect(body.status).toBe(expected);
});
Now removing or renaming a field in the specification breaks the test build after regeneration instead of being caught at run time. Types work at compile time and do not replace checking the response, because res.json() still returns whatever the server sent.
Step two: negative cases from the request schema. Fields in required give a ready list of "without field X the request is rejected":
import { readFileSync } from'node:fs';
import { parse } from'yaml';
const spec = parse(readFileSync('openapi.yaml', 'utf8'));
const req = spec.components.schemas.TransferRequest;
const VALID = { toAccount: 'UA21...', amount: 150, currency: 'UAH' };
for (const field of req.required as string[]) {
test('missing ' + field + ' is rejected', async ({ request }) => {
const data: Record<string, unknown> = { ...VALID };
delete data[field];
const res = await request.post('/v1/transfers', { data });
expect(res.status()).toBe(400);
});
}
Add a required field to the specification and the case appears on its own. The expected code here comes from the documentation (400). The server from the previous lesson returns 422, and this test is what exposes the mismatch.
Steps three and four live in CI. A linter finds incomplete descriptions, and a comparison tool (oasdiff, for example) shows whether a PR contains a breaking change against the main branch:
A specification does not guarantee business logic. The schema says amount is a number, not that the right sum was debited. Functional tests are needed for that.
Quality depends on the file. If the specification is generated from code and describes no errors, no negative cases come out of it. Then a linter rule "every operation has a 4xx" is more useful than anything else.
Generating tests from scratch. Tools exist that produce fuzzing from OpenAPI (Schemathesis, for example). They quickly find a 500 on strange input, but they are not a substitute for thought-out test design: they do not know what is right for the business.
A mock server from the specification lets the front end work before the back end is ready. It answers with the examples in the specification, so it goes stale together with it.
Typical mistakes
Copying the schema into the test. A month later the copy drifts from the original and the test stops meaning anything.
Generating types but not regenerating them in CI. Then they sit in the repository as one more copy.
Validating only success responses. Errors have schemas too, and that is where drift is most common.
Ignoring linter warnings. A missing 4xx description or a field without a type or required is not cosmetic, it is a hole in the contract.
Check yourself
A required field currency was added to the request in the specification. Which automated tests should react without manual edits?
Answer
Negative cases generated from required (a "without currency" case appears) and the types, if regenerated: code that builds a request without the new field stops compiling.
Why do types from the specification not replace validating a response against a schema?
Answer
Types work at compile time and only describe expectations. res.json() returns what really arrived, so only a schema check at run time verifies the real response.
Related lessons: “Swagger/OpenAPI in testing”, “Schema validation in code: ajv and zod”, “Consumer-driven contracts and breaking changes”.
In an interview.Junior: From the specification I take schemas to check responses and I can generate types. That way the test does not duplicate the description by hand. Middle/Senior: I keep one file as the source of truth: a linter in CI, types, schemas in tests and version comparison for breaking changes. I generate negative cases from required and bounds, and I do not treat the specification as a replacement for functional tests, because it describes shape, not business rules.
Schema validation in code: ajv and zod
Responses are checked against a schema in code: ajv uses standard JSON Schema, while zod defines the schema in TypeScript and infers its type. Such a check catches wrong types that a field-exists check misses, and shows the path to the violation. Responses that must be exact need strict mode (additionalProperties: false or z.strictObject), because extra fields otherwise pass, and a schema checks shape, not values.
API · Contracts
The test checks that amount exists and lets the string "150" through. What should check the structure?
The response of /v1/transfers/tr_91 contains "amount": "150" (a string), and the test is expect(body.amount).toBeDefined(). The test is green. A month later the mobile app crashes because it adds a number to the amount. "The field exists" said nothing about type, and a schema closes that gap.
The lesson covers two tools used to validate responses in TypeScript: ajv (JSON Schema) and zod (schemas as code), how they differ and where the blind spot remains.
How it works
A schema describes the shape of data: which fields, of which types, which are required, what is allowed. A validator takes a response and a schema and returns "yes" or a list of violations with paths to the problem fields. The test then does not check fields one by one but demands "the response matches the contract". The error shows exactly what is wrong.
ajv reads standard JSON Schema. If the schema already exists in OpenAPI (3.1, where a schema is JSON Schema 2020-12), it does not have to be rewritten. zod works the other way round: the schema is written in TypeScript and the type is derived from it (z.infer). Then schema and type cannot drift, but there is no separate contract file.
ajv or zod
ajv
A JSON Schema or OpenAPI file already exists. The schema is not duplicated, it is taken from the specification. You need ajv-formats for format and careful strict settings.
zod
There is no specification or the contract is kept in code. Schema and type are in one place, error messages are readable. An OpenAPI file cannot be obtained from it.
Figure 1. Both options are legitimate: the choice depends on where the contract lives.
Example: from "the field exists" to a schema
A weak check:
const body = await res.json();
expect(body.id).toBeDefined();
expect(body.amount).toBeDefined(); // passes for "150" and for null
It lets through a string instead of a number, and null. The same with ajv, the schema taken from the specification:
What matters here. Ajv2020 is needed because OpenAPI 3.1 schemas follow JSON Schema 2020-12. strict: false allows OpenAPI-only keywords such as example or discriminator, which ajv would otherwise reject. The $ref to components works because we pass them in the schema root. Specifications 3.0 use a different dialect (nullable, boolean exclusiveMinimum), so this code does not fit them without converting the schemas.
Where in the body: the path to the field in the response, here amount. For nested fields the path is longer.
Which rule: the place in the schema that was violated. Look it up in the specification.
What is wrong: the schema requires a number (params), but the string "150" arrived.
What to do
This is a contract bug, not a test bug: report it against the endpoint instead of widening the schema to ["number", "string"]. Putting the array into the test message (JSON.stringify(validateTransfer.errors)) gives this breakdown at once, without a debugger.
Figure 2. The validateTransfer.errors array for a response with "amount": "150" (ajv 8 error format).
The same in zod, when schemas live in code:
import { z } from'zod';
constTransfer = z.strictObject({
id: z.string(),
status: z.enum(['pending', 'completed', 'failed']),
amount: z.number().positive(),
note: z.string().nullable(), // may be null, must be present
memo: z.string().optional(), // may be absent
});
test('transfer matches the contract', async ({ request }) => {
const body = await (await request.get('/v1/transfers/tr_91')).json();
const parsed = Transfer.safeParse(body);
expect(parsed.success, JSON.stringify(parsed.error?.issues)).toBe(true);
});
Note strictObject (.strict() works the same): by default zod silently drops unknown keys, and the test would let an extra field such as cardNumber through. In ajv extra fields pass too, unless the schema has additionalProperties: false:
Transfer:
type: object
required: [id, status, amount]
properties:
id: { type: string }
status: { type: string }
amount: { type: number }
# additionalProperties is true by default: an extra "cardNumber" passes
This is a common source of vulnerabilities: an extra field in a response can be a data leak. So for responses that must be exact, enable the strict check.
Limits and alternatives
A schema checks shape, not content.amount: 150 passes even if 200 was expected. Values are checked separately.
format is not always enforced. In JSON Schema 2020-12 it is an annotation by default; ajv checks formats only with ajv-formats.
Required, optional and null are three different cases: required in a schema, an absent field and the value null. In zod these are .optional() and .nullable(), in OpenAPI 3.1 (JSON Schema 2020-12) they are required and type: [string, 'null'].
Postman has pm.response.to.have.jsonSchema(schema) inside a script, Playwright and Cypress have no built-in schema validation, so you plug in ajv or zod as above, and REST Assured has the json-schema-validator module (matchesJsonSchemaInClasspath) built on a separate Java library.
Typical mistakes
Validating only the success response. Error bodies need a schema too, otherwise the error format breaks easily.
One big expect(parsed.success) without a message. The test fails with "expected true" and the cause is hunted by hand. Pass JSON.stringify(parsed.error?.issues) or validate.errors.
Not enabling strict mode for responses. Extra fields pass silently.
Copying the schema into zod when OpenAPI already exists. Two sources of truth again.
Check yourself
The server started returning an extra field internalScore. The schema has no additionalProperties: false (or zod without strict). Is the test green or red?
Answer
Green: extra keys are not forbidden by the schema (zod even drops them). To notice the extra field you need strict mode: additionalProperties: false or z.strictObject.
How does .optional() differ from .nullable() in zod?
Answer
.optional() allows the field to be absent altogether, .nullable() allows the value null but the field must be present. They are different cases and a contract must tell them apart.
Related lessons: “OpenAPI as a source of tests”, “Request and response body: types, null and empty values”, “Consumer-driven contracts and breaking changes”.
In an interview.Junior: In tests I validate the response with a schema: ajv for JSON Schema or zod when the schema is in TypeScript. It beats checking fields one by one because it catches wrong types. Middle/Senior: With OpenAPI 3.1 I take schemas from it through ajv (Ajv2020 and ajv-formats) so the contract is not duplicated. I enable strict checks for extra fields, tell required, optional and nullable apart and put the full validation error in the message. A schema does not replace value checks, so I write business assertions separately.
Consumer-driven contracts and breaking changes
In consumer-driven contracts (Pact) the consumer describes the requests it makes and the response fields it uses, and the provider replays them in its CI. Removing or renaming a used field, changing a type, a new required request field, or changing an error code or format is a breaking change that fails before deploy. A new enum value can also break a client with no default branch.
API · Contracts
The back end renamed a field and the front end learned about it from production. How to catch it before deploy?
The provider team changed amount to sum because it looked "cleaner". Their tests are green, they wanted it. The front end, which reads amount, shows "NaN" in production. Two teams, each with its own tests, and nobody watches that they agree. Contract testing exists for that.
The lesson covers consumer-driven contracts (Pact), what breaks clients and what does not, and why a new enum value is not always safe.
How it works and why
Integration tests between two services are slow and brittle: both must run, plus all their dependencies. Contract testing splits the check into two parts, each run in isolation. In the consumer-driven approach (Pact) the consumer produces the contract: its test describes which requests the client makes and which response fields it actually uses. The requests go to a mock provider, and Pact records what happened in a pact file (JSON).
The file is then published to a Pact Broker (or PactFlow), and the provider in its own CI replays the recorded requests against the real service and checks that the responses fit. The result goes back to the broker, and a team can ask can-i-deploy: is this version compatible with all consumers in the target environment.
The Pact flow
Figure 1. The consumer sets expectations, the provider fulfils them, the broker stores the results. No shared test infrastructure.
The key idea: the contract contains only what the consumer really uses. So the provider can change everything else without fear of breaking someone. And the other way round: when it removes a field someone uses, its CI fails before deploy, naming the consumer and the exact request.
Example: a consumer test and a breaking change
A consumer test (Pact JS, V3) describes one interaction and at the same time checks the client code:
Here like says "the type matters, not the exact value", and regex sets allowed values with an example. The given block is the "provider state": before replaying the request the provider must prepare the transfer tr_91 (on its side this is a state handler). Thanks to this the pact file does not depend on database contents.
What counts as a breaking change. The yardstick: will a consumer written against the previous contract break.
Change
Type
Add a new optional response field
Non-breaking
Add a new endpoint
Non-breaking
Add an optional request parameter
Non-breaking
Remove or rename a response field
Breaking
Change a field type, for example number to string
Breaking
Make an optional request field required
Breaking
Change a status code or the error format
Breaking
A nuance: a new enum value is formally an addition but can break a client that knows only the old values:
So for an enum the contract records what the consumer can handle, and in practice teams agree on a "tolerant reader": the client must react safely to an unknown value instead of crashing.
Limits and alternatives
Pact does not replace the provider's functional tests. It checks that the response has the shape a consumer expects, not that the service calculates correctly.
A consumer must exist and write contracts. For a public API with unknown clients consumer-driven does not fit; a specification, version comparison (oasdiff) and API versioning work there.
Bi-directional contracts in PactFlow match the consumer pact against the provider's specification, so the provider does not have to replay requests. It is cheaper but checks only what could be compared with the schema.
Versioning is still needed: a breaking change without a new API version (/v2, a separate header or a compatibility period) breaks those the contracts did not cover.
Typical mistakes
Describing the whole response in the pact instead of the fields the consumer needs. The contract becomes brittle and the provider cannot change anything without a red build.
Hard values instead of matchers. The test fails on a different id or date, not on a real violation.
Not publishing provider verification results. Without them can-i-deploy has no data.
Treating an enum as safe to extend. A new value breaks a consumer with no default branch.
Check yourself
The provider removed a field no consumer uses. Will Pact fail?
Answer
No: the pact file holds only what consumers actually read. That is both the advantage (the provider is free to change) and the limit: a field read by an unknown client is not protected by contracts.
Why can adding a value to a response enum be a breaking change although it is "only an addition"?
Answer
A client that handles a list of values with no default branch receives an unknown value and breaks or shows an empty state. So a consumer must handle unknown values safely and a provider must announce enum extensions.
Related lessons: “Swagger/OpenAPI in testing”, “OpenAPI as a source of tests”, “Contract and performance: breaking change, 200 with an error, N+1”, “Filtering, sorting and versioning”.
In an interview.Junior: Contract testing checks that two services understand each other without bringing up the whole system. The consumer describes what it expects, the provider verifies it. Removing or renaming a field or changing a type is a breaking change, adding a new field usually is not. Middle/Senior: In Pact a consumer test generates a pact file, it is published to a broker, the provider replays the requests in CI and can-i-deploy gives the release go-ahead. The contract holds only the fields the consumer needs and matchers, not exact values. It complements functional tests and versioning rather than replacing them, and for public APIs with unknown consumers I work from the specification and version comparison.