Skip to content

Schemas & OpenAPI

API schemas are a useful tool that allow for a range of use cases, including generating reference documentation, or driving dynamic client libraries that can interact with your API.

Django REST Framework natively supports OpenAPI (formerly Swagger), which is a widely adopted standard for describing APIs.

Generating an OpenAPI Schema

DRF provides a built-in schema generator.

Using the Management Command

You can generate a static schema file using the generateschema management command:

bash
python manage.py generateschema --file openapi-schema.yml

You can specify the format explicitly:

bash
python manage.py generateschema > schema.json --format json

Exposing a Schema Endpoint

If you want to serve the schema dynamically over HTTP, DRF provides the get_schema_view shortcut.

python
from django.urls import path
from rest_framework.schemas import get_schema_view

urlpatterns = [
    # ... your other url patterns
    path('openapi/', get_schema_view(
        title="Your Project",
        description="API for all things …",
        version="1.0.0"
    ), name='openapi-schema'),
]

When a user visits /openapi/, they will receive a YAML (or JSON, based on negotiation) representation of the OpenAPI schema.

Customizing Schema Generation

You can customize how individual views generate their schema operations by setting the schema attribute on a view to an instance of AutoSchema (or a subclass).

python
from rest_framework.views import APIView
from rest_framework.schemas.openapi import AutoSchema

class CustomView(APIView):
    schema = AutoSchema(
        tags=['Users'],
        operation_id_base='CustomUser',
    )

To entirely exclude a view from the schema, you can set its schema to None:

python
class ExcludedView(APIView):
    schema = None

Third-Party Packages

While DRF includes basic OpenAPI support, you may want to use third-party packages for a fully-featured Swagger UI or ReDoc interface.

A popular choice is drf-spectacular:

  1. Install it: pip install drf-spectacular
  2. Add to INSTALLED_APPS: 'drf_spectacular'
  3. Add to settings:
python
REST_FRAMEWORK = {
    'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}

Then you can use it to serve Swagger UI:

python
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView

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