intermediate
OpenAPI contracts
Use OpenAPI as a reviewed contract for documentation, client generation, mocks, validation, and contract testing.
OpenAPI (Swagger) describes HTTP APIs as a machine-readable contract: paths, methods, parameters, request/response schemas, security schemes, and examples. Treat the spec as reviewed source of truth, not a post-hoc export.
paths:
/orders:
post:
operationId: createOrder
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/CreateOrder'
responses:
'201':
description: Created
headers:
Location:
schema: { type: string }
content:
application/json:
schema:
$ref: '#/components/schemas/Order'
Uses in the lifecycle:
- **Documentation** (Redoc, Swagger UI) with examples.
- **Client/server codegen** (types, fetch wrappers) — mind codegen limits.
- **Request validation** middleware from schemas.
- **Contract tests** and breaking-change CI (oasdiff, openapi-diff).
- **Mocks** for parallel frontend work.
On interviews: code-first vs design-first, how to prevent spec drift from implementation, and what belongs in components/schemas.
Common pitfalls: auto-generated specs missing constraints, no examples, versioning the whole monolith spec without ownership, and codegen treating optional as required incorrectly.
The trade-off is maintaining the spec versus integration pain — automate validation in CI to keep spec and code aligned.
Checklist:
- Single reviewed OpenAPI per API surface.
- Reusable components/schemas and securitySchemes.
- Examples on critical operations.
- CI fails on unintended breaking changes.