'Use USDA Food API to search and get the nutrient facts by food name

I'm using an API to access the USDA food database. I crawled some food names from the menus of some restaurants. I want to connect these foods' names to Food Data Central to get their nutritional data. I wanted to find a way to search by food name. Does anyone know how to do that? Here is the code I rewrote through Github. But it does not seem to run, no result output, and displays KeyError: 'foodNutrients'. Does anyone know how can I do?

import requests
import json
import pandas as pd

apiKey = '###'
foodName = "Cheddar cheese"

def nutrient_API(apiKey, foodName):
    data = {"query": foodName}
    parameters = {'dataType': 'Survey (FNDDS)'}
    res = requests.post(f'https://api.nal.usda.gov/fdc/v1/foods/search?api_key={apiKey}', json=data, params = parameters)
    api_resp = json.loads(res.text)
    api_nutrients = api_resp[FoodNutrients]
    nutrientDict = {"FoodName": [api_resp['description'], foodName, api_resp['datatype']]}

    for items in api_nutrients:
        if 'amount' in items:
            nutrientDict.update({(items['nutrient']['name']): [(items['nutrient']['id']),
            (items['amount']), (items['nutrient']['unitName'])]})
            print(nutrientDict)
    return nutrientDict

nutrient_API('###', 'Cheddar cheese')


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source