Created
December 13, 2022 18:35
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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