Adding a header to the python request module

I used to use the httplib module to add a header to the request. Now I am trying to do the same with the request module.

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

How to add a header to request.post and request.get , let's say I need to add the foobar key to each request in the header.

+33
python python-requests
Dec 31 '11 at 2:02
source share
2 answers

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 key is the name of the header and value is the value of the pair) and pass that dict to the headers parameter on .get or .post .

So a more specific question:

 headers = {'foobar': 'raboof'} requests.get('http://himom.com', headers=headers) 
+71
Dec 31 2018-11-12T00:
source share

You can also do this to set a title for all future events 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

+9
Apr 14 '16 at 21:20
source share



All Articles