Tilman Nathaniel
Tilman Nathaniel

Reputation: 11

Use USDA Food API to search by food name instead of foodID

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')

Upvotes: 1

Views: 3204

Answers (1)

Nicolas M.
Nicolas M.

Reputation: 1478

Based on the API documentation (I don't have a key to test it), you can query by keyword using the endpoint:

GET Method

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

POST Method

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

I'd also recommend to use string formatting when you are making concatenation such as this one. It makes the code easier to read ;). Even better, it you are in python 3.6+, the F-string. (But this is a must have)

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

EDIT:

With basic stringg creation, it is:

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

With string formatting, it is:

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

With f-string, it is:

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

EDIT 2

This works for me

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")

You can find also some information about string formatting on https://pyformat.info/ (you should avoid %s anymore, it is depreciated)

I hope it helps,

Upvotes: 2

Related Questions