Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include multiple headers in python requests

I have this HTTPS call in curl below;

header1="projectName: zhikovapp"
header2="Authorization: Bearer HZCdsf="
bl_url="https://BlazerNpymh.com/api/documents?pdfDate=$today"

curl -s -k -H "$header1" -H "$header2" "$bl_url" 

I would like to write an equivalent python call using requests module.

header ={
            "projectName": "zhikovapp",
            "Authorization": "Bearer HZCdsf="
        }
response = requests.get(bl_url, headers = header)

However, the request was not valid. What is wrong?

The contents of the returned response is like this;

<Response [400]>
_content = '{"Message":"The request is invalid."}'
headers = {'Content-Length': '37', 'Access-Control-Allow-Headers': 'projectname, authorization, Content-Type', 'Expires': '-1', 'cacheControlHeader': 'max-age=604800', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Date': 'Sat, 15 Oct 2016 02:41:13 GMT', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Content-Type': 'application/json; charset=utf-8'}
reason = 'Bad Request'

I am using python 2.7

EDIT: I corrected some syntex errors after Soviut pointed them out.

like image 824
guagay_wk Avatar asked Oct 15 '16 02:10

guagay_wk


People also ask

What are the headers of a Python request?

response.headers – Python requests. Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc.

How do I get additional information about a request in Python?

We can make requests with the headers we specify and by using the headers attribute we can tell the server with additional information about the request. Headers can be Python Dictionaries like, { “Name of Header”: “Value of the Header” } The Authentication Header tells the server who you are.

What is a POST request in Python?

Python requests – POST request with headers and body. HTTP headers let the client and the server pass additional information with an HTTP request or response. All the headers are case-insensitive, headers fields are separated by colon, key-value pairs in clear-text string format.

How do you import a request into a python function?

You can do this by typing “import requests” in your Python code. Next, you need to specify the request parameters which includes the header fields and body of your request, followed by a call to “send ()” function. Finally, you will get a response with data in it if everything goes as expected.


2 Answers

In request.get() the headers argument should be defined as a dictionary, a set of key/value pairs. You've defined a set (a unique list) of strings instead.

You should declare your headers like this:

headers = {
    "projectName": "zhikovapp",
    "Authorization": "Bearer HZCdsf="
}
response = requests.get(bl_url, headers=headers)

Note the "key": "value" format of each line inside the dictionary.

Edit: Your Access-Control-Allow-Headers say they'll accept projectname and authorization in lower case. You've named your header projectName and Authorization with upper case letters in them. If they don't match, they'll be rejected.

like image 87
Soviut Avatar answered Sep 18 '22 15:09

Soviut


  1. If you have $today defined in the shell you make curl call from, and you don't substitute it in the requests' call URL, then it's a likely reason for the 400 Bad Request.
  2. Access-Control-* and other CORS headers have nothing to do with non-browser clients. Also HTTP headers are generally case insensitive.
  3. Following @furas's advice here's the output:

    $ curl -H "projectName: zhikovapp" -H "Authorization: Bearer HZCdsf=" \
        http://httpbin.org/get
    
    {
       "args": {}, 
       "headers": {
          "Accept": "*/*", 
          "Authorization": "Bearer HZCdsf=", 
          "Host": "httpbin.org", 
          "Projectname": "zhikovapp", 
          "User-Agent": "curl/7.35.0"
       }, 
       "origin": "1.2.3.4", 
       "url": "http://httpbin.org/get"
    }
    

    And the same request with requests:

    import requests
    res = requests.get('http://httpbin.org/get', headers={
      "projectName"   : "zhikovapp",
      "Authorization" : "Bearer HZCdsf="
    })
    print(res.json())
    
    {
      'args': {},
      'headers': {
         'Accept': '*/*',
         'Accept-Encoding': 'gzip, deflate, compress',
         'Authorization': 'Bearer HZCdsf=',
         'Host': 'httpbin.org',
         'Projectname': 'zhikovapp',
         'User-Agent': 'python-requests/2.2.1 CPython/3.4.3 '
           'Linux/3.16.0-38-generic'
       },
       'origin': '1.2.3.4',
       'url': 'http://httpbin.org/get'
    }
    

    As you can see the only difference is User-Agent header. It's unlikely the cause but you can easily set it in headers to the value you like.

like image 36
saaj Avatar answered Sep 18 '22 15:09

saaj