How to access custom HTTP request headers on Django Rest Framework?
The name of the meta data attribute of request is in upper case:
print request.META
Your header will be available as:
request.META['HTTP_X_MYHEADER']
Or:
request.META.get('HTTP_X_MYHEADER') # return `None` if no such header
HTTP headers in the request are converted to
META
keys by converting all characters to uppercase, replacing any hyphens with underscores and adding anHTTP_
prefix to the name. So, for example, a header calledX-Bender
would be mapped to theMETA
keyHTTP_X_BENDER
.
If you provide a valid header information and get that information from backend then follow those
client-name='ABCKD'
then you have get that client information in post or get function following this-
request.META['HTTP_CLIENT_NAME']
it will give you output 'ABCKD'.
remember that, whatever the valid variable name you provide in your header information in request, django convert it uppercase and prefix with 'HTTP_
'in here it will client-name converted to CLIENT_NAME
and prefix with HTTP_
.so final output is HTTP_CLIENT_NAME
Seeing this is an old post, I thought I would share the newer and more flexible approach that is available since Django 2.2. You can use the request's headers object:
# curl --header "X-MyHeader: 123" --data "test=test" http://127.0.0.1:8000/api/update_log/request.headers['X-MYHEADER'] # returns "123"request.headers['x-myheader'] # case-insensitive, returns the samerequest.headers.get('x-myheader') # returns None if header doesn't exist# standard headers are also available hererequest.headers.get('Content-Type') # returns "application/x-www-form-urlencoded"
The biggest differences with request.META
are that request.headers
doesn't prepend headers with HTTP_
, it doesn't transform the header names to UPPER_SNAKE_CASE
and that the headers can be accessed case-insensitively. It will only transform the header to Title-Casing
(e.g. X-Myheader
) when displayed.