我正在使用 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')