Django API Documentation with drf-spectacular: Clean, OpenAPI 3-Compliant Docs for DRF
Last updated 4 months ago | 469 views 75 5

Introduction: Why Use drf-spectacular
for API Documentation?
Good API documentation is not a luxury—it's a necessity. Whether you're developing APIs for internal tools or exposing them to third-party consumers, your documentation:
-
Saves time debugging API integrations
-
Provides an excellent onboarding experience
-
Boosts developer productivity
-
Improves collaboration between frontend and backend teams
While Django REST Framework (DRF) includes a basic browsable API, it doesn’t support OpenAPI 3 out of the box. That’s where drf-spectacular
shines.
✅
drf-spectacular
is a robust, OpenAPI 3-compliant schema generator for Django REST Framework with tight integration, excellent customization, and support for ReDoc and Swagger UI.
⚙️ Setting Up drf-spectacular in Django
Let’s walk through the installation and setup to start documenting your APIs.
✅ Step 1: Install drf-spectacular
Use pip to install:
pip install drf-spectacular
✅ Step 2: Update Django Settings
In your settings.py
, add the schema class and settings:
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
SPECTACULAR_SETTINGS = {
'TITLE': 'My Awesome API',
'DESCRIPTION': 'Detailed documentation of my API with drf-spectacular',
'VERSION': '1.0.0',
}
✅ Step 3: Add Schema View to URLs
Add the schema view to your urls.py
:
from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView
from django.urls import path
urlpatterns = [
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
# Optional Swagger UI
path('api/docs/swagger/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
# Optional ReDoc UI
path('api/docs/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
]
You now have 3 different ways to access your documentation:
Raw OpenAPI schema:
/api/schema/
Swagger UI:
/api/docs/swagger/
ReDoc UI:
/api/docs/redoc/
Documenting Endpoints with drf-spectacular
✅ 1. Use @extend_schema
for Custom Descriptions
from drf_spectacular.utils import extend_schema
from rest_framework.decorators import api_view
from rest_framework.response import Response
@extend_schema(
summary="Welcome endpoint",
description="Returns a welcome message",
responses={200: {"type": "object", "properties": {"message": {"type": "string"}}}},
)
@api_view(['GET'])
def welcome_view(request):
return Response({"message": "Welcome to the API!"})
✅ 2. Add Schema Metadata for ViewSets
from rest_framework import viewsets
from drf_spectacular.utils import extend_schema_view, extend_schema
from .models import Post
from .serializers import PostSerializer
@extend_schema_view(
list=extend_schema(summary="List all posts"),
retrieve=extend_schema(summary="Retrieve a specific post"),
)
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
Complete Example
views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from drf_spectacular.utils import extend_schema
@extend_schema(
summary="Greet user",
responses={200: {"type": "object", "properties": {"greeting": {"type": "string"}}}},
)
@api_view(["GET"])
def greet_user(request):
return Response({"greeting": "Hello from the API!"})
urls.py
from django.urls import path
from .views import greet_user
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView, SpectacularRedocView
urlpatterns = [
path("api/schema/", SpectacularAPIView.as_view(), name="schema"),
path("api/docs/swagger/", SpectacularSwaggerView.as_view(url_name="schema"), name="swagger-ui"),
path("api/docs/redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc"),
path("api/greet/", greet_user, name="greet-user"),
]
Tips & Common Pitfalls
✅ Best Practices
-
Always use
@extend_schema
to add summaries and parameter/response info -
Use
@extend_schema_view
to annotate entire ViewSets -
Organize schema settings using
SPECTACULAR_SETTINGS
insettings.py
-
Version your API schema for long-term maintainability
❌ Common Pitfalls
Problem | Solution |
---|---|
Schema doesn’t show expected output | Define response schemas explicitly with @extend_schema |
Parameters not appearing | Use OpenApiParameter inside @extend_schema |
Invalid view or path in docs | Ensure all paths use DRF-compatible views |
Error on schema load | Check for non-serializable response types |
ReDoc vs Swagger UI vs Raw Schema
Feature | Swagger UI | ReDoc | Raw OpenAPI JSON |
---|---|---|---|
UI | Interactive forms | Clean, readable UI | No UI |
Use Case | Testing endpoints | Read-only viewing | For machine integrations |
Endpoint URL | /swagger/ |
/redoc/ |
/schema/ |
✅ Conclusion: Let Your API Speak for Itself
With drf-spectacular
, documenting your Django REST APIs is:
-
Simple and flexible
-
Fully OpenAPI 3 compliant
-
Easy to integrate with Swagger UI and ReDoc
A well-documented API increases your project's credibility and speeds up development across teams. Take time to document properly and automate it into your development workflow.
Final Takeaways
-
Use
drf-spectacular
for OpenAPI 3 support in Django -
Customize each view with
@extend_schema
-
Serve both Swagger and ReDoc UIs for better dev experience
-
Keep your schema clean, DRY, and versioned