{
"$type": "site.standard.document",
"canonicalUrl": "https://rednafi.com/python/uniform-error-response-in-drf/",
"description": "Standardize Django REST Framework error responses using custom exception handlers to match Microsoft's REST API guidelines format.",
"path": "/python/uniform-error-response-in-drf/",
"publishedAt": "2022-01-20T00:00:00.000Z",
"site": "at://did:plc:fgtm2c26vfcj74rfmeggbyqj/site.standard.publication/3mnl6f7ob462z",
"tags": [
"Python",
"Django",
"TIL",
"API"
],
"textContent": "Django Rest Framework exposes a neat hook to customize the response payload of your API when\nerrors occur. I was going through [Microsoft's REST API guideline] and wanted to make the\nerror response of my APIs more uniform and somewhat similar to [this example].\n\nI'll use a modified version of the [quickstart example] in the DRF docs to show how to\nachieve that. Also, we'll need a POST API to demonstrate the changes better. Here's the same\nexample with the added POST API. Place this code in the project's urls.py file.\n\nIf you make a POST request to /users endpoint with the following payload where it'll\nintentionally fail email and username validation:\n\nyou'll see the following response:\n\nWhile this is okay, there's one gotcha here. The error payload isn't consistent. Depending\non the type of error, the shape of the response payload will change. This can be a problem\nif your system has custom error handling logic that expects a consistent response.\n\nI wanted the error payload to have a predictable shape while carrying more information\nlike - HTTP error code, error message, etc. You can do it by wrapping the default\nrest_framework.views.exception_handler function in a custom exception handler function.\nLet's write the api_exception_handler:\n\nNow, you'll have to register this custom exception handler in the settings.py file. Head\nover to the REST_FRAMEWORK section and add the following key:\n\nIf you make a POST request to /users endpoint with an invalid payload as before, you'll\nsee this:\n\nMuch nicer!\n\nFurther reading\n\n- [Custom Exception Handling - DRF docs]\n\n\n\n\n[microsoft's rest api guideline]:\n https://github.com/microsoft/api-guidelines\n\n[this example]:\n https://github.com/microsoft/api-guidelines/blob/vNext/Guidelines.md#examples\n\n[quickstart example]:\n https://www.django-rest-framework.org/#example\n\n[custom exception handling - drf docs]:\n https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling",
"title": "Uniform error response in Django Rest Framework"
}