202

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.

1

2 Answers 2

348

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)
Sign up to request clarification or add additional context in comments.

2 Comments

It may be helpful to see the response you send and/or receive back. According to Requests Advanced Usage docs, use r.headers to access the headers the server sends back and r.request.headers to view the headers you are sending to the server.
Might also be useful if your example expanded on what the headers dictionary should/could look like as the quickstart guide you linked to is pretty slim on details for it. Relatively straight forward but given the documentation is a little light there is an opportunity to improve your answer
86

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

2 Comments

Above link is dead. requests.readthedocs.io/en/latest/user/advanced/… works. (I'd just edit the post but the edit queue is full)
I have tried this solution but when I print out the headers to check, the new field is not there, it was not added to the headers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.