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.
Python code
37 linesimport 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
{
"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
- Use `json.dumps(problem, indent=2, separators=(',', ': '))` for explicit separator control.
- 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
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Format data in Python using dataclasses like gRPC messages easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
Keep learning
Related tutorials and quizzes for this topic.