Reputation: 48
In a simple TokenAuthentication
system in Django Rest Framework, the default message when you fail to send a proper authorization token is this
{
"detail": "Authentication credentials were not provided."
}
I want all my API responses to follow a certain template e.g. { success, message, data }
P.S. I checked out other questions but couldn't find anyone with a similar problem. If it was already answered I'd be glad if you could point me to it.
Upvotes: 3
Views: 1258
Reputation: 398
For response with no exception
you can use a helper function. something like this.
def render_response(success, data=None, item=None, items=None, err_name=None,
err_message=None):
if success:
if data is not None:
return {
"success": True,
"data": data
}
elif item is not None:
return {
"success": True,
"data": {
"item": item
}
}
elif items is not None:
return {
"success": True,
"data": {
"items": items
}
}
else:
return {
"success": False,
"error": {
"name": err_name,
"message": err_message
}
}
and in your return statement for every response, use:
return Response(render_response(True, data=serializer.data), status= status.200_OK)
this will give
{
"success": true,
"data": {
...
}
}
and this can your standard format.
Upvotes: 0
Reputation: 641
If you need to change the default message, one way is to implement your own error handler like below:
#your_app/error_handler.py
def custom_exception_handler(exc, context):
....
# ovverride IsAuthenticated permission class exception
if(response.data['detail'].code == 'not_authenticated'):
response.data['code'] = Unauthorized.default_code
response.data['message'] = Unauthorized.default_detail
del response.data['detail']
return response
Also, don't forget to add your own error handler in Django's settings.py
REST_FRAMEWORK = {
"EXCEPTION_HANDLER": ("your_app.error_handler.custom_exception_handler")
}
Moreover, you can implement custom exception classes. For example:
class UnreadableCSVFile(APIException):
status_code = 400
default_detail = "Unable to read file."
default_code = "unreadable_csv_file"
Upvotes: 3