要利用Swagger进行Debian API文档共享,可以按照以下步骤进行:
drf-yasg2(兼容DRF 3.10+)。drf-spectacular。settings.py中完成以下配置:INSTALLED_APPS = [ 'drf_yasg2', # 文档引擎 'rest_framework', # DRF核心 'django_filters' # 接口过滤支持 ] TEMPLATES = [ { 'DIRS': [os.path.join(BASE_DIR, 'templates')], }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'swagger_static')] urls.py中配置文档入口:from drf_yasg2.views import get_schema_view from drf_yasg2 import openapischema_view schema_view = get_schema_view( openapi.Info( title="电商平台API", default_version='v1', contact=openapi.Contact(email="dev@example.com") ), public=True ) urlpatterns = [ path('swagger/', schema_view.with_ui('swagger')), path('redoc/', schema_view.with_ui('redoc')) ] 启动服务后,访问/swagger/即可看到自动化生成的接口文档。
serializers.py中定义带说明的字段:class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'name', 'price'] swagger_schema_fields = { 'description': '商品核心信息模型', 'example': { 'name': '智能手机', 'price': 3999 } } @swagger_auto_schema装饰器增强接口描述:from drf_yasg2.utils import swagger_auto_schema from rest_framework import viewsets class ProductViewSet(viewsets.ModelViewSet): @swagger_auto_schema( operation_summary="批量查询商品", manual_parameters=[ openapi.Parameter( 'category', openapi.IN_QUERY, description="商品类目筛选", type=openapi.TYPE_STRING ) ], responses={ 200: ProductSerializer(many=True) } ) def list(self, request): # 业务逻辑 pass # settings.py SWAGGER_ENABLED = os.getenv('SWAGGER_ENABLED', 'False') == 'True' # urls.py if settings.SWAGGER_ENABLED: urlpatterns += [ path('swagger/', schema_view.with_ui('swagger')) ] 配合Nginx实现IP白名单访问控制。
path('api/v1/', include('app.urls', namespace='v1')), path('api/v2/', include('app.urls', namespace='v2')) schema_view_v1 = get_schema_view(..., urlconf='app.url_v1') 通过以上步骤,你可以在Debian系统上利用Swagger生成和共享API文档,从而提高团队协作效率和文档管理的规范性。