Uniform error response in Django Rest Framework
Django Rest Framework exposes a neat hook to customize the response payload of your API when errors occur. I was going through Microsoft's REST API guideline and wanted to make the error response of my APIs more uniform and somewhat similar to this example.
I'll use a modified version of the quickstart example in the DRF docs to show how to achieve that. Also, we'll need a POST API to demonstrate the changes better. Here's the same example with the added POST API. Place this code in the project's urls.py file.
If you make a POST request to /users endpoint with the following payload where it'll intentionally fail email and username validation:
you'll see the following response:
While this is okay, there's one gotcha here. The error payload isn't consistent. Depending on the type of error, the shape of the response payload will change. This can be a problem if your system has custom error handling logic that expects a consistent response.
I wanted the error payload to have a predictable shape while carrying more information like - HTTP error code, error message, etc. You can do it by wrapping the default rest_framework.views.exception_handler function in a custom exception handler function. Let's write the api_exception_handler:
Now, you'll have to register this custom exception handler in the settings.py file. Head over to the REST_FRAMEWORK section and add the following key:
If you make a POST request to /users endpoint with an invalid payload as before, you'll see this:
Much nicer!
Further reading
Discussion in the ATmosphere