1

Im trying to fetch data from a API and worked something out like this below. I get the following error: response 200TypeError: list indices must be integers or slices, not str I get this has to do with my API call but when i change str to int it doesnt solve the problem. Could someone help me with this?

headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
headers["Authorization"] = "Bearer xx"


total_results = []

for page_num in range(1, 7):
    # Build the URL and download the results
    url = "url" + str(page_num)
    print("Downloading", url)
    response = requests.get(url,headers=headers)
    data = response.json()
    total_results = total_results + data['results']


print("We have", len(total_results), "total results")

error: Downloading xxx: list indices must be integers or slices, not str Traceback (most recent call last):

TypeError: list indices must be integers or slices, not str

7
  • 3
    Where is data defined? Also please provide the full traceback. Commented Mar 2, 2022 at 14:03
  • I don't understand. Your url is literally URL1 through URL6, but I assume that is just for sample purposes. But then your are printing response.status_code before you even get the response. And why use CaseInsensitiveDict? Commented Mar 2, 2022 at 14:10
  • @CoryKramer i added the new code. Commented Mar 2, 2022 at 14:15
  • @theherk the print statement is just printing all the url's im reaching Commented Mar 2, 2022 at 14:15
  • Still would help to provide the full traceback, and the contents of data. Commented Mar 2, 2022 at 14:19

1 Answer 1

0

This should get you squared away:

import requests

results = []
for page in range(1, 7):
    url = f"hxx={page}"
    headers = {
        "Accept": "application/json",
        "Authorization": "Bearer redacted",
    }
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        results.append(resp.json())

print(results)

Which yields a list as expected.

The full traceback in your scenario was:

Traceback (most recent call last):
  File "/Users/h4s/projects/github.com/theherk/tmp-py/ws/./req.py", line 15, in <module>
    results.append(resp.json()["results"])
TypeError: list indices must be integers or slices, not str

Which helps us to see that the issue was that there was no key "results" in the response data. It was just a list.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much! Could you edit the url please?
No problem, I approved the edit. But history shows both this and the token, so you should probably recycle your token. ... and consider accepting the answer by clicking the checkmark if it helped.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.