Interview question
How do you generate and provide API documentation for a Django REST Framework API? Django REST Framework API के लिए documentation कैसे generate और provide करते हैं?
Answer
Use drf-spectacular or drf-yasg to auto-generate OpenAPI/Swagger documentation. Add docstrings and descriptions to serializers and viewsets. Configure documentation URL in settings. Clients can explore and test endpoints interactively.
// Using drf-spectacular (Recommended)
pip install drf-spectacular
# settings.py
INSTALLED_APPS = [
'drf_spectacular',
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
# urls.py
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView, SpectacularRedocView
urlpatterns = [
# Schema endpoints
path('api/schema/', SpectacularAPIView.as_view(), name='schema'),
path('api/docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
path('api/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'),
# API endpoints
path('api/', include('myapp.urls')),
]
// Adding Documentation to ViewSet
from drf_spectacular.utils import extend_schema, OpenApiParameter
class BookViewSet(viewsets.ModelViewSet):
'''A viewset for viewing and editing books.'''
queryset = Book.objects.all()
serializer_class = BookSerializer
@extend_schema(
summary='List all books',
description='Returns a paginated list of all books in the system.',
parameters=[
OpenApiParameter(
name='author',
description='Filter by author name',
required=False,
),
],
)
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
@extend_schema(
summary='Create a new book',
description='Creates and returns a new book object.',
)
def create(self, request, *args, **kwargs):
return super().create(request, *args, **kwargs)
// Documenting Serializers
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
class BookDetailedSerializer(serializers.ModelSerializer):
'''Detailed book serializer with all information.'''
author = serializers.CharField(
help_text='Full name of the author',
max_length=100
)
price = serializers.DecimalField(
max_digits=10,
decimal_places=2,
help_text='Price in USD'
)
class Meta:
model = Book
fields = ['id', 'title', 'author', 'price', 'created_at']
// Using drf-yasg (Alternative)
pip install drf-yasg
# settings.py
INSTALLED_APPS = [
'drf_yasg',
'rest_framework',
]
# urls.py
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title='Book API',
default_version='v1',
description='API for managing books',
contact=openapi.Contact(email='contact@example.com'),
),
public=True,
)
urlpatterns = [
path('api/docs/', schema_view.with_ui('swagger', cache_timeout=0)),
path('api/redoc/', schema_view.with_ui('redoc', cache_timeout=0)),
]
// Accessing Documentation
// Swagger UI: http://localhost:8000/api/docs/
// ReDoc: http://localhost:8000/api/redoc/
// OpenAPI Schema: http://localhost:8000/api/schema/
// Custom Schema Descriptions
from drf_spectacular.utils import extend_schema, extend_schema_serializer
@extend_schema_serializer(
examples=[
{
'value': {
'id': 1,
'title': 'Django for Beginners',
'author': 'John Smith',
'price': '29.99',
'created_at': '2024-01-15T10:30:00Z'
}
}
]
)
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'drf-spectacular or drf-yasg use करें auto-generate documentation के लिए। Docstrings और descriptions add करें। Interactive API documentation provide करें।
Was this answer clear?