I've written a function to search for a recipe in an API and print the ingredients(code below). I get an error message (see ## in text for problematic line) saying that list indices must be integers or slices, not str. The examples I have been given seem to use strings, so I'm not sure why it won't work in my code. Any help greatly appreciated! Sophie
def get_chosen_recipe():
chosen_recipe = input("What recipe do you want to cook? ")
app_id = "<my app id>"
app_key = "<my app key>"
url = 'https://api.edamam.com/search?q={}&app_id={}&app_key={}'.format(chosen_recipe, app_id, app_key)
response = requests.get(url)
response.raise_for_status() # Raises error code if unsuccessful http request
choice = response.json()
ingredients = choice['hits']['recipe']['ingredientLines'] ## THIS LINE CAUSES THE ERROR
if chosen_recipe:
return pprint(ingredients)
else:
return print("No ingredients found. Please try a different recipe.")
The error message you are getting is a TypeError: list indices must be integers or slices, not str
. This is due to trying to access a list as if it were a dictionary. In the API response, choice['hits']
is a list of recipe hits, not a single recipe object. Each item in this list is a dictionary representing a recipe, which includes another dictionary accessed by the key 'recipe'
.
Instead, you would need to first select an item from the hits list before you can access its 'recipe'
dictionary, like so:
ingredients = choice['hits'][0]['recipe']['ingredientLines']