使用DRF_Yasg.openapiInfo()生成API文档的最佳实践
DRF-Yasg是一个用于Django REST框架的库,用于自动生成API文档。在开发过程中,API文档对于了解和使用API非常重要。使用DRF-Yasg可以简化API文档的生成,提高开发效率。
首先,需要安装DRF-Yasg库。可以使用pip命令进行安装:
pip install drf-yasg
安装完成后,在Django项目的settings.py文件中添加以下配置:
INSTALLED_APPS = [
...
'drf_yasg',
'rest_framework',
...
]
SWAGGER_SETTINGS = {
'USE_SESSION_AUTH': False, # 设置为False,不使用session进行身份认证
'PERSIST_AUTH': True, # 设置为True,持久化认证,即每次请求都带上认证信息
'REFETCH_SCHEMA_WITH_AUTH': True, # 如果需要身份认证的接口未认证,则重新获取架构
}
接下来,在Django项目的urls.py文件中添加API文档的URL配置:
from django.contrib import admin
from django.urls import path, include
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="API文档标题",
default_version='v1',
description="API文档描述",
terms_of_service="https://www.example.com/policies/terms/",
contact=openapi.Contact(email="contact@example.com"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
urlpatterns = [
...
path('api/docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
...
]
上述代码中,需要修改以下内容:
- title: API文档标题
- default_version: 默认版本号
- description: API文档描述
- terms_of_service: 服务条款链接
- contact: 联系方式
- license: 许可证
运行Django项目后,在浏览器中访问http://localhost:8000/api/docs/即可看到生成的API文档界面。
在生成API文档时,我们需要为每个接口添加注释。下面是一个示例接口及其注释:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def hello(request):
"""
返回Hello World字符串
---
responses:
200:
description: Hello World
"""
return Response("Hello World")
接口函数需要使用@api_view装饰器进行装饰,并在函数上方添加注释。注释的格式需要遵循OpenAPI规范。其中,responses中可以定义接口的响应信息,例如响应码和响应描述。
使用DRF-Yasg生成API文档的最佳实践是:
1. 对于每个API接口,添加@api_view装饰器并添加对应的注释。
2. 修改settings.py文件,配置DRF-Yasg的相关设置。
3. 在urls.py文件中添加API文档的URL配置,并添加相应的注释。
4. 运行Django项目并在浏览器中访问生成的API文档界面。
通过以上步骤,可以快速生成并展示API文档,方便开发人员查阅和使用API。同时,API文档的自动生成也能提高开发效率,减少手工编写文档的工作量。
