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

DRF_Yasg.openapiInfo()插件推荐

发布时间:2023-12-14 08:36:26

DRF_Yasg是一个用于为Django Rest Framework (DRF) 生成Swagger/OpenAPI规范的插件。它提供了一个简单的方法来为DRF API生成优雅的文档,并且可以轻松地集成到Django项目中。以下是对于DRF_Yasg的使用例子:

安装DRF_Yasg:

pip install drf-yasg

### 示例1:基本设置

首先,需要在Django的settings.py文件中进行一些基本设置。

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

# ...

SWAGGER_SETTINGS = {
    'USE_SESSION_AUTH': False,  # 关闭session认证
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        },
    }
}

然后,需要在urls.py文件中添加以下代码来启用swagger UI。

from django.urls import path
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
   openapi.Info(
      title="Your Project",
      default_version='v1',
      description="API Documentation",
      terms_of_service="https://www.google.com/policies/terms/",
      contact=openapi.Contact(email="contact@yourcompany.com"),
      license=openapi.License(name="MIT License"),
   ),
   public=True,
)

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

现在就可以运行Django服务器,并在浏览器中访问Swagger UI了。默认情况下,swagger UI将位于/swagger/路径下。

### 示例2:添加认证

可以通过配置插件的SECURITY_DEFINITIONS来添加认证方式。以下是一个支持JWT认证的示例。

settings.py中添加以下代码:

from drf_yasg import openapi

SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'Bearer': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        },
    },
    'LOGIN_URL': 'rest_framework:login',
    'LOGOUT_URL': 'rest_framework:logout',
    'PERSIST_AUTH': True,
}

swagger_info = openapi.Info(
    title="Your Project",
    default_version='v1',
    description="API Documentation",
    terms_of_service="https://www.google.com/policies/terms/",
    contact=openapi.Contact(email="contact@yourcompany.com"),
    license=openapi.License(name="MIT License"),
)

urls.py中添加以下代码:

from drf_yasg import openapi
from drf_yasg.views import get_schema_view

schema_view = get_schema_view(
    info=swagger_info,
    public=True,
    authentication_classes=(
        authentication.TokenAuthentication,
        authentication.SessionAuthentication,
    ),
    permission_classes=(permissions.AllowAny,),
)

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

### 示例3:自定义操作

在一些情况下,可能需要自定义操作,例如文档内的参考链接或自定义参数。可以通过定义一个包含操作的字典来实现。

from drf_yasg.openapi import Parameter

@extend_schema(
    parameters=[
        OpenApiParameter(
            name="username",
            required=True,
            type=str,
            location=OpenApiParameter.QUERY,
            description="搜索关键字",
        )
    ],
    description="用户搜索操作",
)
@api_view()
def user_search(request):
    """
    用户搜索
    """
    # ...


urlpatterns = [
    ...
    path('user-search/', user_search),
    ...
]

### 示例4:文档分组

可以通过为每个API添加分组标签来将API分组展示在Swagger UI中。可以使用@extend_schema装饰器来指定组名称。

@extend_schema(tags=['分组1'])
@api_view()
def api_endpoint1(request):
   # ...

@extend_schema(tags=['分组1'])
@api_view()
def api_endpoint2(request):
   # ...

@extend_schema(tags=['分组2'])
@api_view()
def api_endpoint3(request):
   # ...


urlpatterns = [
    ...
    path('api-endpoint1/', api_endpoint1),
    path('api-endpoint2/', api_endpoint2),
    path('api-endpoint3/', api_endpoint3),
    ...
]

以上是一些DRF_Yasg的使用例子。DRF_Yasg能够轻松地为DRF API生成Swagger/OpenAPI规范,并能够进行一些自定义设置,例如认证方式、分组等。通过使用这个插件,可以为DRF API提供清晰、易读的文档,方便其他开发人员理解和使用API。