drf_yasg.openapi:一种快速生成中文API文档的工具
drf_yasg.openapi 是一个用于快速生成中文 API 文档的工具,它是基于 Django REST framework 和 Swagger UI 的扩展库。下面将介绍 drf_yasg.openapi 的使用方法,并给出一些使用例子。
首先,需要安装 drf_yasg 包。可以通过 pip 命令进行安装:
pip install drf_yasg
安装完成后,在 Django 项目的 settings.py 文件中添加以下配置:
INSTALLED_APPS = [
...
'drf_yasg',
...
]
SWAGGER_SETTINGS = {
'DEFAULT_AUTO_SCHEMA_CLASS': 'drf_yasg.openapi.AutoSchema',
}
接下来,需要在项目的 urls.py 文件中添加 Swagger UI 的 URL 配置:
from django.conf.urls import url
from django.urls import include
from rest_framework import routers
from rest_framework.documentation import include_docs_urls
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
router = routers.DefaultRouter()
schema_view = get_schema_view(
openapi.Info(
title="API 文档",
default_version='v1',
description="这是一个示例 API 文档",
),
public=True,
)
urlpatterns = [
url(r'^api/docs/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^api/docs/redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
url(r'^api/v1/', include(router.urls)),
url(r'^api/docs/', include_docs_urls(title='API 文档')),
]
以上配置中,使用了 get_schema_view 方法创建了一个 API 文档的视图,并通过 schema_view.with_ui 方法指定 Swagger UI 和 ReDoc 的界面。
接下来,就可以在你的 API 视图中使用 drf_yasg 的装饰器来为你的 API 添加文档。
from drf_yasg.utils import swagger_auto_schema
@swagger_auto_schema(
method='post',
request_body=YourRequestBodySerializer,
responses={200: YourResponseSerializer}
)
@api_view(['POST'])
def your_api_view(request):
# Your view code here
pass
在上面的例子中,使用 swagger_auto_schema 装饰器为 your_api_view 视图添加了文档。
除了上面的方法,还可以使用其他装饰器为 API 视图添加更多的文档信息,例如 @swagger_auto_schema、@extend_schema 等。
最后,启动你的 Django 项目,并访问 http://your-domain/api/docs/,你将在浏览器中看到自动生成的 API 文档界面。
总结一下,drf_yasg.openapi 是一个方便快捷生成中文 API 文档的工具,它提供了简单的装饰器和配置,使得为 API 添加文档变得非常容易。无论是在开发过程中还是在对外发布 API 时,都可以使用 drf_yasg.openapi 来生成详细的 API 文档,并提供给开发者阅读和使用。
