How to add header in requests

39.9k Views Asked by At

Is there any other elegant way to add header to requests :

import requests

requests.get(url,headers={'Authorization', 'GoogleLogin auth=%s' % authorization_token}) 

doesn't work, while urllib2 worked :

import urllib2

request = urllib2.Request('http://maps.google.com/maps/feeds/maps/default/full')
request.add_header('Authorization', 'GoogleLogin auth=%s' % authorization_token)
urllib2.urlopen(request).read()
4

There are 4 best solutions below

0
On

You can pass dictionary through headers keyword. This is very elegant in Python :-)

 headers = {
     "header_name": "header_value",
 }

 requests.get(url, headers=headers)
0
On

You can add custom headers to a requests request using the following format which uses a Python dictionary having a colon, :, in its syntax.

r = requests.get(url, headers={'Authorization': 'GoogleLogin auth=%s' % authorization_token})

This is presented in the Requests documentation for custom headers as follows:

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}

>>> r = requests.get(url, headers=headers)
0
On

Headers should be a dict, thus this should work

headers= {}
headers['Authorization']= 'GoogleLogin auth=%s' % authorization_token

requests.get(url, headers=headers)
0
On

You can add headers by passing a dictionary as an argument.

This should work:

requests.get(url,headers={'Authorization': 'GoogleLogin auth=%s' % authorization_token}) 

Why your code not worked?

You were not passing a dictionary to the headers argument. You were passing values according to the format defined in add_header() function.

According to docs,

requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)

headers – (optional) Dictionary of HTTP Headers to send with the Request.

Why request.add_header() worked?

Your way of adding headers using request.add_header()worked because the function is defined as such in the urllib2 module.

Request.add_header(key, val)

It accepts two arguments -

  1. Header name (key of dict defined earlier)
  2. Header value(value of the corresponding key in the dict defined earlier)