NewConnect Claude, Gemini, ChatGPT, and other AI agents to API Ninjas via our MCP server

How to Get Nutrition Data in Python

Nutrition APIUpdated August 28, 2026
Create a free API key and it will be pre-filled into every code sample on this page. No credit card required.
Getting nutrition data in Python takes one GET request to the Nutrition API — and the query is plain English, like 1 large apple or 200g chicken breast. No food-ID lookups, no database dumps. This guide covers the request, the response fields, and building a small meal-calorie tracker on top.

Prerequisites

You need three things:

  • Python 3.8 or newer.
  • The requests library.
  • A free API Ninjas API key — issued instantly, no credit card. If you already have an account, it's on your profile page.
shell
pip install requests

Step 1: Look up your first food

The endpoint is /v1/nutrition and takes one parameter: query, a natural-language description of the food:

nutrition.py
import requests response = requests.get( 'https://api.api-ninjas.com/v1/nutrition', params={'query': '1 large apple'}, headers={'X-Api-Key': 'YOUR_API_KEY'}, timeout=10, ) response.raise_for_status() items = response.json() for item in items: print(f"{item['name']}: {item['calories']} kcal") # apple: 95.2 kcal

The request on the wire and the full response:

api.api-ninjas.com
GET/v1/nutrition?query=1 large apple
200 OKapplication/json
[ { "name": "apple", "calories": 95.2, "serving_size_g": 182, "fat_total_g": 0.3, "fat_saturated_g": 0.1, "protein_g": 0.5, "sodium_mg": 2, "potassium_mg": 195, "cholesterol_mg": 0, "carbohydrates_total_g": 25.1, "fiber_g": 4.4, "sugar_g": 18.9 } ]

Step 2: Read the response

The response is always a list, one entry per recognized food — because a single query can name several. Each entry carries the calorie count, the parsed serving_size_g, macros in grams (protein_g, carbohydrates_total_g, fat_total_g, plus fiber_g and sugar_g), and minerals in milligrams (sodium_mg, potassium_mg, cholesterol_mg). Note the quantity handling in the sample above: “1 large apple” became a 182-gram serving, and every value is scaled to it.

Wrapped as a reusable client with the key in an environment variable:

nutrition_client.py
import os import requests API_URL = 'https://api.api-ninjas.com/v1/nutrition' session = requests.Session() session.headers['X-Api-Key'] = os.environ.get('API_NINJAS_KEY', 'YOUR_API_KEY') def get_nutrition(query: str) -> list: """Return nutrition data for a natural-language food query.""" response = session.get(API_URL, params={'query': query}, timeout=10) response.raise_for_status() return response.json() for item in get_nutrition('200g chicken breast'): print(f"{item['name']}: {item['calories']} kcal, {item['protein_g']}g protein")

Step 3: Query in plain English

The query parser is the reason this API is pleasant to build on: it understands cups, grams, slices, and multiple foods joined with “and” — so user input can go straight through:

queries.py
queries = [ '1 cup of rice', '200g chicken breast', 'a slice of cheese pizza', '1 banana and 2 tablespoons of peanut butter', ] for q in queries: items = get_nutrition(q) total = sum(item['calories'] for item in items) print(f'{q:45} {total:>7.1f} kcal ({len(items)} item(s))')

Step 4: Build a meal tracker

A meal is just a multi-food query, so totals are a sum over the returned list. This helper aggregates calories and the three macros:

meal.py
def meal_totals(query: str) -> dict: """Sum calories and macros across every food in one query.""" items = get_nutrition(query) totals = {'calories': 0.0, 'protein_g': 0.0, 'carbohydrates_total_g': 0.0, 'fat_total_g': 0.0} for item in items: for key in totals: totals[key] += item.get(key, 0) return totals meal = meal_totals('2 eggs, 1 slice of toast, and 1 cup of orange juice') print(f"Calories: {meal['calories']:.0f} kcal") print(f"Protein: {meal['protein_g']:.1f} g") print(f"Carbs: {meal['carbohydrates_total_g']:.1f} g") print(f"Fat: {meal['fat_total_g']:.1f} g")

Log the totals to a CSV or SQLite table with a date column and you have a personal food diary in an afternoon.

Step 5: Handle errors

The important quirk: an unrecognized food is not an HTTP error — the API returns an empty list. Check for it separately from the usual auth and rate-limit failures:

errors.py
from requests.exceptions import HTTPError, RequestException items = get_nutrition('flurbles') # unknown food if not items: print('No foods recognized — rephrase the query') try: items = get_nutrition('1 cup of rice') except HTTPError as error: status = error.response.status_code if status == 401: print('Missing or invalid API key') elif status == 429: print('Rate limit exceeded — slow down and retry') else: print(f'HTTP {status}: {error.response.text}') except RequestException as error: print(f'Network error: {error}')

Where to go from here

For a fitness app, pair this with the Calories Burned API (the expenditure side of the ledger) and the Exercises API; for meal ideas, the Recipe API searches by ingredient. The complete command-line tracker is below.

meal_tracker.py

The complete script from this guide: pass a meal description on the command line, get a per-food and total breakdown.

Frequently asked questions

What kinds of queries does the API accept?

Natural language with quantities: "1 cup of rice", "200g chicken breast", "2 eggs and 1 slice of toast". The parser extracts each food and its amount automatically.

Why is the response a list instead of a single object?

One query can contain several foods — "a banana and 2 tablespoons of peanut butter" returns two entries. Sum across the list for meal totals.

What units does the API return?

Calories in kilocalories, macronutrients (protein, carbohydrates, fat, fiber, sugar) in grams, and minerals like sodium and potassium in milligrams. Serving size is in grams.

Does the API cover branded foods?

It covers generic foods — "a slice of cheese pizza" returns typical values rather than a specific restaurant recipe. That is usually what calorie tracking needs.

What happens when a food is not recognized?

The API returns an empty list rather than an error. Check for it and prompt for a rephrase — usually adding a quantity or simplifying the food name fixes it.