Skip to main content

Standardize all Django REST Framework API responses into a consistent, predictable format

Project description

Django Response Formatter

Standardize all Django REST Framework API responses into a consistent, predictable format.

Every response — success or error — follows this structure:

{
    "status": "success" | "error",
    "message": "Human-readable message",
    "data": { ... } | [ ... ] | null,
    "errors": { ... } | null,
    "metadata": { ... } | null
}

Installation

pip install dj-response-formatter

Quick Start

1. Add to INSTALLED_APPS:

INSTALLED_APPS = [
    # ...
    "dj_response_formatter",
]

2. Configure DRF settings:

REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": [
        "dj_response_formatter.renderers.FormattedJSONRenderer",
    ],
    "EXCEPTION_HANDLER": "dj_response_formatter.exceptions.format_exception_handler",
}

3. (Optional) Add middleware for non-DRF exception handling:

MIDDLEWARE = [
    # ... other middleware ...
    "dj_response_formatter.middleware.ResponseFormatterMiddleware",
]

That's it. All your API responses are now formatted consistently.

Response Examples

Success (2xx)

# View
class UserView(APIView):
    def get(self, request, pk):
        user = get_object_or_404(User, pk=pk)
        return Response(UserSerializer(user).data)
{
    "status": "success",
    "message": "Request was successful.",
    "data": {
        "id": 1,
        "username": "john",
        "email": "john@example.com"
    },
    "errors": null,
    "metadata": null
}

Validation Error (400)

{
    "status": "error",
    "message": "Bad request.",
    "data": null,
    "errors": {
        "email": ["This field is required."],
        "username": ["A user with that username already exists."]
    },
    "metadata": {
        "status_code": 400
    }
}

Not Found (404)

{
    "status": "error",
    "message": "Not found.",
    "data": null,
    "errors": null,
    "metadata": {
        "status_code": 404
    }
}

Paginated Response

DRF pagination metadata is automatically extracted:

{
    "status": "success",
    "message": "Request was successful.",
    "data": [
        {"id": 1, "name": "Item 1"},
        {"id": 2, "name": "Item 2"}
    ],
    "errors": null,
    "metadata": {
        "pagination": {
            "count": 100,
            "next": "http://api.example.com/items/?page=2",
            "previous": null
        }
    }
}

Helper Functions

Use the helper functions for explicit control over response messages:

from dj_response_formatter.helpers import success_response, error_response, raw_response

class UserView(APIView):
    def get(self, request, pk):
        user = get_object_or_404(User, pk=pk)
        return success_response(
            data=UserSerializer(user).data,
            message="User retrieved successfully.",
        )

    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return success_response(
                data=serializer.data,
                message="User created.",
                status_code=201,
            )
        return error_response(
            errors=serializer.errors,
            message="Validation failed.",
            status_code=400,
        )

success_response(data=None, message=None, status_code=200, headers=None)

Returns a DRF Response that the renderer formats as a success envelope.

error_response(errors=None, message=None, status_code=400, headers=None)

Returns a DRF Response that the renderer formats as an error envelope.

raw_response(data=None, status_code=200, headers=None)

Returns a DRF Response that skips formatting entirely. Use for health checks, webhooks, or any endpoint that must return raw JSON.

Configuration

Customize behavior via the RESPONSE_FORMATTER dict in your Django settings:

RESPONSE_FORMATTER = {
    # Field names in the envelope
    "STATUS_FIELD": "status",
    "MESSAGE_FIELD": "message",
    "DATA_FIELD": "data",
    "ERRORS_FIELD": "errors",
    "METADATA_FIELD": "metadata",

    # Status values
    "SUCCESS_STATUS": "success",
    "ERROR_STATUS": "error",

    # Default messages
    "DEFAULT_SUCCESS_MESSAGE": "Request was successful.",
    "DEFAULT_ERROR_MESSAGE": "An error occurred.",

    # Include fields even when their value is null
    "INCLUDE_NULL_FIELDS": True,

    # Extract pagination info into metadata automatically
    "EXTRACT_PAGINATION": True,

    # Pagination field names to detect
    "PAGINATION_FIELDS": ["count", "next", "previous", "page_size", "total_pages"],
}

Example: Minimal Responses

RESPONSE_FORMATTER = {
    "INCLUDE_NULL_FIELDS": False,
}

A success response now omits null fields:

{
    "status": "success",
    "message": "Request was successful.",
    "data": {"id": 1}
}

Example: Custom Field Names

RESPONSE_FORMATTER = {
    "STATUS_FIELD": "ok",
    "DATA_FIELD": "result",
    "SUCCESS_STATUS": True,
    "ERROR_STATUS": False,
}
{
    "ok": true,
    "message": "Request was successful.",
    "result": {"id": 1},
    "errors": null,
    "metadata": null
}

Components

Component Purpose
FormattedJSONRenderer Wraps all DRF responses in the standardized envelope
format_exception_handler Normalizes DRF exception data for consistent error formatting
ResponseFormatterMiddleware Catches unhandled exceptions outside DRF views (optional)
success_response / error_response / raw_response View helpers for explicit control

Requirements

  • Python >= 3.9
  • Django >= 4.2
  • Django REST Framework >= 3.14

License

MIT

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

dj_response_formatter-0.1.3.tar.gz (16.4 kB view details)

Uploaded Source

Built Distribution

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

dj_response_formatter-0.1.3-py3-none-any.whl (14.9 kB view details)

Uploaded Python 3

File details

Details for the file dj_response_formatter-0.1.3.tar.gz.

File metadata

  • Download URL: dj_response_formatter-0.1.3.tar.gz
  • Upload date:
  • Size: 16.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for dj_response_formatter-0.1.3.tar.gz
Algorithm Hash digest
SHA256 1dc8816d125aaf4820cc77e12116b7c1e2a881754f4dc5e4f95197049bab1536
MD5 9521c16a388c7f12d41c7f9dd3b78a5a
BLAKE2b-256 fe82777e10d57e29c9e078ea4b01ee1778e20a7743c42ea73ab91b14b7eb9c2e

See more details on using hashes here.

Provenance

The following attestation bundles were made for dj_response_formatter-0.1.3.tar.gz:

Publisher: publish.yml on suomynonAnonymous/django-response-formatter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file dj_response_formatter-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for dj_response_formatter-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 7070231afe18f3e08707fc113e1a9169637413bd9b78812efd4e32374e9080e2
MD5 ab240680f1970a9b0b1c61d89180101a
BLAKE2b-256 04d4af7466afe92f1142e790bc7b1d8ae10610861274d4c5d741772f57118459

See more details on using hashes here.

Provenance

The following attestation bundles were made for dj_response_formatter-0.1.3-py3-none-any.whl:

Publisher: publish.yml on suomynonAnonymous/django-response-formatter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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