Type error when accessing API data and insert into a CSV file

38 Views Asked by At

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")

1

There are 1 best solutions below

0
Aleksei Krikunov On

First, I think you want to pass data as argument to the function as def get_info(data): and in the prompt loop you will call it as get_info(data)

The error you got means that item variable is not a dict-like object as you expect but string. data is 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 variable item will take values as "name", "birth_year", etc).

def get_info(data):
    with open("star_wars_people2.csv", "a") as aFile:
        aFile.write(
            data["name"] + data["birth_year"] + data["height"] + data["mass"] + "\n"
        )