0

Looking for help with the USDA central food API:

I am working on a program that is using the USDA central food database API to collect nutritional information on food. The program takes an input (a food name) and searches the database and returns various data on macro and micronutrients. My program is working as intended 99% of the time. Sometimes, the program will search the branded foods or SR Legacy foods before searching the foundation and survey foods. I want to prioritize searching through the foundation foods and survey foods before defaulting to the other databases. Does anybody know how to do this? I assume the databases have some parameter to set, but I could not find any info about this online. Below is what I have so far, but now I need a way to prioritize the foundation foods.

import requests

def get_nutrition(api_key, food_name):
    base_url = 'https://api.nal.usda.gov/fdc/v1/foods/search'
    params = {
        'api_key': api_key,
        'query': food_name,
        'page_size': 1
    }
    
    #Access databse through API key
    response = requests.get(base_url, params=params)
    if response.status_code == 200:
        data = response.json()
        if data['foods']:
            food = data['foods'][0]
            nutrient_info = {}
            
            if 'foodPortions' in food:
                serving_size = fooc['servingSizeUnit']
                serving_size_unit = food['servingSize']
                nutrient_info['servingSize'] = f"{serving_size} {serving_size_unit}"
            #Extract calorie info
            for nutrient in food['foodNutrients']:
                if nutrient['nutrientName'] == 'Energy':
                    nutrient_info['Calories'] = f"{nutrient['value']} {nutrient['unitName']}"
            
            #Extract macronutrient info
            macro_nutrients = ['Protein', 'Total lipid (fat)', 'Carbohydrate, by difference']
            for nutrient in food['foodNutrients']:
                if nutrient['nutrientName'] in macro_nutrients:
                    nutrient_info[nutrient['nutrientName']] = f"{nutrient['value']} {nutrient['unitName']}"
            
            #Extract water soluble vitamin info        
            water_soluble_vitamins = ['Thiamin', 'Riboflavin', 'Niacin', 'Pantothenic acid', 'Vitamin B-6', 'Biotin','Folate, total', 'Vitamin B-12', 'Vitamin C']
            for nutrient in food['foodNutrients']:
                if nutrient['nutrientName'] in water_soluble_vitamins:
                    nutrient_info[nutrient['nutrientName']] = f"{nutrient['value']} {nutrient['unitName']}"
                    
            #Extract fat-soluble vitamins
            fat_soluble_vitamins = ['Vitamin A, IU', 'Vitamin D (D2 + D3)', 'Vitamin E (alpha-tocopherol)',
                                    'Vitamin K (phylloquinone)']
            for nutrient in food['foodNutrients']:
                if nutrient['nutrientName'] in fat_soluble_vitamins:
                    nutrient_info[nutrient['nutrientName']] = f"{nutrient['value']} {nutrient['unitName']}"

            #Extract macrominerals
            macrominerals = ['Calcium, Ca', 'Phosphorus, P', 'Magnesium, Mg', 'Sodium, Na', 'Chloride, Cl',
                             'Potassium, K', 'Sulfur, S']
            for nutrient in food['foodNutrients']:
                if nutrient['nutrientName'] in macrominerals:
                    nutrient_info[nutrient['nutrientName']] = f"{nutrient['value']} {nutrient['unitName']}"

            #Extract trace minerals
            trace_minerals = ['Iron, Fe', 'Manganese, Mn', 'Copper, Cu', 'Zinc, Zn', 'Iodine, I', 'Fluoride, F',
                              'Selenium, Se']
            for nutrient in food['foodNutrients']:
                if nutrient['nutrientName'] in trace_minerals:
                    nutrient_info[nutrient['nutrientName']] = f"{nutrient['value']} {nutrient['unitName']}"
   
            return nutrient_info

    else:
        print(f'Error: Unable to fetch data')
        return None
    
if __name__ == "__main__":
    api_key = 'api_key_here'
    food_name = input("Enter food name: ")
    food_info = get_nutrition(api_key, food_name)
    if food_info:
        print(f'Nutritional information for {food_name}: {food_info}')
    else:
        print('Food info not found, invalid food')

I tried to set the dataType in my parameters to a list of database names. But I don't think I can iterate in the parameters because it gave me a syntax error.

  • What error did you get on which line? Always include error details! Please check [ask], then [edit] your question and add the error with any stack trace. – Robert Jul 25 '23 at 20:00

0 Answers0