How to Create an RFC 7807 Error JSON in Python

Construct a structured error response using the RFC 7807 Problem Details format with a reusable function.

Easy Python 3.10+ Aug 9, 2026 API design & gRPC 14 views 0 copies

Python code

37 lines
Python 3.10+
import json
from typing import Dict


def create_rfc7807_error(
    type_: str,
    title: str,
    status: int,
    detail: str,
    instance: str,
    extra_fields: Dict[str, object] | None = None,
) -> str:
    """
    Build a JSON string following RFC 7807 Problem Details format.
    """
    problem = {
        "type": type_,
        "title": title,
        "status": status,
        "detail": detail,
        "instance": instance,
    }
    if extra_fields:
        problem.update(extra_fields)
    return json.dumps(problem, indent=2, sort_keys=True)


if __name__ == "__main__":
    error = create_rfc7807_error(
        type_="https://example.com/problems/out-of-credit",
        title="You do not have enough credit.",
        status=403,
        detail="Your current balance is 30, but that costs 50.",
        instance="/account/12345/msgs/abc",
        extra_fields={"balance": 30, "accounts": ["/account/12345", "/account/67890"]},
    )
    print(error)

Output

stdout
{
  "accounts": [
    "/account/12345",
    "/account/67890"
  ],
  "balance": 30,
  "detail": "Your current balance is 30, but that costs 50.",
  "instance": "/account/12345/msgs/abc",
  "status": 403,
  "title": "You do not have enough credit.",
  "type": "https://example.com/problems/out-of-credit"
}

How it works

The function builds a dictionary with the mandatory RFC 7807 fields (type, title, status, detail, instance) then optionally merges additional extension fields with update. Using json.dumps with indent=2 produces a readable, pretty-printed JSON string. The sort_keys=True sorts the keys alphabetically, which is helpful for stable comparisons and debugging. The output is a single JSON string ready to be returned from an API endpoint or written to a response body.

Common mistakes

  • Forgetting to set the mandatory 'type' field, which should be a URI referencing the problem type.
  • Using `json.dumps` without `indent` or `sort_keys` results in a compact, less readable output.
  • Mutating the input dictionary by reusing it across calls instead of creating a new one each time.

Variations

  1. Use `json.dumps(problem, indent=2, separators=(',', ': '))` for explicit separator control.
  2. Wrap the function to return a `dict` instead of a string, then let a web framework serialize it.

Real-world use cases

  • Returning standardized error payloads from a REST API to help clients handle failures consistently.
  • Providing machine-readable error details for webhook consumers to log or display diagnostics.
  • Implementing a custom error response in a microservice that adheres to industry standards.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.