3

我确实在我的应用程序中实现了标准 API 响应,例如这篇文章。我还为我的 API 文档实现了 drf-yasg。正如我们所知,模式正在使用直接序列化程序来呈现响应。我如何使用 drf-yasg 模式涵盖以下所有这些响应示例?

1. 成功单身

{
   "status": 200,                       # int : http status, can be 201, 200, etc.
   "success": true,                     # bool: boolean to identify the response is success or failed.
   "message": "The success message",    # str : string success message or null
   "result": {}                         # dict: a dict response data
}

2. 成功名单

{
   "status": 200,      # int : http status
   "success": true,    # bool: boolean to identify the response is success or failed.
   "message": null,    # str : string message or null.
   "results": [],      # arr : a list/array

   "count": 2,                                                   # int: all total result items
   "page_size": 5,                                               # int: maximum items per-page
   "current_page": 1,                                            # int: your current page
   "next": "http://127.0.0.1:8000/api/page/?page=2&search=a",    # str: string link or null.
   "previous": null                                              # str: string link or null.
}

3. 错误或失败

{
   "status": 400,                      # int : http status, can be 403,404,500,etc..
   "success": false,                   # bool: boolean to identify the response is success or failed.
   "message": "The failed message",    # str : string failed message or null
   "result": {}                        # dict: a dict response data
}

目前我只是从 drf_yasg 实现了一般模式,但仍然不知道该怎么做。

from django.urls import path
from django.conf import settings

from rest_framework import permissions, authentication
from rest_framework.settings import api_settings
from rest_framework.routers import SimpleRouter

from drf_yasg import openapi
from drf_yasg.views import get_schema_view

from myproject.users.api.views import UserViewSet, AuthLoginView
from myproject.storage.api.views import FileViewSet

router = SimpleRouter()
router.register('users', UserViewSet, basename='api_users')
router.register('files', FileViewSet, basename='api_files')

app_name = 'api'
urlpatterns = [
    path('auth/login/', AuthLoginView.as_view(), name='api_auth_login'),
] + router.urls

if settings.DEBUG:
    swagger_info = openapi.Info(
        title='My Project API',
        default_version=api_settings.DEFAULT_VERSION,
        description='This is documentation of My Project open API',
        terms_of_service='https://foobar.com/tos/',
        contact=openapi.Contact(email='help@foobar.com'),
        license=openapi.License(name='Proprietary and confidential'),
    )
    schema_view = get_schema_view(
        info=swagger_info,
        public=True,
        permission_classes=(permissions.IsAdminUser,),
        authentication_classes=(authentication.SessionAuthentication,)
    )
    urlpatterns += [
        path('', schema_view.with_ui('swagger', cache_timeout=None), name='schema-swagger-ui'),
    ]
4

0 回答 0