How to filter an API Search result in Python?

866 Views Asked by At

I am using the edamam recipe api and have been trying to filter the response by only saving recipes with a number of calories > the max inputed by the user. I keep getting an error. This is the code:

import requests
import pandas as pd


def recipe_search(ingredient):
    app_id = ''
    app_key = ''
    result = requests.get('https://api.edamam.com/search?q={}&app_id={}&app_key={}'.format(ingredient, app_id, app_key))
    data = result.json()
    return data['hits']


def run():
    ingredient = input('Enter an ingredient: ')
    max_no_of_calories = float(input('Enter the max amount of calories desired in recipe: '))
    data_label = []
    data_uri = []
    data_calories = []
    results = recipe_search(ingredient)

    for result in results:
        recipe = result['recipe']
        result['calories'] < max_no_of_calories
        data_label.append(recipe['label'])
        data_uri.append(recipe['uri'])
        data_calories.append(recipe['calories'])
        data = {'Label': data_label,
                'URL': data_uri,
                'No of Calories': data_calories
                }
        df = pd.DataFrame(data, columns=['Label', 'URL'])
        df.to_csv(r'C:\Users\name\Documents/cfg-python/export_dataframe.csv',
                  index=False, header=True)


run()
df2 = pd.read_csv(r'C:\Users\name\Documents/cfg-python/export_dataframe.csv')
sorted_df = df2.sort_values(by=["calories"], ascending=True)
sorted_df.to_csv(r'C:\Users\name\Documents/cfg-python/export_dataframe.csv', index=False)

This is the error:

if result['calories'] < max_no_of_calories:
KeyError: 'calories'

Is anyone able to help? How could I re-write this code with the filter of only recipes with under the max_no_of_calories? 'max_no_of_calories' is input by the user.

1

There are 1 best solutions below

0
On

You made a typo in your for loop

for result in results:
    recipe = result['recipe']
    if recipe["calories"] < max_no_of_calories:
        print(recipe["calories"])

This will get rid of your key error