使用drf_yasg.openapi实现API自动化文档生成的编码技巧
drf_yasg.openapi是一个用于生成API自动化文档的库,它是基于Django Rest Framework和Swagger的一个扩展。 drf_yasg帮助我们轻松地将API代码中的注释和元数据转化为具有漂亮UI界面的可交互文档。下面将介绍一些drf_yasg.openapi的编码技巧,并附带一个使用例子。
1. 配置Swagger设置:
在Django的settings.py文件中,我们需要添加一些设置来配置drf_yasg.openapi。其中最重要的设置是SWAGGER_SETTINGS,它定义了生成文档的基本配置。
SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'api-key': {
'type': 'apiKey',
'in': 'header',
'name': 'Authorization'
}
},
'USE_SESSION_AUTH': False,
'PERSIST_AUTH': True,
'REFETCH_SCHEMA_WITH_AUTH': True,
'HIDE_EMPTY_TAGS': True,
'STRICT_PARAMETER_NAMES': False,
}
2. 为API视图添加元数据:
我们需要在每个API视图中添加元数据,以便drf_yasg.openapi可以将其转化为文档。例如,我们可以在视图类的下方添加一些注释来描述API的功能、参数和响应。
from rest_framework.views import APIView
from rest_framework.response import Response
class MyAPIView(APIView):
"""
My API View
This API allows users to perform some action.
---
request_serializer: MyRequestSerializer
response_serializer: MyResponseSerializer
"""
def get(self, request):
"""
Perform an action.
This endpoint allows users to perform some action.
Parameters:
- name: name
type: string
required: true
description: The name of the user.
Response:
- status: 200
schema: MyResponseSerializer
description: Successful response.
"""
name = request.GET.get('name')
# Perform the action
response = {'message': f"Hello, {name}!"}
return Response(response)
3. 生成文档视图:
为了生成文档视图,我们需要创建一个新的Django视图,并使用drf_yasg.openapi的生成器来生成文档。
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework.permissions import AllowAny
schema_view = get_schema_view(
openapi.Info(
title="My API",
default_version='v1',
description="My API description",
),
public=True,
permission_classes=(AllowAny,),
)
urlpatterns = [
# ...
path('api/docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
# ...
]
4. 运行Django应用程序并访问文档视图:
运行Django应用程序,并使用浏览器访问生成的文档视图。默认情况下,文档将在http://localhost:8000/api/docs/中显示。
通过上述设置和步骤,我们可以在API代码中添加元数据和注释,并使用drf_yasg.openapi生成漂亮的自动化文档。
总结:drf_yasg.openapi是一个简单而强大的库,它可以帮助我们轻松地生成API自动化文档。通过为API视图添加元数据和注释,我们可以定义API的功能、参数和响应。然后,通过配置Swagger设置和生成文档视图,我们可以将这些元数据转化为具有交互功能的可视化文档。这样,开发人员和用户可以更轻松地了解API的功能和使用方式。
