1.OpenAPI, schema generation, and request/response schemas
OpenAPI is a machine-readable description of an HTTP API — every path, every method, the shape of each request body, the shape of each response, and the authentication each endpoint expects — written as a single JSON or YAML document. Because it is machine-readable, one file drives several things at once: interactive documentation, generated client libraries in a dozen languages, request validation in a gateway, and contract tests. In DRF you do not write it by hand. A generator walks your URLconf, reads each view's serializer, and produces the document — which is why the schema is only as accurate as the serializers and the type hints it was derived from.
Key features
- OpenAPI 3.x describes paths, operations, parameters, request bodies, responses, security schemes, and reusable components in one JSON/YAML document
- DRF ships basic OpenAPI generation (`generateschema`, `rest_framework.schemas.openapi.AutoSchema`), and its own documentation recommends `drf-spectacular` for real use
- Request and response schemas come from the serializer, so a serializer without declared types produces a schema with unknown types
- A view returning a hand-built `Response({...})` has no serializer to read, so its response body is absent from the schema unless annotated
- Error responses are invisible by default — the generator does not know which exceptions a view raises, so 400/403/409 shapes must be declared
- Generate the document in CI and commit it: diffing it turns a breaking change into a reviewable line in a pull request
What the generator reads, and what it cannot see
- 1 · The generator walks the URLconf — Every routed view becomes a path and a set of operations. Nothing here is written by hand, so nothing here can drift.
- 2 · Serializers become schemas — Field types, required-ness, choices, and read-only flags all transfer. A vague serializer produces a vague schema.
- 3 · You annotate what it cannot infer — Custom actions, error shapes, and dynamic serializer selection are Python control flow — invisible to a static pass until declared.
- 4 · One document, four consumers — Swagger UI and ReDoc render it, client generators compile it, a gateway validates against it, and CI diffs it to catch breaking changes.
Command
REST_FRAMEWORK = {"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema"}
SPECTACULAR_SETTINGS = {"TITLE": "Orders API", "VERSION": "1.0.0"}OpenAPI is a machine-readable description of the API, and in DRF it is generated from your URLconf and serializers rather than written. Generation makes it a correctness tool: it describes what you shipped, and a gap in the document is a gap in the code. But it can only read what is declarative — custom `@action` responses, dynamic serializer selection, and every error shape are invisible until annotated with `@extend_schema`. Commit the generated file and diff it in CI, so a breaking change becomes a line someone has to approve.