cottonblueskies
cottonblueskies

Reputation: 11

Spoonacular API integration with Python

def getRecipeByIngredients():
    payload = {
        'fillIngredients': False,
        'ingredients': ingredients,
        'limitLicense': False,
        'number': 5,
        'ranking': 1
    }

    api_key = os.environ['api_key']

    endpoint = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients"


    headers={
        "X-Mashape-Key": "mashape key",
        "X-Mashape-Host": "mashape host"
    }

    r = requests.get(endpoint, params=payload, headers=headers)
    results = r.json()
    title = results[0]['title']
    print(title)

I am having trouble accessing the title of the recipe when searching for recipes by ingredients using the Spoonacular API. I've followed all the instructions on the page and made sure I'm getting to the title correctly, however when I search for the recipe nothing is outputted besides the GET request. Any ideas?

Upvotes: 1

Views: 2583

Answers (1)

John
John

Reputation: 31

It looks like your code is mostly correct.

Here are the necessary changes:

  • Make sure the ingredients variable is given a value
  • Make sure api_key is given as the value for the X-Mashape-Key header

I've made the relevant changes to your code below:

import requests

def getRecipeByIngredients(ingredients):
    payload = {
        'fillIngredients': False,
        'ingredients': ingredients,
        'limitLicense': False,
        'number': 5,
        'ranking': 1
    }

    api_key = "your-api-key"

    endpoint = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients"


    headers={
        "X-Mashape-Key": api_key,
        "X-Mashape-Host": "mashape host"
    }

    r = requests.get(endpoint, params=payload, headers=headers)
    results = r.json()
    title = results[0]['title']
    print(title)

getRecipeByIngredients('apple')

If you're interested, I've written a Python package that wraps the Spoonacular API and makes it easy to access each of its endpoints. The package is available on GitHub.

Upvotes: 2

Related Questions