Search code examples
python-requestsapi-key

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.


Solution

  • 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)