3

For my API, I need to respond every request's error with HTTP 200 and a JSON content. So instead of, responding with this:

Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

I'd like to do this:

res = {"code": 400, "message": "Bad Requset"}
Response(res)

Where is the best place to put such thing and how? In Serializer, Renderer, Exception? I need to catch every exception that serializer might throw as well as custom exception that I have written.

1 Answer 1

10

You may use status code 200 and with data=json.dumps(...), something like this:

res = {"code": 400, "message": "Bad Requset"}
return Response(data=json.dumps(res), status=status.HTTP_200_OK)

In terms of where to handle the exception, RestFramework has it covered, read Exceptions - Django REST framework, you can create a custom handler and do so.

However as api end points normally will be per view base, I would personally recommend create a custom decorator to wrap your views and return such Response in case of error. Or, if you really want to return same response on ALL errors, then follow RestFramework doc and customise your error handling should be the best practice.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.