How to generate an OpenAPI spec in Django Rest Framework?
There are two ways to generate an OpenAPI spec in Django Rest Framework: CLI command and API endpoint.
How it works
The actual spec is produced by an underlying generator class, called by either a CLI command or an API endpoint. Long story short: generator collects the project endpoints from settings.ROOT_URLCONF and compiles a spec for each of them. To be able to generate a spec you need to install a pyyaml package first:
pip install pyyamlCLI command
To generate a spec via CLI command, call a generateschema management command:
python manage.py generateschemaThis command outputs an OpenAPI spec in YAML format by default.
API endpoint
To generate a spec via API endpoint, add this code to urls.py:
from django.urls import path
from rest_framework.schemas import get_schema_view
urlpatterns = [
path('schema/', get_schema_view())
...
]Now, when you call GET /schema/, DRF will respond with an OpenAPI spec.