Content-Type Enforcement Middleware
A snippet showing how to enforce Content-Type in middleware.
# middleware.py
from django.conf import settings
class EnforceContentTypeMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.default_ct = getattr(settings, 'DEFAULT_CONTENT_TYPE', 'application/json')
self.only_api_prefixes = getattr(settings, 'CONTENT_TYPE_ONLY_PREFIXES', ['/api/'])
def __call__(self, request):
response = self.get_response(request)
path = request.path
is_api = any(path.startswith(p) for p in self.only_api_prefixes)
if is_api:
# Respect explicit content type already set by views
current = response.get('Content-Type')
if not current:
response['Content-Type'] = self.default_ct
return response
# settings.py
MIDDLEWARE = [
# ...
'your_app.middleware.EnforceContentTypeMiddleware',
]
# Default Content-Type for API responses
DEFAULT_CONTENT_TYPE = 'application/json'
# Apply only to these URL prefixes (avoid forcing admin/static pages)
CONTENT_TYPE_ONLY_PREFIXES = ['/api/']
# views.py (examples)
from django.http import JsonResponse, HttpResponse
def api_ok(request):
return JsonResponse({'status': 'ok'}) # already sets application/json
def api_text(request):
return HttpResponse('hello') # middleware will enforce application/json
# Example curl tests
$ curl -i http://localhost:8000/api/ok/
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
...
$ curl -i http://localhost:8000/api/text/
HTTP/1.1 200 OK
Content-Type: application/json
...
hello
Explanation:
-
Forces a consistent
Content-Type(default:application/json) for API endpoints. -
Applies only to paths starting with
/api/(configurable) so HTML pages/assets are unaffected. -
Respects any
Content-Typea view already sets (e.g., file downloads, images, HTML). -
Useful for APIs that sometimes return plain
HttpResponseand you want uniform client behavior.
- Category Middleware
- Total Views 954
- Last Modified 07 March, 2026
- Tags #middleware #content-type #response #headers
Previous snippet
CORS Handling Middleware
Next snippet