8. OpenAPI, schemas & contract testing
API Testing · 44 pages source format
OpenAPI (Swagger) describes API contracts. Validate responses against schemas — catch drift before production.
What you'll learn
- OpenAPI structure
- JSON Schema validation
- Contract vs E2E
- Consumer-driven contracts intro
Read an OpenAPI spec
paths, components/schemas, responses. Petstore is the hello world.
Do this now
Open swagger.io petstore spec. Map 3 endpoints to tests you already wrote.
JSON Schema validation
Assert response matches schema — required fields, types, enums. jsonschema library (Python) or ajv (JS).
import jsonschema
schema = {"type": "object", "required": ["id", "email"], "properties": {"id": {"type": "number"}, "email": {"type": "string"}}}
jsonschema.validate(instance=response.json(), schema=schema)Do this now
Validate GET /users/1 response against a hand-written JSON Schema.
Contract testing concept
Consumer defines expected shape. Provider verifies. Pact and similar tools — know the idea for interviews.
Do this now
Write CONTRACTS.md: what your tests guarantee about API shape.
OpenAPI diff awareness
Breaking changes: removed fields, type changes, new required fields. CI can diff specs on PR.
Do this now
Read about openapi-diff or oasdiff. Note 3 breaking change examples.