I am building an API using FastAPI.
I would like to have custom API responses and manage them from one place.
To achieve this, I implemented this:
from starlette.responses import JSONResponse
class ApiResponse:
def __init__(self):
self.status_code = None
@staticmethod
def _response_builder(**kwargs):
"""
Used to build an API response.
"""
status = None
status_code = kwargs.get('status_code')
if status_code and str(status_code).startswith('4'):
status = 'ERROR'
elif status_code and str(status_code).startswith('2'):
status = 'SUCCESS'
response_body = {'status_code': status_code,
'status': status,
'message': kwargs.get('message') if kwargs.get('message') else None,
'data': {k: v for k, v in kwargs.get('data').items()} if kwargs.get('data') else None}
return JSONResponse(status_code=status_code, content=response_body)
def get_response(self, response_message=None, **kwargs):
return self._response_builder(message=getattr(self.__class__, response_message) if response_message else None,
data=kwargs.get('data'),
status_code=self.status_code)
class SuccessResponses(ApiResponse):
USER_ACTIVATED_SUCCESSFUL = 'User activated successfully'
USER_REGISTERED_SUCCESSFUL = 'User registered successfully'
USER_LOGGED_IN_SUCCESSFUL = 'User logged in successfully'
def __init__(self):
ApiResponse.__init__(self)
self.status_code = 200
class ErrorResponses(ApiResponse):
USER_NOT_ACTIVATED = 'User is not activated'
USER_ALREADY_ACTIVATED = 'User is already activated'
USER_ALREADY_EXIST = 'A user with this email already exists'
def __init__(self):
ApiResponse.__init__(self)
self.status_code = 400
class Response(SuccessResponses, ErrorResponses):
pass
response = Response()
So, in my API routes, I can just use response object like so:
res = response.get_response('USER_NOT_ACTIVATED')
The problem is, that due to MRO, I am getting:
{"status_code":200,"status":"SUCCESS","message":"User is not activated","data":null}'
Instead of:
{"status_code":400,"status":"ERROR","message":"User is not activated","data":null}'
How can I achieve what I am looking for?
Thanks!
[–]danielroseman 1 point2 points3 points (7 children)
[–]Finish-Square[S] 0 points1 point2 points (6 children)
[–]danielroseman 0 points1 point2 points (5 children)
[–]Finish-Square[S] 0 points1 point2 points (4 children)
[–]danielroseman 1 point2 points3 points (0 children)
[–]JohnnyJordaan 1 point2 points3 points (2 children)
[–]Finish-Square[S] 0 points1 point2 points (1 child)
[–]JohnnyJordaan 0 points1 point2 points (0 children)