1

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')
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
  • Does this API have any documentation? The answer is most likely there – ForceBru Jun 14 '20 at 20:05
  • yeah, but I didn't get how to use it. it's a bit confusing for a beginner. the API example I posted I found on Github. https://fdc.nal.usda.gov/api-spec/fdc_api.html#/FDC/getFoodsSearch – Tilman Nathaniel Jun 15 '20 at 04:04

1 Answers1

2

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,

Nicolas M.
  • 1,472
  • 1
  • 13
  • 26
  • Thanks! What do you mean by use F-string? I'm not very familiar with it and from the examples I looked at I couldn't tell how I would apply it. – Tilman Nathaniel Jun 15 '20 at 04:03
  • I've made an update regarding string formatting even if it out of the scope of the question. If your question is solved, don't forget to accept it ;). – Nicolas M. Jun 15 '20 at 06:55
  • hmm I keep getting this error every way I try it (with and without json loads, with and without .text at the end, using each of your examples). you got it to work like that? {'timestamp': '2020-06-15T21:19:51.420+0000', 'status': 500, 'error': 'Internal Server Error', 'message': 'all shards failed', 'path': '/portal-data/api/v1/foods/search'} – Tilman Nathaniel Jun 15 '20 at 21:23
  • one question how do you put serving size in that? – James Apr 08 '21 at 22:37