import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/nutrition',
params={'query': '1 large apple'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Prerequisites
- Python 3.7+ installed
- The
requestslibrary (pip install requests) - A free API Ninjas API key
Step 1: Get your API key
Sign up at api-ninjas.com/register.
Step 2: Make the API request
import requests
API_KEY = 'YOUR_API_KEY'
response = requests.get(
'https://api.api-ninjas.com/v1/nutrition',
params={'query': '1 large apple'},
headers={'X-Api-Key': API_KEY},
)
print(response.json())Step 3: Use the response
[
{
"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
}
]Complete example: meal-calorie tracker
import os
import requests
API_KEY = os.environ['API_NINJAS_KEY']
URL = 'https://api.api-ninjas.com/v1/nutrition'
def get_nutrition(query: str) -> list:
response = requests.get(
URL,
params={'query': query},
headers={'X-Api-Key': API_KEY},
timeout=10,
)
response.raise_for_status()
return response.json()
def total_calories(items: list) -> float:
return sum(item.get('calories', 0) for item in items)
if __name__ == '__main__':
meal = get_nutrition('2 eggs and 1 slice of toast')
for item in meal:
print(f"{item['name']:25} {item['calories']:>6.1f} kcal")
print(f"{'Total':25} {total_calories(meal):>6.1f} kcal")Natural-language queries
The API parses quantities and units from plain English:
# The query parameter accepts natural language
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)
cals = total_calories(items)
print(f"{q:40} {cals:>6.1f} kcal")Aggregating macronutrients
Sum protein, carbs, and fat across all items returned by a query:
meal = get_nutrition('1 cup of cooked oatmeal with milk')
totals = {'protein': 0, 'carbohydrates_total_g': 0, 'fat_total_g': 0}
for item in meal:
for key in totals:
totals[key] += item.get(key, 0)
print(f"Protein: {totals['protein']:.1f}g")
print(f"Carbs: {totals['carbohydrates_total_g']:.1f}g")
print(f"Fat: {totals['fat_total_g']:.1f}g")Related APIs
For fitness apps, pair Nutrition with Calories Burned and Exercises. For recipe ideas use Recipe.