Fix Python – Adding headers to requests module

Question

Asked By – discky

Earlier I used httplib module to add a header in the request. Now I am trying the same thing with the requests module.

This is the python request module I am using:
http://pypi.python.org/pypi/requests

How can I add a header to request.post() and request.get(). Say I have to add foobar key in each request in the header.

Now we will see solution for issue: Adding headers to requests module


Answer

From http://docs.python-requests.org/en/latest/user/quickstart/

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get or .post method.

So more specific to your question:

headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

This question is answered By – tkone

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0