I am trying to use python to access an api, pull specified data from it and add it to a csv file, under the correct element headings. I keep getting the error:
name = item['name'] TypeError: string indices must be integers, not 'str' for the line near the start of the first loop: .
I can't figure out what I've done wrong:
import requests
import csv
from pprint import pprint as pp
aHeader = ['name', 'birth_year', 'height', 'mass']
with open('star_wars_people2.csv', 'w') as file:
file = csv.DictWriter(file, fieldnames=aHeader)
file.writeheader()
def get_info():
for item in data:
name = item['name']
birth_year = item['birth_year']
height = item['height']
mass = item['mass']
with open('star_wars_people2.csv', 'a') as aFile:
aFile.write(name + birth_year + height + mass + "\n")
for i in range(5):
user_input = input("Pick a number between 1 and 83 to find the associated Star Wars character: ")
endpoint2 = 'https://swapi.dev/api/people/{}/'.format(user_input)
response = requests.get(endpoint2)
data = response.json()
pp(data)
user_input2 = input("Would you like to add this info to a file? ")
if user_input2 == 'y' or 'Y':
get_info()
else:
print('No problem!')
I'm quite new to code, but I noticed that when I targeted the whole api, and used the code below, it worked to target one specific element - but I can't then translate this to specifying a page and targeting multiple elements:
endpoint1 = 'https://swapi.dev/api/people/'
response = requests.get(endpoint1)
data = response.json()
pp(data)
aHeader = ['name', 'birth_year', 'height', 'mass']
with open('star_wars_people2.csv', 'w') as file:
file = csv.DictWriter(file, fieldnames=aHeader)
file.writeheader()
# def get_info():
for item in data['results']:
with open('star_wars_people2.csv', 'a') as aFile:
aFile.write(item['name'] + "\n")
First, I think you want to pass
dataas argument to the function asdef get_info(data):and in the prompt loop you will call it asget_info(data)The error you got means that
itemvariable is not a dict-like object as you expect but string.datais already the dictionary that you want to parse so doing for loop over it you will iterate over key of this dict (in your case variableitemwill take values as "name", "birth_year", etc).