欢迎访问宙启技术站
智能推送

drf_yasg.openapi中文文档生成器使用详解

发布时间:2023-12-27 02:36:52

drf_yasg是一个基于Django Rest Framework (DRF)的OpenAPI生成器,使用它可以将DRF的API文档以OpenAPI规范生成。

使用drf_yasg生成API文档需要以下步骤:

1. 在项目中安装drf_yasg库:

pip install drf_yasg

2. 在Django的settings.py中添加以下配置:

INSTALLED_APPS = [
    ...
    'drf_yasg',
]

SWAGGER_SETTINGS = {
    'DEFAULT_INFO': 'api.urls.openapi_info',
}

3. 在项目的urls.py中导入drf_yasg的相关视图和设置URL:

from django.urls import re_path
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="API文档",
      default_version='v1',
      description="API描述...",
      contact=openapi.Contact(email="contact@api.com"),
   ),
   public=True,
   permission_classes=(AllowAny,),
)

urlpatterns = [
    re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    ...
]

4. 在API视图类中添加说明注释,使用OpenAPI的装饰器来生成文档定义:

from drf_yasg.utils import swagger_auto_schema

class MyAPIView(APIView):
    @swagger_auto_schema(
        operation_summary="接口摘要",
        operation_description="接口详细描述...",
        request_body=openapi.Schema(...),
        responses={200: openapi.Response(...)},
        manual_parameters=[
            openapi.Parameter(...),
        ],
    )
    def post(self, request):
        ...

通过以上步骤,就可以在项目中使用drf_yasg生成API文档了。

下面给出一个使用示例:

1. 安装drf_yasg:

pip install drf_yasg

2. 在Django的settings.py中添加配置:

INSTALLED_APPS = [
    ...
    'drf_yasg',
]

SWAGGER_SETTINGS = {
    'DEFAULT_INFO': 'api.urls.openapi_info',
}

3. 在项目的urls.py中导入drf_yasg的相关视图和设置URL:

from django.urls import re_path
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="API文档",
      default_version='v1',
      description="这是一个测试API文档",
      contact=openapi.Contact(email="contact@api.com"),
   ),
   public=True,
   permission_classes=(AllowAny,),
)

urlpatterns = [
    re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    ...
]

4. 在API视图类中添加说明注释,使用OpenAPI的装饰器来生成文档定义:

from drf_yasg.utils import swagger_auto_schema

class MyAPIView(APIView):
    @swagger_auto_schema(
        operation_summary="测试接口摘要",
        operation_description="这是一个测试接口",
        request_body=openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                'name': openapi.Schema(type=openapi.TYPE_STRING),
                'age': openapi.Schema(type=openapi.TYPE_INTEGER),
            },
            required=['name'],
        ),
        responses={200: openapi.Response(description="OK")},
    )
    def post(self, request):
        """
        这是一个测试接口
        """
        data = request.data
        name = data.get('name')
        age = data.get('age')
        return Response({'name': name, 'age': age})

通过以上步骤,就可以在Django项目中使用drf_yasg生成API文档了。可以通过访问/swagger/来查看生成的Swagger UI界面,或者通过访问/swagger.json来获取OpenAPI规范的JSON文件。