8

I'm facing problem to get data from Django Headers.

My API using CURL:-

curl -X POST \
  https://xyx.com \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/json' \
  -H 'xyzId: 3223' \
  -H 'abcData: ABC-123' \
  -d '{
  "name": "xyz",
  "dob": "xyz",
  "user_info": "xyz",
}'

In my API I need to get xyzId and abcData

I tried request.META['abcData'] but got error KeyError.

How do I get Both data in my view?

Please help me to out this problem.

Thanks in advance.

Mr Singh
  • 3,936
  • 5
  • 41
  • 60
  • Possible duplicate of [How can I get all the request headers in Django?](https://stackoverflow.com/questions/3889769/how-can-i-get-all-the-request-headers-in-django) – Sardorbek Imomaliev May 29 '18 at 12:23

2 Answers2

14

As per documentations say https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpRequest.META

With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.

So you should be able to access your header like this

request.META['HTTP_ABCDATA']
Sardorbek Imomaliev
  • 14,861
  • 2
  • 51
  • 63
0

If I understand your question properly.

I believe you are consuming the API.

from urllib import request
with request.urlopen(url, data) as f:
    print(f.getcode())  # http response code
    print(f.info())     # all header info

    resp_body = f.read().decode('utf-8') # response body

To little more advance in-case you are using requests module.

Then you can make request like.

head = {}
head['Cache-Control'] = 'no-cache'
head['Content-Type'] = 'application/json'
head['xyzId'] = '3223'
head['abcData'] = 'ABC-123'
x = request.post(url='https://xyx.com',headers = head)
print x.headers

Well incase if you just want to access HTTP header in your Django View as above suggested use.

import re
regex = re.compile('^HTTP_')
dict((regex.sub('', header), value) for (header, value) 
       in request.META.items() if header.startswith('HTTP_'))

The above will give you all headers.

Hope this helps.

burning
  • 2,426
  • 6
  • 25
  • 38