drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.
Installation
pip install drf-spectacular
INSTALLED_APPS = [
...
'drf_spectacular',
]
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}
Schema Configuration
SPECTACULAR_SETTINGS = {
'TITLE': 'Task Manager API',
'DESCRIPTION': 'API for task management',
'VERSION': '1.0.0',
'SERVE_INCLUDE_SCHEMA': False,
}
URLs
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView, SpectacularRedocView
urlpatterns = [
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'),
]
Open /api/docs/ for the interactive documentation.
Annotations
from drf_spectacular.utils import extend_schema, OpenApiParameter
class TaskViewSet(viewsets.ModelViewSet):
@extend_schema(
summary='List tasks',
description='Returns tasks belonging to the current user',
parameters=[
OpenApiParameter('status', str, description='Filter by status'),
],
)
def list(self, request):
return super().list(request)
@extend_schema(summary='Create a task')
def create(self, request):
return super().create(request)
Documenting a Serializer
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ['id', 'title', 'status']
# drf-spectacular automatically generates descriptions from the model
Exporting the Schema to a File
python manage.py spectacular --color --file schema.yml
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!