Skip to content

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.

Get free API keyRead API docs50 evaluation requests, no card. Every call uses 1 request.

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).

recipe_quickstart.py — downloadable Python 3.10+ example
"""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:

Python (httpx)
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 →

EndpointReturned JSON shapeNotes
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: dictIncludes grouped ingredients with ingredient_id UUIDs, phased instructions, and 32 per-serving nutrients.
GET /api/v1/ingredients?q=spinachdata: list[{ id, name, category, source }]Pass returned UUIDs to /api/v1/recipes?ingredients=id1,id2 or /api/v1/ingredients/{id}.
POST /api/v1/generateHTTP 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.

Python — Retry-After helper
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

Do I need a third-party Python SDK to use Recipe API?
No. Recipe API is a standard JSON REST API authenticated with a single X-API-Key header. You can call it with Python's built-in urllib.request, requests, or httpx, and find a ready-to-clone Python starter in github.com/recipe-api/start-here.
How are nulls and missing nutrients represented in Python?
Every recipe returns the same 32 keys inside data['nutrition']['per_serving'], typed as float | None (for example, alcohol_g or caffeine_mg may be None). You never need defensive KeyError checks for the standard 32 nutrient keys.
What timeout should I set in Python for recipe generation?
Normal GET endpoints respond quickly (a 30-second timeout is plenty). POST /api/v1/generate computes the full recipe and nutrition on demand and can take several minutes, so set a dedicated higher timeout on generation calls.
How many requests per minute can a Python script make?
Every plan from Evaluation through Production allows 60 requests/minute (300/min on Scale). Respect the Retry-After header if you receive HTTP 429.

Related guides

Free Recipe API Quickstart
Evaluation limits and a free-tier comparison across recipe APIs.
Recipe to Shopping List API
Deduplicate ingredients by stable UUID across multiple recipes.
Recipe Schema Reference
Exact types and nullability for building Pydantic or dataclass models.

Run the Python quickstart now

Grab a free key (50 evaluation requests, no card) and run recipe_quickstart.py locally with Python 3.10+.