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.
In this code, you add a headers dictionary that contains a single header Content-Type set to application/json . This tells the REST API that you're sending JSON data with the request. You then call requests. post() , but instead of passing todo to the json argument, you first call json.
The API key is a lightweight form of authentication because it's added to the end of the request URL when being sent.
A CARTO API Key is physically a token/code of 12+ random alphanumeric characters. You can pass in the API Key to our APIs either by using the HTTP Basic authentication header or by sending an api_key parameter via the query string or request body.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With