Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Versioning and Documentation

OpenAPI Schema Generation for DRF with drf-spectacular

Generate an OpenAPI 3 schema for a Django REST Framework API with drf-spectacular: settings, extend_schema, parameters, examples, Swagger UI, Redoc and keeping the schema accurate in CI.

An API without documentation is a guessing game. Hand-written docs drift out of date the moment someone changes a serializer. The modern fix is to generate the documentation from the code, using the OpenAPI standard: a JSON or YAML file that describes every path, parameter, request body, response and error of your API. From one OpenAPI file you can get interactive docs (Swagger UI, Redoc), client libraries in many languages, mock servers and contract tests.

DRF used to include its own schema generator, but it is deprecated and no longer developed, and the community package drf-spectacular is the standard replacement. It reads your views, serializers, filters and pagination classes and produces OpenAPI 3.

Setup

Install it (pip install drf-spectacular), add it to INSTALLED_APPS and make it DRF's schema class:

Python
# settings.py (read-only)
INSTALLED_APPS = [..., "rest_framework", "drf_spectacular"]

REST_FRAMEWORK = {
    "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}

SPECTACULAR_SETTINGS = {
    "TITLE": "Bookstore API",
    "DESCRIPTION": "Browse and manage books.",
    "VERSION": "1.0.0",
    "SERVE_INCLUDE_SCHEMA": False,   # keep the schema endpoint out of its own schema
}

Then add the views:

Python
# urls.py (read-only)
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView, SpectacularRedocView

urlpatterns = [
    path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
    path("api/docs/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui"),
    path("api/redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc"),
]

To write the schema to a file (for CI or client generation), run python manage.py spectacular --file schema.yml.

From code to docs

Your DRF code Views, serializers, filters
OpenAPI file One YAML or JSON description
Interactive docs Swagger UI and Redoc
Clients and tests SDKs, mocks, contract checks

Change the code, regenerate, docs stay true

1 / 2

What you get for free

Without any extra annotations the generator already understands ModelViewSets, generic views, routers, serializers (field types, required, read_only, choices, nested serializers), pagination and django-filter parameters. Here it is on a tiny catalog API. The script asks the schema endpoint for JSON and prints a summary.

Python Generate a schema for a ModelViewSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
Loading attrs, jsonschema, jsonschema_specifications, pyrsistent, pyyaml, referencing, rpds-py, six, typing-extensions
Loaded attrs, jsonschema, jsonschema_specifications, pyrsistent, pyyaml, referencing, rpds-py, six, typing-extensions
OpenAPI 3.0.3 | Bookstore API 1.0.0
GET    /api/books/          books_list
POST   /api/books/          books_create
GET    /api/books/{id}/     books_retrieve
PUT    /api/books/{id}/     books_update
PATCH  /api/books/{id}/     books_partial_update
DELETE /api/books/{id}/     books_destroy
required: ['author', 'genre', 'id', 'price', 'title', 'year']
  id       integer  (read only)
  title    string  
  author   string  
  genre    string  
  price    string decimal 
  year     integer int64 
  in_stock boolean  
components: ['Book', 'PatchedBook']

Spectacular created one reusable Book component for responses and requests, marked id as read-only, and generated an operation ID for every route. Tools that build SDKs use those operation IDs as function names, so keep views named sensibly.

Improving the schema with @extend_schema

The generator works from static information. For a plain APIView, or for a response that is not made by a serializer, it cannot know what you return. The extend_schema decorator tells it. You can set a summary, description, tags, the request body, the responses per status code, query parameters and examples.

Use it on a view method (get, post) or on a viewset action. On a whole class, use @extend_schema_view to annotate several actions at once.

Python extend_schema: request, responses, parameters, examples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
{
 "summary": "Check a coupon code",
 "tags": [
  "coupons"
 ],
 "parameters": [
  {
   "in": "query",
   "name": "lang",
   "schema": {
    "type": "string",
    "enum": [
     "de",
     "en"
    ]
   },
   "description": "Message language"
  }
 ]
}
responses: {'200': {'$ref': '#/components/schemas/CouponOut'}, '400': {'type': 'object', 'additionalProperties': {}}}
request example: {'code': 'SPRING10', 'order_total': '80.00'}

A few related tools are worth knowing:

Need Tool
Different serializers per action the schema follows get_serializer_class() for viewsets
Method fields (SerializerMethodField) annotate the method with @extend_schema_field(OpenApiTypes.STR)
Hide an endpoint @extend_schema(exclude=True)
Several response shapes OpenApiResponse(response=..., description=...) or PolymorphicProxySerializer
Group operations in the docs tags (or a custom SCHEMA_PATH_PREFIX)
Mark deprecated @extend_schema(deprecated=True)

Serving the docs

The Swagger UI and Redoc views return a small HTML page that loads its JavaScript from a CDN and fetches your schema. Swagger UI also has a "Try it out" button that sends real requests and can authorize with a token, so developers can explore the API in the browser.

Python The schema in YAML, plus the Swagger UI and Redoc pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
--- schema as YAML (first lines) ---
openapi: 3.0.3
info:
  title: Notes API
  version: 0.3.0
  description: Tiny API
paths:
  /api/health/:
    get:
      operationId: health_retrieve
      description: Return the service status.
      tags:
      - health
      security:
      - cookieAuth: []
/api/docs/ 200 text/html | mentions the schema URL: True
/api/redoc/ 200 text/html | mentions the schema URL: True

Two details: the default response is YAML (clients can ask for JSON with ?format=json or an Accept header), and the HTML pages need a network connection in the browser because the viewer scripts come from a CDN. For offline or locked-down environments install drf-spectacular-sidecar and set SWAGGER_UI_DIST = "SIDECAR" so the files are served from your own server.

Keep the schema honest

A generated schema is only useful if it is correct and stays correct.

  • Read the warnings. manage.py spectacular --validate --fail-on-warn reports views whose serializer it cannot guess, duplicate component names and untyped method fields. Fix each with extend_schema or extend_schema_field.
  • Check it in CI. Generate the schema on every pull request, commit it as schema.yml, and fail the build if the committed file differs. Then API changes become visible in code review, and breaking changes can be caught with a diff tool.
  • Protect the docs endpoint if the API is private. SpectacularAPIView uses the default permission classes, so set SERVE_PERMISSIONS in SPECTACULAR_SETTINGS (for example staff only) when the docs should not be public.
  • Describe authentication. Spectacular detects token, session and JWT schemes from your authentication classes and adds them to securitySchemes, which makes Swagger UI's Authorize button work (see JWT authentication).
  • Version-aware docs. With API versioning enabled, spectacular can produce a separate schema per version (use SCHEMA_COERCE_PATH_PK_SUFFIX and the ?v= parameter, or the SCHEMA_PATH_PREFIX setting).

Generating client code

Because OpenAPI is a standard, tools can read your schema.yml and write typed clients: openapi-generator or openapi-typescript for JavaScript/TypeScript front ends, and similar generators for Swift, Kotlin or Python. This is why stable operation IDs and accurate response schemas matter: they become the names and types in the generated code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does OpenAPI describe?

    OpenAPI is a machine-readable description of an HTTP API that tools can render, test and generate clients from.
  2. 2. When do you need @extend_schema?

    Static analysis cannot see what an APIView returns. extend_schema states the request, responses and parameters explicitly.
  3. 3. How do you hide one endpoint from the generated docs?

    extend_schema(exclude=True) removes the operation from the schema.
  4. 4. Why commit the generated schema.yml and compare it in CI?

    A committed schema turns API changes into visible diffs.

Summary

  • Generate docs from code with OpenAPI; drf-spectacular is the standard generator for DRF (the built-in generator is deprecated).
  • Install the app, set DEFAULT_SCHEMA_CLASS, fill SPECTACULAR_SETTINGS, and add the schema, Swagger UI and Redoc views.
  • Viewsets, serializers, pagination and filters are documented automatically; use extend_schema, extend_schema_field and OpenApiParameter for the rest.
  • Validate with manage.py spectacular --validate, commit the schema, and restrict the docs endpoint when the API is private.
  • OpenAPI also powers generated client libraries and contract tests.

Next: Customizing the Browsable API and Docs