I am using an API to access the USDA food database and pull some nutrient data for a particular food, do some calculations (with another function partially shown here). I would like to find a way to search by a food name rather than foodID. Then I'll add it to my flask app and figure out how to allow a user to input some text to search for that food item, select it, and then run the function on it. Does anyone know how to do this?
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')