How to send API key in the header of python request?

Viewed 4582

I'm trying to make http post request with the file as input and some tokens I'm passing in the request header which is working fine from the postman but the same is not working via python code below is the code which I'm trying but getting 401 error

files = {'upload_file': open('small.csv', 'rb')}
url = 'https://www.test.com'
header = {'token', 'abcd'}
r = requests.post(url, headers=header, files=files)

enter image description here enter image description here

2 Answers

Try this. There are some things missing on the request such as types.

import requests

try:
    url = 'https://httpbin.org/post'
    files = {'file': ('report.csv')}

    payload={}
    files=[
    ('file',('report.csv',open('/report.csv','rb'),'text/csv'))
    ]
    headers = {
    'Accept': 'application/json',
    'Authorization': 'Bearer 0000000'
    }

    response = requests.request("POST", url, headers=headers, data=payload, files=files)


except Exception as err:
    print(err)

your dictionary for header has incorrect syntax:

change :

 header = {'token', 'abcd'}

To:

header = {'token': 'abcd'}

dictionary is ordered (from Python 3.6+) collection of key-value

you can generate equalent code of any language binding through postman , just click the code link under the url and select the language . It shows the correct python syntax:

enter image description here

Related