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

Peter picture Peter · Oct 31, 2018 · Viewed 22.1k times · Source

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.

Answer

KC. picture KC. · Oct 31, 2018

Your curl command is likely to the code. When you do not know what it supports to. 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 = {'filename': open('filename','rb')}

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