0

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?

1
  • you need to pass the headers to the .get function Commented Apr 4, 2024 at 17:34

2 Answers 2

0

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"}
Sign up to request clarification or add additional context in comments.

Comments

0

You aren't passing headers properly to the API request. Here is the corrected code

import requests

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

headers = {
    'Authorization': 'Bearer ' + api_key  # Make sure to prepend 'Bearer ' before your API key
}

response = requests.get(api_url, headers=headers)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print("Error:", response.status_code)

I included the headers parameter in the requests.get() function, passing the headers dictionary containing the Authorization header with the API key. Also, make sure to call response.json() as a function to get the JSON data from the response.

1 Comment

It's better to concat string variable with string literal this way: f'Bearer {api_key}'. Also, you can check whether response of requests lib requests is successful or not like this: if response.ok: ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.