Here is a detailed guide to using Django and django-rest-swagger (or alternative drf-yasg). becausedjango-rest-swagger
Maintenance has been stopped. It is recommended to use drf-yasg (supports Swagger 2.0 and OpenAPI 3.0), but both methods will be explained:
1. Solution selection and installation
1. Solution comparison
Library name | Maintenance status | Support specifications | Functional Features |
---|---|---|---|
django-rest-swagger | Deprecated | Swagger 2.0 | Old projects are compatible, simple document generation |
drf-yasg | Active maintenance | OpenAPI 3.0 | Powerful, support more detailed configuration |
2. Install the recommended library (drf-yasg)
# Install drf-yasg (recommended)pip install drf-yasg # or install the old version of django-rest-swagger (not recommended)# pip install django-rest-swagger==2.2.0
2. Configure drf-yasg to generate interface documents (recommended)
1. Configuration
# INSTALLED_APPS = [ ... 'rest_framework', 'drf_yasg', # Add drf-yasg] # Optional: Configure the default permissions for DRF (set on demand)REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.', ] }
2. Configure URL routing
# from import path, include from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi # Define Swagger Document Viewschema_view = get_schema_view( ( title="API Documentation", default_version='v1', description="Project interface documentation", terms_of_service="/terms/", contact=(email="contact@"), license=(name="MIT License"), ), public=True, permission_classes=(,), # Control document access rights) urlpatterns = [ # Swagger Document Routing path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='redoc'), #Other API routing path('api/', include('')), ]
3. Add document comments to the view
In view (such as) Use decorator or YAML annotation to describe the interface:
from drf_yasg.utils import swagger_auto_schema from rest_framework.views import APIView from rest_framework.response import Response class UserListView(APIView): @swagger_auto_schema( operation_description="Get user list", manual_parameters=[ ( 'page', openapi.IN_QUERY, description="page number", type=openapi.TYPE_INTEGER ), ], responses={200: 'Successfully obtained user list'} ) def get(self, request): return Response({"users": []})
4. Access the document
• Swagger UI: http://localhost:8000/swagger/
• ReDoc: http://localhost:8000/redoc/
3. Use the old version of django-rest-swagger (not recommended)
1. Configuration
# INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework_swagger', # Add django-rest-swagger] # Configure Swagger settingsSWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'basic': { 'type': 'basic' } }, 'USE_SESSION_AUTH': False, # Whether to enable Django's Session authentication}
2. Configure URL routing
# from import path from rest_framework.schemas import get_schema_view from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer schema_view = get_schema_view( title="API Documentation", renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer] ) urlpatterns = [ path('swagger/', schema_view, name='swagger'), path('api/', include('')), ]
3. Add comments to the view
Use document strings (YAML format) in view classes or functions:
class UserListView(APIView): def get(self, request): """ Get the user list --- parameters: - name: page in: query type: integer required: false description: Page number Responses: 200: description: successfully returned to user list """ return Response({"users": []})
4. Access the document
• Visithttp://localhost:8000/swagger/
4. Frequently Asked Questions and Optimization
1. The document does not display the interface
• Reason: View not inheritedAPIView
Or no routing is configured.
• Solution: Ensure that all interfaces use DRF's view classes (e.g.APIView
, ViewSet
) and register to the route correctly.
2. Authentication configuration
• Scenario: You need to log in to access Swagger documents.
•Configuration (inmiddle):
SWAGGER_SETTINGS = { 'LOGIN_URL': '/admin/login/', # Login address 'LOGOUT_URL': '/admin/logout/', 'USE_SESSION_AUTH': True, }
3. Custom document style
• Method: Overwrite the default template or usedrf-yasg
Extended parameters:
schema_view = get_schema_view( ... patterns=[...], # Specify the route to include generator_class='', # Custom generator)
4. Hide specific interfaces
• usedrf_yasg
:
@swagger_auto_schema(auto_schema=None) def my_view(request): ...
5. Summary
Recommended solution: Use drf-yasg, which is more powerful and has active maintenance.
Core steps:
- Install the library and configure it
and
。
- Add interface description to the view via decorator or comment.
- Visit
/swagger/
View the document.
• Things to note:
• Ensure that the view inherits from the base class of DRF (e.g.APIView
)。
• If the interface involves authentication (such as JWT), security policies need to be configured in the document.
This is the end of this article about the implementation of django automatic interface documentation. For more related django automatic interface documentation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!