Django REST API Documentation with drf-spectacular vs drf-yasg

Last updated 4 months ago | 439 views 75     5

Tags:- Python Django DRF

Introduction: Why API Documentation Matters

In modern web development, clear and interactive API documentation isn't optional—it's essential. Whether you're working with frontend teams, mobile devs, or third-party integrators, your API must be understandable and testable.

Django REST Framework (DRF) doesn’t come with full OpenAPI support out of the box. That’s where tools like drf-yasg and drf-spectacular come in. Both help you auto-generate Swagger or Redoc interfaces so devs can interact with and explore your endpoints visually.

This article walks through setup, features, code examples, and key differences to help you choose the right tool.


⚙️ drf-yasg vs drf-spectacular: At a Glance

Feature drf-yasg drf-spectacular
OpenAPI version 2.0 3.0
Schema generation method Introspective (view-based) Declarative (serializer/view-based)
Customization Flexible, verbose Modern, concise
Actively maintained ❌ Slower updates ✅ Regular updates
Swagger/Redoc UI ✅ Built-in ✅ Built-in
Settings complexity Moderate Lower with conventions

Setting Up drf-spectacular

Step 1: Install the package

pip install drf-spectacular

Step 2: Update settings.py

# settings.py

INSTALLED_APPS += ['drf_spectacular']

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

Step 3: Add schema and UI views to urls.py

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'),
]

Step 4: Optional schema customization

# settings.py

SPECTACULAR_SETTINGS = {
    'TITLE': 'My Awesome API',
    'DESCRIPTION': 'Cool API built with Django and DRF',
    'VERSION': '1.0.0',
}

Setting Up drf-yasg

Step 1: Install the package

pip install drf-yasg

Step 2: Configure urls.py

from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
   openapi.Info(
      title="My API",
      default_version='v1',
      description="Test description",
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]

Adding Schema to Views or Serializers

With drf-spectacular:

from drf_spectacular.utils import extend_schema

@extend_schema(
    summary="Get user list",
    responses={200: UserSerializer(many=True)}
)
def get(self, request):
    ...

With drf-yasg:

from drf_yasg.utils import swagger_auto_schema

@swagger_auto_schema(
    operation_description="Get list of users",
    responses={200: UserSerializer(many=True)}
)
def get(self, request):
    ...

✅ Full Code Example: drf-spectacular

# views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from drf_spectacular.utils import extend_schema
from .serializers import UserSerializer
from .models import User

class UserListView(APIView):
    
    @extend_schema(
        responses={200: UserSerializer(many=True)},
        summary="List all users"
    )
    def get(self, request):
        users = User.objects.all()
        serializer = UserSerializer(users, many=True)
        return Response(serializer.data)
# urls.py

from django.urls import path
from .views import UserListView
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView

urlpatterns = [
    path('api/users/', UserListView.as_view()),
    path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
    path('api/docs/', SpectacularSwaggerView.as_view(url_name='schema')),
]

Tips & Common Pitfalls

✅ Best Practices

  • Document custom endpoints using decorators (extend_schema, swagger_auto_schema)

  • Add schemas to every view, even if it's just basic metadata

  • Use drf-spectacular for OpenAPI 3.0 support

  • Test schema generation in CI using spectacular --validate

⚠️ Common Pitfalls

Mistake Fix/Tip
No schema shown for generic views Add view-level decorators
Using both drf-yasg and spectacular Pick one — don’t mix them
Poor schema structure Use proper serializers with Meta fields
Forgetting DEFAULT_SCHEMA_CLASS Schema won't be generated without this setting

Conclusion: Which One Should You Use?

Both drf-spectacular and drf-yasg do the job well. However:

  • Choose drf-spectacular if:

    • You want OpenAPI 3.0

    • Prefer newer tooling and better future support

    • Like declarative, structured schemas

  • Choose drf-yasg if:

    • You’re maintaining a legacy codebase

    • Need view-based introspection with minimal setup

Recommendation: Start new projects with drf-spectacular.


Final Takeaways

  • API docs are not just for frontend devs — they are crucial for debugging, integration, and testing.

  • Adding documentation shouldn't be an afterthought.

  • Pick a tool that aligns with your team's workflow and project scale.