0

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    The [docs](https://developer.edamam.com/edamam-docs-recipe-api?gclid=CjwKCAjwqvyFBhB7EiwAER786ThtfQ-cmJ2TxO4Af8RftHpwXYH9V-vMGtY2HtvietoeZpxS_vmE-RoCezAQAvD_BwE) say you can pass a `calories=` parameter with your GET request. "The format is calories=RANGE where RANGE is replaced by the value in kcal. RANGE is in one of MIN+, MIN-MAX or MAX, where MIN and MAX are non-negative integer numbers. The + symbol needs to be properly encoded. Examples: “calories=100-300” will return all recipes with which have between 100 and 300 kcal per serving." –  Jun 08 '21 at 17:39
  • 1
    Hello Polly, welcome to SO. I guess you should hide your API key, unless it is public. – Alexis Jun 08 '21 at 23:11

1 Answers1

0

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