Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: application/json" -F "file=@{input_file}" https://api_url

Thank you for your help.

like image 218
Peter Avatar asked Oct 31 '18 03:10

Peter


People also ask

How do you call REST API in Python?

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.

Where do I put API key in request?

The API key is a lightweight form of authentication because it's added to the end of the request URL when being sent.

How do I pass an API key?

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.


2 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)
like image 72
KC. Avatar answered Oct 05 '22 12:10

KC.


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)
like image 33
user3761555 Avatar answered Oct 05 '22 13:10

user3761555