RFC 7807 Integration
๐งฉ RFC 7807 Support¶
Build trust with frontend developers and third-party integrators by adopting predictable, standardized error responses.
RFC 7807 is an IETF standard that defines a consistent JSON structure for communicating error details over HTTP using the application/problem+json
media type.
Instead of returning arbitrary error objects, your API responses will include structured fields such as:
type
: A URI reference that identifies the problem typetitle
: A short, human-readable summary of the problemstatus
: The HTTP status codedetail
: A detailed explanation of the errorinstance
: A URI reference to the specific occurrence
This structure makes your error messages machine-readable, self-descriptive, and easier to document and debug across all client types.
RFC 7807 ensures every failure tells the same story โ clearly, consistently, and predictably.
โ Enable RFC7807 Globally¶
To enable RFC 7807 response formatting across your application:
from api_exception import register_exception_handlers, ResponseFormat
from fastapi import FastAPI
app = FastAPI()
register_exception_handlers(
app,
response_format=ResponseFormat.RFC7807
)
This will return error responses with the application/problem+json content type, formatted according to the RFC 7807 spec.
๐งช RFC7807 Usage Example¶
from api_exception import APIException, APIResponse
from api_exception import ResponseFormat
from api_exception import ResponseModel
from fastapi import FastAPI
from .schemas import UserResponse
from .exceptions import CustomExceptionCode
app = FastAPI()
register_exception_handlers(app, response_format=ResponseFormat.RFC7807)
@app.get(
"/rfc7807",
response_model=ResponseModel[UserResponse],
responses=APIResponse.rfc7807(
(401, CustomExceptionCode.INVALID_API_KEY, "https://example.com/errors/unauthorized", "/account/info"),
(403, CustomExceptionCode.PERMISSION_DENIED, "https://example.com/errors/forbidden", "/admin/panel"),
(422, CustomExceptionCode.VALIDATION_ERROR, "https://example.com/errors/unprocessable-entity", "/users/create")
),
)
async def rfc7807_example():
raise APIException(
error_code=CustomExceptionCode.PERMISSION_DENIED,
http_status_code=403,
)
๐ Example Error Response¶
{
"type": "https://example.com/errors/forbidden",
"title": "Permission denied.",
"status": 403,
"detail": "Access to this resource is forbidden.",
"instance": "/admin/panel"
}
๐ก Notes¶
- APIResponse.rfc7807(*items) registers each HTTP error code with its corresponding RFC7807-compliant example.
- APIException uses the values defined in your CustomExceptionCode class to populate the fields of the RFC 7807 response.
- You can still return traditional JSON error responses by switching the response_format argument to ResponseFormat.RESPONSE_DICTIONARY.