| 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. 
To generate API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator), follow these steps:
1. Install drf-yasgEnsure you have drf-yasg installed in your Django project: pip install drf-yasg
2. Configure settings.pyIn 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.pyModify 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 ViewsUse @swagger_auto_schema in your DRF views to enhance documentation. Example: Class-based API Viewfrom 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 Serializerfrom 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 ServerStart 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 FeaturesUsing Query Parameters in DocumentationIf 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 UsersModify 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,),
)
|