3
\$\begingroup\$

I’m pretty new to Python. I’m trying to build a multiple choice quiz using Edamam API. It’s currently not flagging any errors but there has to be a neater way to ask the questions, I’m just stuck as some of them require pulling through data from Edamam.

import requests


def recipe_search(meal_type, ingredient, Health):
    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():
    meal_type = input("Are you looking for a particular type of meal?: ")
    if meal_type == "yes":
          input("Select an option from the following list:\n - breakfast\n - brunch\n - lunch\n - snack\n - teatime\n > ")
    else: pass

    Health = input("Do you have a dietary requirement?: ")
    if Health == "yes":
        input("Select an option from the following list:\n - vegan\n - vegetarian\n - paleo\n - dairy-free\n - gluten-free\n"
              " - wheat-free\n - fat-free\n - low-sugar\n - egg-free\n - peanut-free\n - tree-nut-free\n - soy-free\n"
              " - fish-free\n - shellfish-free\n >")
    else: pass

    ingredient = input("What ingredient would you like to use?:\n > ")
    results = recipe_search(meal_type, ingredient, Health)
    for result in results:
        recipe = result["recipe"]
        print(recipe["ingredientLines"])
        print(recipe["label"])
        print(recipe["calories"])
        print(recipe["dishType"])
        print(recipe["cuisineType"])
        print()


run()

new_item = input("Add recipe to meal planner?:\n > ")
with open("recipe.txt", "r") as recipe_file:
    recipes = recipe_file.read()

recipes = recipes + new_item + "\n"

with open("recipe.txt", "w+") as recipe_file:
    recipe_file.write(recipes)
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

This is a good beginner project and a good API to practice writing a client.

Add type hints to your function signatures. Python has a weak type system, and the more you can do to strengthen it, the more you'll be able to perform meaningful static analysis and write self-documenting code.

Your program doesn't actually do what you intended. meal_type and Health aren't sent to the API, and even if they were, they would both be the string yes. You need to separate the "yes/no" variable from the "what" variable; the latter you are not assigning at all.

Consider using Edamam's V2 recipe API.

Pay attention to error values that the API may return, the easiest way being raise_for_status.

Delete your else: pass. Or, more likely, once you fix your health and meal assignments, the else will assign the default value for these variables, probably None.

From new_item onward, this is fairly puzzling: it might as well be an entirely separate program, as it doesn't use any of the results from your search to store in the file. It would probably a good feature to add: have the user enter the title of their chosen recipe, and store the entire rendered text of the recipe to the file.

Don't read the entire file; just open the file in append mode.

Suggested

from typing import Any

import requests


def recipe_search(meal_type: str, ingredient: str, health_restriction: str) -> list[dict[str, Any]]:
    with requests.get(
        'https://api.edamam.com/api/recipes/v2',
        headers={'Accept': 'application/json'},
        params={
            'app_id': '...',
            'app_key': '...',
            'type': 'any',
            'mealType': meal_type,
            'health': health_restriction,
            'q': ingredient,
        },
    ) as result:
        result.raise_for_status()
        data = result.json()
    return data['hits']


def run_recipe_search() -> None:
    has_meal_type = input('Are you looking for a particular type of meal? ')
    if has_meal_type == 'yes':
          meal_type = input(
              'Select an option from the following list:'
              '\n - breakfast'
              '\n - brunch'
              '\n - lunch'
              '\n - snack'
              '\n - teatime'
              '\n > '
          )
    else:
        meal_type = None

    has_restriction = input('Do you have a dietary requirement? ')
    if has_restriction == 'yes':
        health_restriction = input(
            'Select an option from the following list:'
            '\n - vegan'
            '\n - vegetarian'
            '\n - paleo'
            '\n - dairy-free'
            '\n - gluten-free'
            '\n - wheat-free'
            '\n - fat-free'
            '\n - low-sugar'
            '\n - egg-free'
            '\n - peanut-free'
            '\n - tree-nut-free'
            '\n - soy-free'
            '\n - fish-free'
            '\n - shellfish-free'
            '\n >'
        )
    else:
        health_restriction = None

    ingredient = input('What ingredient would you like to use? ')
    results = recipe_search(meal_type, ingredient, health_restriction)
    for result in results:
        recipe = result['recipe']
        print(recipe['ingredientLines'])
        print(recipe['label'])
        print(recipe['calories'])
        print(recipe['dishType'])
        print(recipe['cuisineType'])
        print()


def add_recipe() -> None:
    new_item = input('What recipe would you like to add to your meal planner? ')
    with open('recipe.txt', 'a') as recipe_file:
        print(new_item, file=recipe_file)


if __name__ == '__main__':
    run_recipe_search()
    add_recipe()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.