How to Document an API with OpenAPI
Author an OpenAPI 3.1 spec with paths and reusable schemas, serve interactive Swagger or Redoc docs, enforce the schema with request validation, and generate a typed client from the spec.
What and why
OpenAPI is the standard, machine-readable description of a REST API. From one spec you get interactive documentation, request validation, server stubs, and typed client SDKs. It becomes the contract between API producers and consumers.
Prerequisites
- A working REST API.
- Basic YAML familiarity.
- A Node or Python toolchain.
Steps
1. Choose a spec-first or code-first approach
Spec-first authors the YAML by hand and generates code from it, keeping the contract central. Code-first generates the spec from annotations or types (FastAPI does this automatically). Either works; pick one and keep it the source of truth.
2. Describe paths and operations
openapi: 3.1.0
info: { title: Articles API, version: 1.0.0 }
paths:
/v1/articles/{id}:
get:
summary: Get an article
parameters:
- name: id
in: path
required: true
schema: { type: string }
responses:
'200':
description: OK
content:
application/json:
schema: { $ref: '#/components/schemas/Article' }
'404': { description: Not found }
3. Define reusable schemas
components:
schemas:
Article:
type: object
required: [id, title]
properties:
id: { type: string }
title: { type: string }
Referencing $ref keeps the spec DRY and consistent.
4. Serve interactive docs
Render the spec with Swagger UI or Redoc:
const swaggerUi = require('swagger-ui-express');
const spec = require('./openapi.json');
app.use('/docs', swaggerUi.serve, swaggerUi.setup(spec));
FastAPI serves /docs automatically from its generated spec.
5. Validate requests against the spec
Use middleware such as express-openapi-validator to reject requests and responses that violate the schema, so the spec is enforced, not just documentation.
6. Generate client code
Generate a typed client from the spec:
npx @openapitools/openapi-generator-cli generate -i openapi.yaml -g typescript-axios -o ./client
Verification
- The spec passes a linter such as Spectral.
- The docs page renders and the try-it feature works.
- A request violating the schema is rejected.
- A generated client compiles and calls the API.
Next Steps
Lint the spec in CI, publish it for consumers, add examples to improve the docs, and detect breaking changes between versions with a diff tool before release.
Prerequisites
- A working REST API
- Basic YAML knowledge
- Node or Python toolchain
Steps
- 1Choose a spec-first or code-first approach
- 2Describe paths and operations
- 3Define reusable schemas
- 4Serve interactive docs
- 5Validate requests against the spec
- 6Generate client code