Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add header in requests

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()
like image 878
user3378649 Avatar asked Jun 14 '15 17:06

user3378649


People also ask

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.

How do I add a header to a python request?

In order to pass HTTP headers into a POST request using the Python requests library, you can use the headers= parameter in the . post() function. The headers= parameter accepts a Python dictionary of key-value pairs, where the key represents the header type and the value is the header value.


2 Answers

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)
like image 78
Rahul Gupta Avatar answered Sep 27 '22 18:09

Rahul Gupta


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

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

 requests.get(url, headers=headers)
like image 23
pancakes Avatar answered Sep 27 '22 18:09

pancakes