Everyday lifeNutrition
Nutrition API: Calories and Macros from a Meal Described in Plain Words
Nutrition API tutorial: turn a meal typed in any language into calories, macros and 24 nutrients from USDA data with Python, plus barcodes and photos.
In a food logging app, the food picker is where users give up. Logging "150 g grilled chicken, a cup of brown rice, broccoli and a spoon of olive oil" means four searches, four choices among near-identical entries and four portion menus. Users would rather type the sentence. Asking a chatbot for the calories does not fix it: the numbers change from one ask to the next and nobody can say where they came from.
A nutrition API that reads plain text solves the first problem, and one that takes its numbers from a reference database solves the second. This tutorial uses the Nutrition Analysis API: the AI splits the meal into foods and reads the amounts, and every calorie and nutrient comes from USDA FoodData Central, scaled to the grams. We will analyse meals in English and French, search the food database without AI, look up a barcode, try a photo, and build a daily log in Python, with real responses throughout.
Why "AI calories" need a database
A language model is good at reading "a cup of cooked brown rice" and knowing that is one food, one cup. It is bad at remembering that 196 g of cooked brown rice holds 241 kcal, and it will not give the same figure twice. So the work is split:
| Step | Done by | Output |
|---|---|---|
| Split the text into foods, read quantities and units | AI | "brown rice, cooked", 1 cup |
| Find candidate entries | Local search over 13,103 USDA foods | 8 candidates per food |
| Choose an entry and a household portion | AI, validated against the candidates | FDC id 2708409, "1 cup, cooked" |
| Compute grams | Code: stated weight or volume, else count × USDA portion, else estimate | 196 g, and how it was found |
| Compute nutrients | Code: USDA value × grams / 100 | 24 nutrients per food and in total |
If the chosen entry is not one of the candidates, the food goes to unmatched instead of being guessed. No nutrient value is generated by the model.
The data is USDA FoodData Central, in the public domain, from three of its datasets: Foundation (analytical values for basic foods), SR Legacy (the former Standard Reference, 7,000+ foods) and FNDDS (foods "as eaten" in the U.S. dietary survey, with household portions like "1 medium croissant"). Barcodes come from Open Food Facts.
Analyse a meal from text in Python
POST /v1/nutrition/analyze takes the meal as text, in any language. The examples use Python and requests; the API reference lists every field.
import requests
HOST = "nutrition-analysis-calories-macros-from-text.p.rapidapi.com"
API = f"https://{HOST}"
HEADERS = {"x-rapidapi-key": "YOUR_API_KEY", "x-rapidapi-host": HOST}
meal = (
"150 g grilled chicken breast, a cup of cooked brown rice, "
"steamed broccoli and a tablespoon of olive oil"
)
response = requests.post(
f"{API}/v1/nutrition/analyze", headers=HEADERS, json={"text": meal}, timeout=60
)
response.raise_for_status()
result = response.json()
for item in result["items"]:
print(item["name"], item["grams"], item["nutrients"]["calories_kcal"])
print(result["totals"]["calories_kcal"], result["macros"])
The real response took 5.3 seconds. Each item carries all 24 nutrients; they are cut here after the main ones:
{
"language": "en",
"items": [
{
"input": "150 g grilled chicken breast",
"name": "chicken breast, grilled",
"quantity": 150.0,
"unit": "g",
"grams": 150.0,
"grams_source": "stated",
"match": {
"fdc_id": 2705968,
"description": "Chicken breast, grilled without sauce, skin not eaten",
"dataset": "fndds",
"category": "Chicken, whole pieces"
},
"nutrients": { "calories_kcal": 264.0, "protein_g": 44.4, "fat_g": 8.2, "carbs_g": 0.0, "sodium_mg": 530.0, "...": "..." }
},
{
"input": "a cup of cooked brown rice",
"name": "brown rice, cooked",
"quantity": 1.0,
"unit": "cup",
"grams": 196.0,
"grams_source": "stated",
"portion": { "label": "1 cup, cooked", "grams": 196.0 },
"match": { "fdc_id": 2708409, "description": "Rice, brown, cooked, NS as to fat", "dataset": "fndds", "category": "Rice" },
"nutrients": { "calories_kcal": 241.0, "protein_g": 4.8, "fat_g": 2.2, "carbs_g": 50.6, "fiber_g": 2.0, "sodium_mg": 394.0, "...": "..." }
},
{
"input": "steamed broccoli",
"name": "broccoli, steamed",
"grams": 150.0,
"grams_source": "estimated",
"assumption": "Amount not given: one ordinary portion was estimated.",
"match": { "fdc_id": 169967, "description": "Broccoli, cooked, boiled, drained, without salt", "dataset": "sr_legacy", "category": "Vegetables and Vegetable Products" },
"nutrients": { "calories_kcal": 52.5, "protein_g": 3.6, "fat_g": 0.61, "carbs_g": 10.8, "fiber_g": 4.9, "vitamin_c_mg": 97.4, "...": "..." }
},
{
"input": "a tablespoon of olive oil",
"name": "olive oil",
"quantity": 1.0,
"unit": "tbsp",
"grams": 14.0,
"grams_source": "stated",
"portion": { "label": "1 cup", "grams": 224.0 },
"match": { "fdc_id": 2710186, "description": "Olive oil", "dataset": "fndds", "category": "Salad dressings and vegetable oils" },
"nutrients": { "calories_kcal": 126.0, "fat_g": 14.0, "...": "..." }
}
],
"unmatched": [],
"totals": {
"calories_kcal": 684.0,
"protein_g": 52.8,
"fat_g": 25.0,
"carbs_g": 61.4,
"fiber_g": 6.9,
"sugar_g": 2.5,
"sodium_mg": 986.0,
"potassium_mg": 1125.0,
"vitamin_c_mg": 97.4,
"...": "..."
},
"incomplete": [],
"macros": { "protein_pct": 31.0, "carbs_pct": 36.0, "fat_pct": 33.0 },
"total_grams": 510.0,
"source": "USDA FoodData Central (public domain)",
"note": "Estimates for information only, not medical or dietary advice. Nutrient values come from USDA FoodData Central; quantities given without a weight are estimated."
}
Read grams_source before trusting a number
grams_source is the field that tells your users how much to trust each line:
stated: the text gave a weight or a volume. The chicken's 150 g is exact; the rice's cup and the oil's tablespoon are converted with USDA densities, which is why the oil shows the "1 cup, 224 g" portion it was scaled from (224 / 16 = 14 g a tablespoon).portion: a count multiplied by a USDA household portion ("2 eggs" × "1 large egg").estimated: no amount was given, so the model estimated an ordinary portion. "Steamed broccoli" became 150 g, andassumptionsays so in words you can show. Show these lines as editable.
Macros and the calorie split
macros gives the share of calories from protein, carbohydrates and fat (and alcohol when present), with the standard 4, 4, 9 and 7 kcal per gram, normalised to 100 %. Here: 52.8 g of protein × 4 = 211 kcal, 31.0 % of the energy from macronutrients.
Watch the sodium of "as eaten" foods
The chicken carries 530 mg of sodium and the rice 394 mg. FNDDS describes foods as Americans eat them, so cooked rice and grilled chicken include the salt usually added while cooking. That is right for a typical meal and too high for someone who cooks without salt. For a low-sodium diet, use the food search below and pick an unsalted Foundation or SR Legacy entry.
Meals in any language
The text can be in any language the model reads; tested languages include French, Spanish, German, Italian, Portuguese and Japanese. A real French breakfast, "un croissant, un café crème et un yaourt nature":
{
"language": "fr",
"items": [
{
"input": "un croissant",
"name": "croissant",
"grams": 57.0,
"grams_source": "portion",
"portion": { "label": "1 medium croissant", "grams": 57.0 },
"match": { "fdc_id": 2707678, "description": "Croissant", "dataset": "fndds" },
"nutrients": { "calories_kcal": 231.0, "fat_g": 12.0, "carbs_g": 26.1, "...": "..." }
},
{
"input": "un café crème",
"name": "coffee latte",
"quantity": 1.0,
"grams": 240.0,
"grams_source": "portion",
"portion": { "label": "1 cup (8 fl oz)", "grams": 240.0 },
"assumption": "US household portion '1 cup (8 fl oz)' (240 g)",
"match": { "fdc_id": 2710386, "description": "Coffee, Latte", "dataset": "fndds" },
"nutrients": { "calories_kcal": 103.0, "caffeine_mg": 86.4, "...": "..." }
},
{
"input": "un yaourt nature",
"name": "yogurt, plain",
"grams": 125.0,
"grams_source": "estimated",
"assumption": "1 pot taken as 125 g, the usual size where the text was written (USDA's '1 4 oz container' is 113 g)",
"match": { "fdc_id": 2705417, "description": "Yogurt, NS as to type of milk, plain", "dataset": "fndds" },
"nutrients": { "calories_kcal": 78.8, "...": "..." }
}
],
"totals": { "calories_kcal": 413.0, "protein_g": 18.0, "fat_g": 17.8, "carbs_g": 45.3, "caffeine_mg": 86.4, "...": "..." },
"macros": { "protein_pct": 17.4, "carbs_pct": 43.8, "fat_pct": 38.8 }
}
The matches are sensible: a café crème is close to a latte, and a French plain yogurt to a plain yogurt. The portions show the assumption field at work. The yogurt is taken as the 125 g pot usual where the text was written, and the API says it set aside USDA's 113 g U.S. container. The café crème has no local size, so it gets the U.S. cup of 240 g, flagged as a U.S. household portion; a café crème in France is closer to 150-200 ml. Show assumptions so users can correct them, or write the amount ("un café crème de 180 ml").
Search foods and build your own picker
Some screens still need a picker: correcting a match, or logging a single food. GET /v1/nutrition/foods/search searches the USDA table without AI, in English and in USDA's words, for 1 credit:
foods = requests.get(
f"{API}/v1/nutrition/foods/search",
headers=HEADERS,
params={"q": "greek yogurt", "limit": 3},
timeout=30,
).json()["foods"]
for food in foods:
print(food["fdc_id"], food["description"], food["per_100g"]["protein_g"])
The real call returned three entries, one per dataset: "Yogurt, Greek, NS as to type of milk, plain" (FNDDS, 67 kcal and 10.2 g of protein per 100 g, with portions from a 150 g container to a 245 g cup), "Yogurt, Greek, plain, nonfat" (Foundation, 61 kcal) and "Yogurt, Greek, plain, lowfat" (SR Legacy, 73 kcal). Then GET /v1/nutrition/foods/{fdc_id}?grams=170 returns one food with the nutrients of the amount asked:
{
"fdc_id": 330137,
"description": "Yogurt, Greek, plain, nonfat",
"dataset": "foundation",
"category": "Dairy and Egg Products",
"per_100g": { "calories_kcal": 61.0, "protein_g": 10.3, "fat_g": 0.37, "carbs_g": 3.6, "sugar_g": 3.3, "calcium_mg": 111.0, "...": "..." },
"portions": [{ "label": "1 container", "grams": 156.0 }],
"amount": {
"grams": 170.0,
"nutrients": { "calories_kcal": 104.0, "protein_g": 17.5, "fat_g": 0.63, "carbs_g": 6.2, "sugar_g": 5.6, "calcium_mg": 189.0, "...": "..." }
},
"source": "USDA FoodData Central (public domain)"
}
Foundation foods have fewer micronutrients than the other datasets (no folate here); when a meal uses one, the totals that miss a value are listed in incomplete.
Look up packaged foods by barcode
For packaged products, the label is better than any generic entry. GET /v1/nutrition/barcode?code= reads Open Food Facts, for 1 credit. A real call for a 330 ml can of Coca-Cola, shortened:
{
"barcode": "5449000000996",
"name": "Coca-Cola Original",
"brand": "COCA-COLA SERVICES SA/NV",
"quantity": "330 ml",
"serving_size": "1 portion (330 ml)",
"serving_grams": 330.0,
"ingredients": "carbonated water, sugar, colour (caramel e150d), acid (phosphoric acid), natural flavourings, caffeine flavouring,",
"allergens": [],
"nutriscore": "e",
"nova_group": 4,
"per": "100g",
"per_100": { "calories_kcal": 44.0, "carbs_g": 10.9, "sugar_g": 10.9, "sodium_mg": 0.0, "...": "..." },
"per_serving": { "calories_kcal": 145.0, "carbs_g": 36.0, "sugar_g": 36.0, "...": "..." },
"url": "https://world.openfoodfacts.org/product/5449000000996",
"source": "Open Food Facts (openfoodfacts.org), ODbL 1.0"
}
Nutri-Score runs from A to E, and NOVA group 4 marks ultra-processed foods. Open Food Facts data is under the Open Database License, so credit it where you show it; the source field carries the wording. A code that is not 8 to 14 digits returns 400 invalid_barcode, unbilled, and an unknown product 404 product_not_found.
Meal photos
POST /v1/nutrition/analyze/photo takes an image url (or /analyze/photo/upload for a file) and an optional description hint, for 15 credits. Vision estimates the foods and portions, then the same USDA matching runs.
A photo is the least precise input. On a Wikimedia Commons photo of a pizza margherita, the API recognised "pizza margherita with mozzarella and basil", matched it to the FNDDS entry "Pizza, cheese, from restaurant or fast food, thin crust" (generic entries are preferred over branded ones), and estimated the whole pizza at 450 g: 1,197 kcal, with "assumption": "Amount not given: one ordinary portion was estimated.". The weight is a guess from the picture, and every 50 g changes the total by about 130 kcal. Pass a description hint ("one thin-crust margherita, about 350 g") when the user can type one, and let them edit the grams.
Build a daily log
Totals add up across meals because every meal returns the same nutrient keys:
from collections import Counter
meals = {
"breakfast": "2 eggs fried in butter, a slice of toast and a glass of orange juice",
"lunch": meal,
"snack": "a 170 g pot of nonfat greek yogurt",
}
day = Counter()
estimated = []
for name, text in meals.items():
r = requests.post(
f"{API}/v1/nutrition/analyze", headers=HEADERS, json={"text": text}, timeout=60
)
r.raise_for_status()
data = r.json()
day.update({k: v for k, v in data["totals"].items() if v is not None})
estimated += [i["input"] for i in data["items"] if i["grams_source"] == "estimated"]
print(round(day["calories_kcal"]), round(day["protein_g"], 1))
print("to confirm:", estimated)
Keep the fdc_id and grams of each item in your database rather than the totals: if a user corrects a portion, recompute that line with /foods/{fdc_id}?grams=, for 1 credit and no AI. The API also caches identical meal texts for 24 hours.
What it costs
A meal costs 10 credits for up to 5 foods and 2 more per extra food; a photo 15. Search, food lookup and barcode cost 1. Failed calls (4xx, 5xx) use no credits.
| Plan | Price per month | Credits | In practice |
|---|---|---|---|
| BASIC | Free | 20 per day | 2 meals (300 characters each), 1 photo or 20 lookups a day |
| PRO | $4.99 | 8,000 | 800 meals at about $0.006, or 8,000 lookups at $0.0006 |
| ULTRA | $14.99 | 25,000 | 2,500 meals |
| MEGA | $49.99 | 80,000 | 8,000 meals |
Beyond the quota, paid plans continue at $0.007 per credit. In our RapidAPI survey, AI calorie APIs charged $0.01 to $0.0125 per analysis and barcode APIs $0.004 to $0.02 per lookup.
What the nutrition API does not do
- No exact portions without amounts. Unstated quantities and photos are estimates of an ordinary portion. Weights in the text give USDA's exact value for that weight.
- A U.S. reference. USDA describes American foods and preparations. Regional dishes it lacks (Schnitzel, muesli, carbonara) are counted through their ingredients, flagged with
part_of; branded products are better served by their barcode. - English food search.
/foods/searchuses USDA's English descriptions; meal analysis accepts any language. - No medical or dietary advice. Every response says so. The numbers support logging and wellness features, not diagnosis or prescriptions.
- No recipes per serving from a URL. Send the ingredient list as text; the API does not read recipe pages.
- No storage. Helenis does not keep meal texts or photos; your app owns the log.
For the training side of a fitness app, the companion exercise database and AI workout plan tutorial covers 870+ exercises and plans built from them.
Frequently asked questions
Is there a free nutrition API?
USDA FoodData Central has a free API for its own data, and Open Food Facts is free for barcodes. Neither reads a meal written in plain words. This API's BASIC plan is free with 20 credits a day: two typed meals, one photo, or 20 food and barcode lookups.
How accurate are the calorie counts?
As accurate as the grams. With weights in the text, the values are USDA's for that weight. Counts use USDA household portions. Unstated amounts and photos are estimates, marked estimated with an assumption you can show, and a photo's weight can be off by a large margin.
Does the AI make up nutrient values?
No. The model splits the meal and picks among database candidates; every value is USDA's figure scaled to the grams. A food with no credible match is listed in unmatched and left out of the totals.
Can it count calories from a photo?
Yes, with /analyze/photo for 15 credits. Portions are estimated by vision, so photos suit quick logging; for precise tracking, ask users to confirm the matched food and the grams.
Which barcodes are supported?
EAN-8, UPC-A, EAN-13 and GTIN-14 codes found in Open Food Facts, with nutrients per 100 g and per serving, Nutri-Score, NOVA group, allergens and ingredients.
What is the difference between Foundation, SR Legacy and FNDDS?
Foundation holds recent laboratory values for basic foods; SR Legacy is the former Standard Reference database, frozen in 2018; FNDDS describes foods as eaten in the U.S. dietary survey, with household portions. The API searches all three and returns the dataset of each match.
Get started
Nutrition Analysis API
Calories, macros and 24 nutrients of any meal, from words in any language or a photo. USDA data.
- Nutrition
- Calorie Counter
- Health Tech
- Python
- Open Data


