Skip to main content

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

Metadata

Release files for dj-response-formatter 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for dj-response-formatter 0.2.0
File Size Uploaded Provenance Actions
dj_response_formatter-0.2.0.tar.gz 18.5 kB With provenance Details for dj_response_formatter-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for dj-response-formatter 0.2.0
File Interpreter ABI Platform Actions
dj_response_formatter-0.2.0-py3-none-any.whl Python 3 none any Details for dj_response_formatter-0.2.0-py3-none-any.whl

Total release size: 33.7 kB

Release files / dj_response_formatter-0.2.0.tar.gz

Download URL dj_response_formatter-0.2.0.tar.gz
Size 18.5 kB
Tags Source
SHA-256 checksum
How to use checksums
db64892cb6715f48711844f7def43c8fa2e6def09094504533150eb05e25d2f7
BLAKE2b-256 checksum
How to use checksums
eebdaaf390053de31a8f9bdda57e73445101e53f06194969c5aafe6a4ccf9563
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 29, 2026.

Transparency log

Release files / dj_response_formatter-0.2.0-py3-none-any.whl

Download URL dj_response_formatter-0.2.0-py3-none-any.whl
Size 15.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ab33c4c4d33829578ed1d3ec78fd007dc597196d5427564161b22dde8e7a9b6e
BLAKE2b-256 checksum
How to use checksums
d3bb47089d9871b10f119555aac02dd072b15c545d3f91d10df76a4e15c526de
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 29, 2026.

Transparency log

Security for dj-response-formatter 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for dj_response_formatter-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Apr 29, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page