ghazi-git / drf-standardized-errors

Standardize your DRF API error responses
https://drf-standardized-errors.readthedocs.io/en/latest/
MIT License
257 stars 15 forks source link
api django django-rest-framework error-formatter error-response exception-handling python standardized-errors

DRF Standardized Errors

Standardize your DRF API error responses.

Read the Docs GitHub Workflow Status codecov PyPI PyPI - License Code style: black

By default, the package will convert all API error responses (4xx and 5xx) to the following standardized format:

{
  "type": "validation_error",
  "errors": [
    {
      "code": "required",
      "detail": "This field is required.",
      "attr": "name"
    },
    {
      "code": "max_length",
      "detail": "Ensure this value has at most 100 characters.",
      "attr": "title"
    }
  ]
}
{
  "type": "client_error",
  "errors": [
    {
      "code": "authentication_failed",
      "detail": "Incorrect authentication credentials.",
      "attr": null
    }
  ]
}
{
  "type": "server_error",
  "errors": [
    {
      "code": "error",
      "detail": "A server error occurred.",
      "attr": null
    }
  ]
}

Features

Requirements

Quickstart

Install with pip

pip install drf-standardized-errors

Add drf-standardized-errors to your installed apps

INSTALLED_APPS = [
    # other apps
    "drf_standardized_errors",
]

Register the exception handler

REST_FRAMEWORK = {
    # other settings
    "EXCEPTION_HANDLER": "drf_standardized_errors.handler.exception_handler"
}

Notes

Integration with DRF spectacular

If you plan to use drf-spectacular to generate an OpenAPI 3 schema, install with pip install drf-standardized-errors[openapi]. After that, check the doc page for configuring the integration.

Links

License

This project is MIT licensed.