Mike Cuddy Mike Cuddy - 3 months ago 12x
Python Question

star wars api => IndexError: list index out of range error

I am working with a star wars API from http://swapi.co/api/. I can connect to it just fine and my project is coming along fine. However, I am running into the following error message: IndexError: list index out of range error. Looking at other stack overflow questions it appears that this could be an off by one error. I am not sure how to fix it in regards to my Program. Here is the code:

url = ('http://swapi.co/api/' + str(view))
#Setting up a get request to pull the data from the URL
r = requests.get(url)
if r.status_code == 200:
print("status_code", r.status_code)
print("Sorry it appears your connection failed!")

#Storing the API response in a variable
response_dict = r.json()
print("There are currently", response_dict['count'], "items to view")

repo_dicts = response_dict['results']

num = 0
while num < response_dict['count']:
if view == 'films':
repo_dict = repo_dicts[num]['title']
print(str(num) + " " + repo_dict)
elif view == 'starships':
repo_dict = repo_dicts[num]['name']
print(str(num) + " " + repo_dict)
num += 1

Now the line that is giving me the problem is in that elif view == 'starships' area. Actually if one goes to the API you can see certain categories like films, people, starships etc. All of the categories, except films, have greater than 10 things in them. I also notice that if I go to http://swapi.co/api/starships/4/ there will be no detail found. Could the fact that some of the categories have no data be causing my problem? Thank you for any insight!!

Here is the traceback error message:

Traceback (most recent call last):
File "main.py", line 102, in <module>
File "main.py", line 98, in main
File "main.py", line 87, in began
File "main.py", line 31, in connect
repo_dict = repo_dicts[num]['name']
IndexError: list index out of range


Iterate through results you have using foreach loop like this:

for item in repo_dicts:
    if view == 'films':
        repo_dict = item['title']
        print(str(num) + " " + repo_dict)
    elif view == 'starships':
        repo_dict = item['name']
        print(str(num) + " " + repo_dict)

Reason is because api returns 10 items in response_dict['results'] but response_dict['count'] is 37. Consult api documentation on why this happens. My guess this is possible pagination happening.