Skip to content Skip to sidebar Skip to footer

Calling Rest Api With An Api Key Using The Requests Package In Python

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: applicati

Solution 1:

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)

Solution 2:

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)

Solution 3:

Everything gets passed as headers so your header could look like - self.headers = {'Content-type': 'application/json', 'Authorization': f'ApiKey {self.passwd}'}. And your actual request can look like -

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

Post a Comment for "Calling Rest Api With An Api Key Using The Requests Package In Python"