pythonapi-key

Accessing an API using a key in python


I'm new to using APIs in python and trying to access an API at the moment but keep getting an error code that based on the API documentation means I do not have access. I do have an account with an API key, so I assume there is an issue going on with passing the given key. According to the Documentation:

With shell, you can just pass the correct header with each request curl "api_endpoint_here" -H "Authorization: YOUR_API_KEY"

My code reads as follows:

api_url = 'https://api.balldontlie.io/v1/teams'
api_key = 'MyKey'

headers = {
    'Authorization' : 'MyKey'
}
response = requests.get(api_url)
print("hello")

if response.status_code == 200:
    data = response.json
    print(data)

else:
    print(response.status_code)

What am I doing wrong here?


Solution

  • You need to pass the headers as a paramter in requests.get(). Think of it this way: how would requests know that the thing you created and called "headers" is something it should be using. That's something you always have to keep in mind. No implicit stuff happening is meant to be one of the basic principles of Python.

    with requests.get(api_url, headers=headers) as response:
        data = response.json()
    

    Also since you probably want to get the JSON data right away, I changed response.json to response.json(), because the former is the bound method. If you store response.json, you could still access the data later on, though:

    ...
    >>> data = response.json
    >>> print(data)
    <bound method Response.json of <Response [200]>>
    >>> print(data())
    {'actual': "data"}