Calling REST API with an API key using the requests package in Python

Viewed 58073

What should the python code to call the REST API below using the requests package? I do not know how to pass the "apikey"

curl -X POST -u "apikey":"1234abcd" -H "Accept: application/json" -F "file=@{input_file}" https://api_url

Thank you for your help.

3 Answers

Your curl command is like code. When you do not know what it supports, you can curl --help or use curl ... --trace-ascii 1.txt to figure out the process.

from requests.auth import HTTPBasicAuth
import requests

url = 'https://api_url'
headers = {'Accept': 'application/json'}
auth = HTTPBasicAuth('apikey', '1234abcd')
files = {'file': open('filename', 'rb')}

req = requests.get(url, headers=headers, auth=auth, files=files)

There are two ways to do this:

Option 1

import base64
import requests
method = "get"
url = "https://xxxxx"
auth_string = f"{apiKey}:{secret}"
auth_string = auth_string.encode("ascii")
auth_string = base64.b64encode(auth_string)
headers = {
       'Accept': 'application/json',
       'Authorization' : f"Basic {auth_string.decode('ascii')}"
}
rsp = requests.request(method, url, headers=headers, auth=None)

Option 2

import requests
from requests.auth import HTTPBasicAuth
method = "get"
url = "https://xxxxx"
auth = HTTPBasicAuth(apiKey, secret)
rsp = requests.request(method, url, headers=None, auth=auth)

Everything gets passed as headers so your header could look like this:

self.headers = {
    'Content-type': 'application/json', 
    'Authorization': f'ApiKey {self.passwd}',
}  

And your actual request can look like this:

requests.get(url, auth=None, headers=self.headers)
Related