Swagger on Django REST

Your Django REST API works, but there is no documentation. Every new developer has to read the source code to understand the endpoints. drf-yasg generates interactive Swagger and ReDoc docs automatically from your views and serializers.

TL;DR: Add Swagger and ReDoc interactive documentation to a Django REST Framework API using drf-yasg.
Stack: Python, Django, Django REST Framework, drf-yasg, Swagger
Level: Beginner
Reading time: ~5 min

Install drf-yasg

pip install drf-yasg

Register in settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
    'drf_yasg',
    ...
]

Configure Swagger in 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="API",
        default_version='v1',
        description="API description",
        contact=openapi.Contact(email="you@example.com"),
        license=openapi.License(name="BSD License"),
    ),
    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'),
    ...
]

Group endpoints by tag

from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema

class MyView(APIView):
    @swagger_auto_schema(tags=['My Category'])
    def get(self, request):
        # your code here

Define request body schema

from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema

post_schema = openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
        'internationalTitle': openapi.Schema(type=openapi.TYPE_STRING, description='International title'),
        'year': openapi.Schema(type=openapi.TYPE_INTEGER, description='Year of release'),
        'genre': openapi.Schema(type=openapi.TYPE_STRING, description='Genre'),
    },
    required=['internationalTitle', 'year']
)

class CreateRecommendationView(APIView):
    @swagger_auto_schema(request_body=post_schema)
    def post(self, request):
        ...

What you’ve built

Swagger and ReDoc documentation auto-generated from your Django REST Framework views, accessible at /swagger/ and /redoc/. The @swagger_auto_schema decorator lets you annotate views with tags, request body schemas, and response types.

Next steps

  • Lock the Swagger endpoint behind authentication in production. Exposing your full API schema publicly is a security risk.
  • Use swagger_auto_schema on serializer-backed views to get accurate schema inference automatically.
  • Export the schema as a static JSON file for Postman or other API clients: /swagger.json.

Questions or feedback? Find me on LinkedIn or GitHub.

Leave a Comment