Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)

CK CK 3788 
Created at
Updated at  
1,027 0 0

The OpenAPI Specification (OAS), formerly known as the Swagger Specification, is a standard, language-agnostic interface description for REST APIs which allows both humans and computers to understand the capabilities of a service without access to source code, documentation, or network traffic inspection. It defines a standard format for describing the API, including available endpoints, request and response parameters, authentication methods, and other relevant metadata, enabling automated API documentation generation, client code generation, and testing. The OAS is governed by the OpenAPI Initiative, a collaborative open-source project that aims to standardize how REST APIs are described.
 

DRF-yasg is a Python library that automatically generates Swagger/OpenAPI specifications from Django REST Framework (DRF) APIs. Swagger (also known as OpenAPI) is a set of standards and open-source tooling for designing, building, documenting, and consuming RESTful APIs. DRF-yasg uses your DRF views, serializers, and other components to create a detailed description of your API in the OpenAPI format, which can then be used by Swagger UI or other tools to visualize and interact with your API documentation, making it easier for developers to understand and use your API.

Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)

To generate API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator), follow these steps:


1. Install drf-yasg

Ensure you have drf-yasg installed in your Django project:

pip install drf-yasg

2. Configure settings.py

In your settings.py, add drf_yasg to your INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',  # Required for Django REST Framework
    'drf_yasg',        # Required for Swagger
]

3. Configure urls.py

Modify your project's urls.py file to include Swagger and Redoc views.

from django.urls import path, re_path
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

# Schema Configuration
schema_view = get_schema_view(
    openapi.Info(
        title="My API",
        default_version='v1',
        description="API documentation for my Django project",
        terms_of_service="https://www.example.com/terms/",
        contact=openapi.Contact(email="support@example.com"),
        license=openapi.License(name="MIT License"),
    ),
    public=True,  # Set to False to restrict access to authenticated users
    permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    # Swagger JSON & UI
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    
    # ReDoc UI
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),

    # Raw JSON Schema
    path('swagger.json', schema_view.without_ui(cache_timeout=0), name='schema-json'),
]

4. Add API Documentation to Views

Use @swagger_auto_schema in your DRF views to enhance documentation.

Example: Class-based API View

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi

class HelloWorldView(APIView):
    @swagger_auto_schema(
        operation_description="Get a greeting message",
        responses={200: openapi.Response("A greeting message")},
    )
    def get(self, request):
        return Response({"message": "Hello, world!"}, status=status.HTTP_200_OK)

Example: DRF ViewSets with Serializer

from rest_framework import viewsets
from rest_framework import serializers
from myapp.models import MyModel

class MyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
        fields = '__all__'

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

5. Run the Django Server

Start the Django development server:

python manage.py runserver

Now, visit:

  • Swagger UI: http://127.0.0.1:8000/swagger/
  • ReDoc: http://127.0.0.1:8000/redoc/
  • JSON Schema: http://127.0.0.1:8000/swagger.json

6. Additional Features

Using Query Parameters in Documentation

If you need query parameters, add manual_parameters:

class MyCustomView(APIView):
    @swagger_auto_schema(
        manual_parameters=[
            openapi.Parameter('param_name', openapi.IN_QUERY, description="A sample query parameter", type=openapi.TYPE_STRING)
        ],
        responses={200: "Success"}
    )
    def get(self, request):
        param = request.GET.get('param_name', 'default_value')
        return Response({"param": param})

Restricting Swagger Access to Authenticated Users

Modify schema_view in urls.py:

 

schema_view = get_schema_view(
    openapi.Info(
        title="My API",
        default_version='v1',
    ),
    public=False,  # Restricts access to authenticated users
    permission_classes=(permissions.IsAuthenticated,),
)
Tags DRF Django REST Framework OAS Open API Open API Documentation OpenAPI OpenAPI Specification Swagger Yet Anohter Swagger Generator drf-yasg Facebook X
Comments 0
Similar posts
  1. Automated OpenAPI documentation for a Python Flask API
    1,118
  2. GPU & LLM Cluster Infrastructure & Task Scheduling Architecture
    231
  1. How to Build a Python Chatbot That Writes and Runs Code Using Microsoft AutoGen (With Sample Code)
    236
  2. Beyond Prompt Engineering: Why Loop Engineering is the Future of Autonomous AI
    300
  3. A Python Code to get the Server Instance ID for Remote Management
    358
  4. From Local Python Web to Standalone
    2,029
  5. Demystifying FAISS: Your Guide to ANN(Approximate Nearest Neighbor) Search
    314
  6. TensorRT for LLMs: Speed, Scale, and Why Startups Choose It Over TensorFlow
    459
  7. Python ML Technologies used for the target Segmentation
    376
  8. Managing WHITE_LIST in FastAPI to Improve the Server Security
    346
  9. A common async example
    966
  10. Milvus and LLM Integration - Very Smart Approach!
    294
  11. Automated API Documentation with PyCharm
    889
  12. How to install python 3.9 alongside python 3.8 on CentOS 7?
    707
  13. How to run Python 3.9 on Mac?
    647
  14. Python Quizs
    501
  15. Automated OpenAPI documentation for a Python Flask API
    1,118
  16. Uploading a file to a Google Drive Folder programmatically with Python
    3,305
  17. Garbage Collection when your system does not have enough memory in your Python App
    1,009
  18. Method to maximize full CPU performance with Python
    314
  19. How do I get the maximum available of thread in python?
    981
  20. Using Queue Algorithm with Redis - RPUSH and LPOP
    767
  21. Use cache concept with Redis : Let's do Redis programming with Python
    529
  22. Installing Python 3.8 in a venv environment on CentOS 7
    461
  23. CUDA versus OpenCL
    577
  24. Simple gRPC server based on Python
    393
  25. Python code to convert PDF file to Excel Spreadsheet
    695
  26. Python script to list files on your Google Drive and download one of them
    939
  27. Coinbase Python API - Basic Example
    461
  28. AWS Lambda Code Example based on Python
    333
  29. Python code using GPU on CentOS with AWS
    1,248
  30. Video Scence Detection with PySceneDetect
    2,318
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,733
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    86
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    198
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    234
  17. The Concept of Scaffolding in AI Agents
    222
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    576
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    253
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    328
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252