I did implement the standard API response such as this article in my app. And I also implement drf-yasg for my API documentation. As we know the schema are using directly serializer to present the response. How I can cover all these below response examples by using drf-yasg schema?
1. Success Single
{
"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. Success List
{
"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. Error or Failed
{
"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
}
Currently I just did implement the general schema from drf_yasg, and still don't know how to do that.
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'),
]
from drf-yasg cover all responses to following implemented standard api response
No comments:
Post a Comment