130

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
  • 6,779
  • 8
  • 29
  • 46
discky
  • 13,001
  • 7
  • 18
  • 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

233

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
  • 19,271
  • 5
  • 50
  • 77
  • 3
    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
52

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,050
  • 1
  • 25
  • 41