Skip to content

Working with Nutrition Data in Python

Python is a common consumer of nutrition data for meal-plan generation, analytics, and ML features. This guide sets up a resilient client with requests, then loads results into pandas for macro analysis.

A session with retries

client.py
import os
import requests
from requests.adapters import HTTPAdapter, Retry

API_BASE = "https://calorieapiadmin.com/api/v1"

session = requests.Session()
session.headers["X-API-Key"] = os.environ["CALORIE_API_KEY"]
# Retry transient failures; 429 respects Retry-After / reset headers
session.mount(
    "https://",
    HTTPAdapter(max_retries=Retry(total=3, backoff_factor=1, status_forcelist=[429, 500])),
)

def search_foods(q: str, limit: int = 30, skip: int = 0, verified_only: bool = False):
    res = session.get(
        f"{API_BASE}/search/foods",
        params={"q": q, "limit": limit, "skip": skip, "verified_only": verified_only},
        timeout=10,
    )
    res.raise_for_status()
    return res.json()

Paginating a full result set

Iterate pages
def iter_foods(q: str, page_size: int = 100):
    skip = 0
    while True:
        page = search_foods(q, limit=page_size, skip=skip)
        yield from page["data"]
        skip += page_size
        if skip >= page["total"]:
            break

Macro analysis with pandas

Analyze verified results
import pandas as pd

rows = list(iter_foods("yogurt"))
df = pd.DataFrame(rows)[["name", "brand", "calories", "protein", "carbs", "fat"]]

# Protein density per 100 kcal, useful for ranking meal-plan candidates
df["protein_per_100kcal"] = df["protein"] / df["calories"] * 100
print(df.sort_values("protein_per_100kcal", ascending=False).head(10))

Quota-aware batch work

  • Use verified_only=true for analysis jobs, curated macro data avoids cleaning noisy label entries.
  • Persist food details by ID between runs; IDs are stable and re-fetching is pure quota spend.
  • Keep batch jobs focused on the foods your product uses, not the entire catalog.

Frequently asked questions

Is there an official Python SDK?

The API is plain REST + JSON, so requests (or httpx) with a session as shown covers everything. The paginated envelope and stable IDs make client code short.

Can I export the whole database for offline analysis?

No, bulk export is blocked by the 5% monthly coverage cap. Work against the foods your application actually references, and cache those locally.

Related resources