1

我正在使用 API 访问美国农业部食品数据库并提取特定食品的一些营养数据,进行一些计算(此处部分显示了另一个函数)。我想找到一种通过食物名称而不是 foodID 进行搜索的方法。然后我会将它添加到我的烧瓶应用程序中,并弄清楚如何允许用户输入一些文本来搜索该食品,选择它,然后在其上运行该功能。有谁知道如何做到这一点?

import requests
import json
import pandas as pd


apiKey = '' 
foodID = '' 

def nutrient_API(apiKey, foodID):
    #calls get api and json load
    api_resp = json.loads(requests.get('https://api.nal.usda.gov/fdc/v1/' + foodID + '?api_key=' + apiKey).text)
    #only return nutrition information
    api_nutrients = api_resp['foodNutrients']
    #first entry is its description, foodID, and database entry type
    nutrientDict = {"FoodID": [api_resp['description'],foodID, api_resp['dataType']]}

    for items in api_nutrients:
        if 'amount' in items:
            #each entry includes nutrient name, nutrient id, amount, and its respective unit
            nutrientDict.update({(items['nutrient']['name']): [(items['nutrient']['id']),
                (items['amount']),(items['nutrient']['unitName'])]})
        #print(nutrientDict)
    return(nutrientDict)


def trypfunc(foodID):
    dataframe = pd.DataFrame(nutrient_API(apiKey, foodID))
    tryp_g=(dataframe['Tryptophan'][1])
#does some more stuff
    return trypfunc

# I call the above function for one food at a time with the foodID
print("Sesame seeds: ")
trypfunc(foodID='170150')
4

1 回答 1

2

根据 API 文档(我没有测试它的密钥),您可以使用端点按关键字查询:

获取方法

foodName = "Cheddar Cheese"
requests.get('https://api.nal.usda.gov/fdc/v1/foods/search?api_key={}&query={}'.format(apiKey, foodName))

POST 方法

data = {"query" : "Cheddar Cheese"}
requests.post('https://api.nal.usda.gov/fdc/v1/foods/search?api_key={}'.format(apiKey), data=data)

我还建议在进行诸如此类的连接时使用字符串格式。它使代码更易于阅读;)。更好的是,如果你在 python 3.6+ 中,F-string。(但这是必须的)

来源:https ://fdc.nal.usda.gov/api-guide.html#bkmk-6

编辑:

通过基本的 stringg 创建,它是:

url = 'https://api.nal.usda.gov/fdc/v1/foods/search?api_key='+apiKey+'&query='+foodName

使用字符串格式,它是:

url = 'https://api.nal.usda.gov/fdc/v1/foods/search?api_key={}&query={}'.format(apiKey, foodName)

使用 f 字符串,它是:

url = f'https://api.nal.usda.gov/fdc/v1/foods/search?api_key={apiKey}&query={foodName}'

编辑 2

这对我有用

import requests
import json

def call_API(foodName, apiKey):
    url = f'https://api.nal.usda.gov/fdc/v1/foods/search?api_key={apiKey}&query={foodName}'
    r = requests.get(url)
    print(r.status_code)  # 200
    return r.json


def call_API_2(foodName, apiKey):
    data = {"query" : foodName}
    url = f'https://api.nal.usda.gov/fdc/v1/foods/search?api_key={apiKey}'
    r = requests.post(url, json=data)
    print(r.status_code)  # 200
    return r.json

ans = call_API_2("Cheddar cheese", "DEMO_KEY")

您还可以在https://pyformat.info/上找到有关字符串格式的一些信息(您应该再避免使用 %s,它已被贬值)

我希望它有所帮助,

于 2020-06-14T20:21:14.017 回答