Django REST Framework: Restrict Swagger Documentation to API Endpoints
This code snippet demonstrates how to customize the Swagger documentation in Django REST Framework to only display API endpoints with a '/api/' prefix.
class ApiOnlySchemaView(get_schema_view()):
def get_schema(self, request):
schema = super().get_schema(request)
# Filter the paths to show only the ones with '/api/' prefix
api_paths = {
path: schema['paths'][path] for path in schema['paths'] if '/api/' in path
}
schema['paths'] = api_paths
return schema
# Optional: Customize the Swagger UI settings
def get_ui_settings(self):
return {
'deepLinking': True,
'persistAuthorization': True,
'displayRequestDuration': True,
'docExpansion': 'none',
}
# main view
schema_view = ApiOnlySchemaView(
openapi.Info(
title='WorkFlowAPI',
default_version='v1',
description='This is the documentation of the api of Workflow.',
contact=openapi.Contact(email='info@vyrazu.com'),
),
public=True,
permission_classes=[permissions.AllowAny],
)
The code works by filtering the paths in the get_schema method, only keeping those that contain '/api/' in their path. This ensures that only API endpoints are displayed in the Swagger documentation.
Optional UI Settings:
The get_ui_settings method provides options to customize the Swagger UI experience. The example above enables features such as deep linking, persistent authorization, request duration display, and a minimalist documentation expansion.
Feel free to adjust these settings according to your preferences.
Note: This code assumes you are using the drf-yasg package for Swagger integration in Django REST Framework. If you encounter any issues, ensure that the package is installed and configured correctly.
AI 优化版
原文地址:https://www.cveoy.top/t/topic/mXQH 著作权归作者所有。请勿转载和采集!