Spoonacular API与Python的集成

2024-05-16 11:08:43 发布

您现在位置: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)

我在使用Spoonacular API按配料搜索配方时遇到问题。我已经按照页面上的所有说明进行了操作,并确保我正确地找到了标题,但是当我搜索配方时,除了GET请求之外,什么也没有输出。有什么想法吗?在


Tags: keyapifalsetitledef配方resultsendpoint
1条回答
网友
1楼 · 发布于 2024-05-16 11:08:43

看起来你的代码基本上是正确的。在

以下是必要的更改:

  • 确保给了ingredients变量一个值
  • 确保将api_key作为X-Mashape-Key头的值

我已对您的以下代码进行了相关更改:

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')

如果您感兴趣的话,我已经编写了一个Python包,它封装了Spoonacular API,并使其能够轻松地访问其每个端点。包是available on GitHub。在

相关问题 更多 >