Skip to content

Instantly share code, notes, and snippets.

@devvspaces
Created December 13, 2022 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devvspaces/77d1022239b0e74d2cca2cab5a2ba394 to your computer and use it in GitHub Desktop.
Save devvspaces/77d1022239b0e74d2cca2cab5a2ba394 to your computer and use it in GitHub Desktop.
Code snippet for wrapping Django restframwork swagger api response with Success, Path, Status
from drf_yasg import openapi
from drf_yasg.inspectors import SwaggerAutoSchema
from drf_yasg.openapi import Schema
class BaseSchema(SwaggerAutoSchema):
def wrap_schema(self, schema):
"""Wrap schema with success, status, message, data and path fields
:param schema: Schema to wrap
:type schema: Schema
:return: Wrapped schema
:rtype: Schema
"""
return Schema(
type='object',
properties={
'success': Schema(type='boolean'),
'status': Schema(type='string'),
'message': Schema(type='string'),
'data': schema,
'path': Schema(type='string'),
}
)
def get_responses(self):
"""Get responses for swagger,
wrap all responses with success, status, message, data and path fields
:return: Responses
:rtype: openapi.Responses
"""
response_serializers = self.get_response_serializers()
data = self.get_response_schemas(response_serializers)
for code in data.keys():
try:
data[code].schema = self.wrap_schema(data[code].schema)
except AttributeError:
pass
return openapi.Responses(
responses=data
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment