JSON Middleware
- class smarter.lib.django.middleware.json.SmarterJsonErrorMiddleware(get_response)[source]
Bases:
SmarterMiddlewareMixinMiddleware to ensure that all requests for
application/jsonreturn responses that are also in JSON format.This middleware intercepts HTTP responses for requests that specify an
Accept: application/jsonheader. If the response is an error (status code >= 400) and is not already aJsonResponse, it wraps the error details in a JSON structure and returns a standardized JSON error response.This ensures that API clients and frontend applications expecting JSON always receive a consistent JSON error format, improving developer experience and error handling.
Key Features
Detects requests with
Accept: application/json.Converts non-JSON error responses (status code >= 400) to a standardized JSON format.
Preserves the original status code in the JSON response.
Integrates seamlessly with Django’s middleware stack.
Note
Only affects responses to requests that explicitly accept JSON.
Does not alter successful (status < 400) responses or responses already in JSON format.
Example
To enable this middleware, add it to your Django project’s middleware settings:
MIDDLEWARE = [ ... 'smarter.lib.django.middleware.json.SmarterJsonErrorMiddleware', ... ]
- Parameters:
request (django.http.HttpRequest) – The incoming HTTP request object.
response (django.http.HttpResponse) – The outgoing HTTP response object.
- Returns:
The original response, or a
JsonResponseif the request expects JSON and an error occurred.- Return type: