Skip to main content

A library for Django Rest Framework returning consistent and easy-to-parse API error messages.

Project description

Django Rest Framework Simple API Errors

PyPI test workflow codecov pyversions

What is this?

A library for Django Rest Framework returning consistent, predictable and easy-to-parse API error messages.

This library was built with RFC7807 guidelines in mind, but with a small twist: it defines a "problem detail" as a list instead of a string, but it still serves as a way to include errors in a human-readable and easy-to-parse format for any API consumer. Error messages are formatted using RFC7807 keywords and DRF exception data.

Unlike standard DRF, where the error response format varies depending on the error source, this library always returns errors in a consistent and predictable structure.

What's different?

Compared to other similar and popular libraries, this library:

  • Is based on RFC7807 guidelines
  • Aims to provide not only a standardized format for error details, but also human-readable error messages (perfect for both internal and public APIs)
  • Transforms both django.core.exceptions.ValidationError and rest_framework.errors.ValidationError to API errors, so you don't have to handle error raised by services/domain logic, clean(), etc.

Table of Contents

Installation

Install using the command line:

pip install drf-simple-api-errors

Usage

Exception Handler

Add EXCEPTION_HANDLER in your REST_FRAMEWORK settings of your Django project settings file:

REST_FRAMEWORK = {
    # ...
    "EXCEPTION_HANDLER": "drf_simple_api_errors.exception_handler",
}

Error structure overview

API error messages will include the following keys:

  • "title" (str): A brief summary that describes the problem type.
  • "detail" (list[str] | None): A list of specific explanations related to the problem, if any.
  • "invalid_params" (list[dict] | None): A list of dict containing details about parameters that were invalid or malformed in the request, if any. Each dict within this list provides:
    • "name" (str): The name of the parameter that was found to be invalid.
    • "reasons" (list[str]): A list of strings describing the specific reasons why the parameter was considered invalid or malformed.
{
  "title": "Error message.",
  "detail": ["error"],
  "invalid_params": [
    {
      "name": "field_name",
      "reason": ["error"]
    }
  ]
}

Example JSON Error Responses

Field validation errors

{
  "title": "Error message.",
  "details": null,
  "invalid_params": [
    {
      "name": "field_name",
      "reason": ["error"]
    }
  ]
}

Non-fields validation errors

{
  "title": "Error message.",
  "detail": ["error"],
  "invalid_params": null
}

Other bad requests with no detail

{
  "title": "Error message.",
  "detail": null,
  "invalid_params": null
}

Settings

Default settings:

DRF_SIMPLE_API_ERRORS = {
    "CAMELIZE": False,
    "EXTRA_HANDLERS": [],
    "FIELDS_SEPARATOR": ".",
}
  • CAMELIZE

Camel case support for Django Rest Framework exceptions JSON error responses.

If CAMELIZE is set to True:

{
  "title": "Error message.",
  "details": null,
  "invalidParams": [
    {
      "name": "fieldName",
      "reason": ["error"]
    }
  ]
}
  • EXTRA_HANDLERS

Support for exceptions that differ from the standard structure of the Django Rest Framework.

For example, if you need to customize how a specific exception is handled or want to format an existing exception differently, you can create your own handler.

To customize error handling for your project, simply create a new file (for example, extra_handlers.py) and define your own handler functions. This approach lets you tailor error responses to fit your specific needs.

Then add it to the EXTRA_HANDLERS list in this package settings:

DRF_SIMPLE_API_ERRORS = {
    "EXTRA_HANDLERS": [
        "path.to.my.extra_handlers.custom_handler",
        # ...
    ]
}

For reference, this library uses the same pattern for its own extra handlers here.

  • FIELDS_SEPARATOR

Support for nested dicts containing multiple fields to be flattened.

If FIELDS_SEPARATOR is set to .:

{
    "field1": {
        "field2": "value"
    }
}

Will result in:

{
    "field1.field2": "value"
}

Testing

All the necessary commands are included in the Makefile.

We are using tox and poetry to run tests in every supported Python version.

Run test during development with the commands below:

make install  # only if necessary
make test

Finally, run tox to ensure the changes work for every supported python version:

pip install tox  # only if necessary
tox -v

Support

Please open an issue.

Contributing

Please use the Github Flow. In a nutshell, create a branch, commit your code, and open a pull request.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf_simple_api_errors-2.1.1.tar.gz (11.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

drf_simple_api_errors-2.1.1-py3-none-any.whl (13.0 kB view details)

Uploaded Python 3

File details

Details for the file drf_simple_api_errors-2.1.1.tar.gz.

File metadata

  • Download URL: drf_simple_api_errors-2.1.1.tar.gz
  • Upload date:
  • Size: 11.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.10.18 Linux/6.11.0-1018-azure

File hashes

Hashes for drf_simple_api_errors-2.1.1.tar.gz
Algorithm Hash digest
SHA256 3dee257f10e670c04c91d232190729ab04f73936250ee8603a7886062f51e5fc
MD5 c01f25e1e905541d652bb01b5d874711
BLAKE2b-256 1a3fe198870b12b4f02a2a53cb47698ac9d45b877b13d9284e87bed0c7781296

See more details on using hashes here.

File details

Details for the file drf_simple_api_errors-2.1.1-py3-none-any.whl.

File metadata

  • Download URL: drf_simple_api_errors-2.1.1-py3-none-any.whl
  • Upload date:
  • Size: 13.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.10.18 Linux/6.11.0-1018-azure

File hashes

Hashes for drf_simple_api_errors-2.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 3d1fc14ffb4f719104540862056480370fbf890095dee9f5f09936a12ecadd27
MD5 5acb0360eec263d03866eff1bd3caae4
BLAKE2b-256 a746af7bcd0ada2310a1cd2072c9d16fdfe25d7637e1a658226ce64c3ec10a29

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page