14

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()
Baalito
  • 67
  • 8
user3378649
  • 5,154
  • 14
  • 52
  • 76
  • that's not dictionary syntax at all... – nthall Jun 14 '15 at 17:44
  • See [this](http://stackoverflow.com/questions/8685790/adding-header-to-python-request-module) answer. – doru Jun 14 '15 at 17:53
  • possible duplicate of [Using headers with the Python requests library's get method](http://stackoverflow.com/questions/6260457/using-headers-with-the-python-requests-librarys-get-method) – Łukasz Rogalski Jun 14 '15 at 17:58
  • Possible duplicate of [adding header to python request module](https://stackoverflow.com/questions/8685790/adding-header-to-python-request-module) – Cees Timmerman Jun 19 '17 at 16:19

4 Answers4

17

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)
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
3

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

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

 requests.get(url, headers=headers)
pancakes
  • 682
  • 5
  • 8
1

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)
Grokify
  • 15,092
  • 6
  • 60
  • 81
1

Headers should be a dict, thus this should work

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

requests.get(url, headers=headers)
dmr
  • 526
  • 2
  • 8