178

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.

petezurich
  • 9,280
  • 9
  • 43
  • 57
discky
  • 14,859
  • 8
  • 20
  • 11
  • 2
    Possible duplicate of [Using headers with the Python requests library's get method](https://stackoverflow.com/questions/6260457/using-headers-with-the-python-requests-librarys-get-method) – Cees Timmerman Jun 19 '17 at 16:27

2 Answers2

325

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)
tkone
  • 22,092
  • 5
  • 54
  • 78
  • 5
    It may be helpful to see the response you send and/or receive back. According to [Requests Advanced Usage docs](http://docs.python-requests.org/en/master/user/advanced/#request-and-response-objects), 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. – harperville Oct 28 '16 at 14:52
  • 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 – theYnot Dec 07 '22 at 02:55
77

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

nommer
  • 2,730
  • 3
  • 29
  • 44
  • 2
    Above link is dead. https://requests.readthedocs.io/en/latest/user/advanced/#session-objects works. (I'd just edit the post but the edit queue is full) – Jakob Lovern Jun 27 '22 at 21:55