1. Home
  2. Docs
  3. Django Rest Framework
  4. Swagger API Documentation

Swagger API Documentation

Step 1: Install drf-yasg

First, you need to install drf-yasg. You can do this by running the following command in your terminal:

pip install drf-yasg
Bash

Step 2: Update INSTALLED_APPS

Next, add drf_yasg to your INSTALLED_APPS in your project’s settings.py file:

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

Step 3: Configure URLs

You need to configure your project’s urls.py to include URLs provided by drf-yasg for the Swagger UI. Here’s how to do it:

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

schema_view = get_schema_view(
   openapi.Info(
      title="Your API Title",
      default_version='v1',
      description="API description",
      terms_of_service="https://www.yourcompany.com/terms/",
      contact=openapi.Contact(email="contact@yourcompany.local"),
      license=openapi.License(name="BSD License"),
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)

urlpatterns = [
    ...
    re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]
Python

Step 4: Secure Your Swagger Documentation (Optional)

If you want to restrict access to your API documentation, you can modify the permission_classes in the schema_view. For example, using permissions.IsAuthenticated will require users to be logged in to view the documentation:

schema_view = get_schema_view(
    ...
    permission_classes=(permissions.IsAuthenticated,),
)
Bash

Step 5: Customize Your API Documentation

open your api views.py

suppose my views.py like below

from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
from Patient.models import Patient
from Appointment.models import Appointment,Visit

from .serializers import PatientSerializer,PatientReportSerializer
from .permissions import HasPatientPermission  
class PatientViewSet(viewsets.ModelViewSet):
    queryset = Patient.objects.all()
    serializer_class = PatientSerializer
    authentication_classes = [JWTAuthentication, SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated, HasPatientPermission]  


class PatientReportViewSet(viewsets.ViewSet):
    def retrieve(self, request, pk=None):
        try:
            patient = Patient.objects.get(pk=pk)
            appointments = Appointment.objects.filter(patient=patient)
            visits = Visit.objects.filter(patient=patient)
            
            serializer = PatientReportSerializer(patient)
            data = serializer.data
            data['appointments'] = appointments.values()
            data['visits'] = visits.values()
            
            return Response(data)
        except Patient.DoesNotExist:
            return Response({'error': 'Patient not found'}, status=404)
Python

follow below for customization

Import drf-yasg Utilities in Your views.py

You’ll need to import swagger_auto_schema for method-specific customization and other utilities as needed:

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
Python

Customize PatientViewSet

To customize the documentation for PatientViewSet, you can use DRF’s built-in class and method decorators. Since ModelViewSet automatically provides list, create, retrieve, update, and destroy actions, you can customize the swagger_auto_schema decorator for specific actions as follows:

class PatientViewSet(viewsets.ModelViewSet):
    ...
    @swagger_auto_schema(operation_summary="List all patients",
                         operation_description="Retrieve a list of all registered patients")
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)

    @swagger_auto_schema(operation_summary="Create a new patient",
                         operation_description="Register a new patient in the system",
                         request_body=PatientSerializer,
                         responses={201: PatientSerializer})
    def create(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)
Python

Customize PatientReportViewSet

For custom actions like those in PatientReportViewSet, you can decorate each method directly:

class PatientReportViewSet(viewsets.ViewSet):

    @swagger_auto_schema(operation_summary="Retrieve patient report",
                         operation_description="Get a detailed report for a specific patient, including appointments and visits",
                         responses={200: PatientReportSerializer,
                                    404: 'Patient not found'})
    def retrieve(self, request, pk=None):
        ...
Python

Deployment

collect static file and upload in clouded folder otherwise not work

How can we help?