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

drf_yasg.openapi:一种快速创建中文API文档的底层库

发布时间:2023-12-27 02:46:23

drf_yasg.openapi是一个Python库,它可以帮助开发人员快速创建中文API文档。它是基于Django REST Framework(DRF)和drf-yasg的扩展,提供了一种简单而快速的方法来生成规范和易于阅读的API文档。

使用drf_yasg.openapi可以大大减少手动编写API文档的工作量,并且可以确保文档的准确性和一致性。以下是使用drf_yasg.openapi创建中文API文档的步骤和示例代码。

首先,确保你已经安装了以下软件包:

- Django

- Django REST Framework

- drf-yasg

- drf_yasg.openapi

接下来,创建一个Django项目,并在项目的settings.py文件中添加以下配置:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'drf_yasg',
    ...
]

SWAGGER_SETTINGS = {
    'VALIDATOR_INSTANCES': [
        'drf_yasg.openapi.validators.CoreAPICompatValidator',
    ],
}

接下来,在你的Django项目中创建一个API视图,例如:

from rest_framework.views import APIView
from rest_framework.response import Response


class HelloAPI(APIView):
    def get(self, request):
        """
        API接口描述:获取欢迎信息
        ---
        请求参数:
        - name: name
          required: false
          default: World
          description: 名字
          type: string
        ---
        返回参数:
        - name: message
          description: 欢迎信息
          type: string
        """
        name = request.query_params.get('name', 'World')
        message = f'Hello, {name}!'
        return Response({'message': message})

在上面的示例代码中,我们创建了一个名为HelloAPI的视图类,它包含一个GET请求方法。在方法的注释中,我们使用了一些特定的标记来描述API的接口和请求参数。例如,我们使用请求参数:标记来描述请求参数,使用返回参数:标记来描述返回参数。

最后,在项目的urls.py文件中,添加以下代码来设置API文档的路由:

from django.urls import path
from rest_framework.permissions import AllowAny
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/terms/",
        contact=openapi.Contact(email="contact@example.com"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=(AllowAny,),
)

urlpatterns = [
    ...
    path('api/docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('api/redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    ...
]

在上面的代码中,我们创建了一个get_schema_view实例,并将其用作Swagger和Redoc的UI视图。这样,我们就可以通过访问/api/docs/和/api/redoc/来查看API文档的Swagger和Redoc版本。

此外,我们还可以通过添加其他的OpenAPI标记来进一步描述API的信息,例如使用request_body来描述请求的body参数,使用security来描述API的安全需求等等。

总结起来,drf_yasg.openapi是一个方便的库,可以帮助我们在Django项目中快速创建中文API文档。通过使用特定的标记和配置,我们可以轻松地描述API的接口、请求参数和返回参数。使用Swagger和Redoc的UI视图,我们可以方便地查看和测试API文档。这个库的使用大大简化了API文档的编写和维护的工作量,提高了开发人员的效率和团队的协作。