Python Tutorial
Python Recipe API Tutorial: Search, Macros & Typed Models
Call Recipe API from Python in under two minutes — filter 25,000+ recipes by calories, protein, and dietary flags, unpack 32 USDA-backed nutrients into typed dataclasses, and handle quotas cleanly.
1. Zero-dependency Python script (stdlib only)
Download recipe_quickstart.py, set RECIPE_API_KEY, and run python3 recipe_quickstart.py. It requires Python 3.10+, installs zero packages, and uses 2 requests (1 filtered search + 1 full recipe detail).
"""Python 3.10+ quickstart for Recipe API (stdlib only — no pip install needed).
Run:
RECIPE_API_KEY=rapi_your_key python3 recipe_quickstart.py
Uses 2 requests: 1 filtered search + 1 full recipe lookup.
Never place your API key in client-side code or a public repository.
"""
from __future__ import annotations
from dataclasses import dataclass
import json
import os
import sys
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
BASE_URL = "https://recipe-api.com/api/v1"
@dataclass(frozen=True)
class RecipeCard:
id: str
name: str
cuisine: str | None
calories: float | None
protein_g: float | None
def api_get(path: str, api_key: str, params: dict[str, str | int] | None = None) -> dict:
url = f"{BASE_URL}/{path.lstrip('/')}"
if params:
url = f"{url}?{urlencode(params)}"
req = Request(url, headers={"X-API-Key": api_key, "Accept": "application/json"})
try:
with urlopen(req, timeout=30) as response:
return json.loads(response.read().decode("utf-8"))
except HTTPError as err:
retry_after = err.headers.get("Retry-After")
hint = f" Retry after {retry_after}s." if retry_after else " Check your key and quota."
raise RuntimeError(f"Recipe API returned HTTP {err.code}.{hint}") from err
def search_high_protein_dinners(api_key: str) -> list[RecipeCard]:
payload = api_get(
"recipes",
api_key,
{
"category": "Dinner",
"max_calories": 600,
"min_protein": 30,
"per_page": 5,
},
)
cards: list[RecipeCard] = []
for item in payload.get("data", []):
summary = item.get("nutrition_summary") or {}
cards.append(
RecipeCard(
id=item["id"],
name=item["name"],
cuisine=item.get("cuisine"),
calories=summary.get("calories"),
protein_g=summary.get("protein_g"),
)
)
return cards
def main() -> None:
api_key = os.environ.get("RECIPE_API_KEY")
if not api_key:
print("Set RECIPE_API_KEY before running this script.", file=sys.stderr)
sys.exit(1)
cards = search_high_protein_dinners(api_key)
if not cards:
print("No recipes matched those filters.")
return
detail = api_get(f"recipes/{cards[0].id}", api_key)
recipe = detail["data"]
per_serving = recipe["nutrition"]["per_serving"]
output = {
"matches": [card.__dict__ for card in cards],
"selected": {
"id": recipe["id"],
"name": recipe["name"],
"yields": recipe["meta"]["yields"],
"calories": per_serving["calories"],
"protein_g": per_serving["protein_g"],
"iron_mg": per_serving["iron_mg"],
"ingredient_groups": len(recipe["ingredients"]),
"steps": len(recipe["instructions"]),
},
"usage": detail.get("usage"),
}
print(json.dumps(output, indent=2))
if __name__ == "__main__":
main()
2. Using httpx with connection pooling
In a FastAPI, Django, or data pipeline backend, reuse an httpx.Client (or requests.Session) so your X-API-Key header and TLS connections stay pooled across requests:
import os
import httpx
BASE_URL = "https://recipe-api.com/api/v1"
with httpx.Client(
base_url=BASE_URL,
headers={"X-API-Key": os.environ["RECIPE_API_KEY"]},
timeout=30.0,
) as client:
# 1. Search by dietary flag and macro bounds (1 request)
search = client.get(
"/recipes",
params={
"dietary": "Gluten-Free",
"max_calories": 600,
"min_protein": 30,
"per_page": 10,
},
)
search.raise_for_status()
cards = search.json()["data"]
# 2. Fetch one recipe's full ingredients, steps, and 32 nutrients (1 request)
if cards:
detail = client.get(f"/recipes/{cards[0]['id']}")
detail.raise_for_status()
payload = detail.json()
recipe = payload["data"]
print(recipe["name"], recipe["nutrition"]["per_serving"]["protein_g"])3. Key endpoints for Python apps
Every endpoint uses the same base URL (https://recipe-api.com/api/v1) and authentication header. Check /schema for the complete field contract when defining Pydantic models.
Swipe table horizontally →
| Endpoint | Returned JSON shape | Notes |
|---|---|---|
GET /api/v1/recipes?q=&category=&cuisine=&dietary= | data: list[dict] (cards + nutrition_summary) | Use min_calories, max_calories, min_protein, max_protein, min_carbs, max_carbs, min_fat, max_fat. |
GET /api/v1/recipes/{id} | data: dict (full Recipe) + usage: dict | Includes grouped ingredients with ingredient_id UUIDs, phased instructions, and 32 per-serving nutrients. |
GET /api/v1/ingredients?q=spinach | data: list[{ id, name, category, source }] | Pass returned UUIDs to /api/v1/recipes?ingredients=id1,id2 or /api/v1/ingredients/{id}. |
POST /api/v1/generate | HTTP 201 { data: Recipe, usage } | Uses 1 generate credit and can take several minutes — pass a generous timeout (e.g., timeout=600). |
4. Handling 429 rate limits and usage quotas
Recipe detail and generation responses return a usage object showing remaining daily, monthly, and generation allowances. On burst limits (60 requests/min on most plans), honor the Retry-After header — and cache fetched recipes within your plan's caching window.
import time
import httpx
def fetch_with_backoff(client: httpx.Client, path: str, params: dict | None = None) -> dict:
response = client.get(path, params=params)
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", "60"))
# Only retry short per-minute bursts; surface monthly/daily cap errors.
if retry_after <= 60:
time.sleep(retry_after)
response = client.get(path, params=params)
response.raise_for_status()
return response.json()Want a full starter project? Clone the Python template in github.com/recipe-api/start-here.
Frequently asked questions
Related guides
Run the Python quickstart now
Grab a free key (50 evaluation requests, no card) and run recipe_quickstart.py locally with Python 3.10+.