Code examples

Copy-paste snippets for the public AllNutrition API in popular languages.

POST /api/v1/ask

curl -X POST https://www.allnutrition.info/api/v1/ask \
  -H "Content-Type: application/json" \
  -d '{
    "question": "Is creatine safe for adolescents who lift weights?"
  }'
import httpx

resp = httpx.post(
    "https://www.allnutrition.info/api/v1/ask",
    json={"question": "Is creatine safe for adolescents who lift weights?"},
    timeout=60,
)
resp.raise_for_status()
data = resp.json()

print(data["answer"])
for src in data["sources"]:
    print(f"- {src['title']} ({src['publisher']}, {src['evidence_level']})")
    print(f"  {src['url']}")
const r = await fetch("https://www.allnutrition.info/api/v1/ask", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    question: "Is creatine safe for adolescents who lift weights?",
  }),
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const data = await r.json();
console.log(data.answer);
data.sources.forEach((s) =>
  console.log(`- ${s.title} (${s.publisher}, ${s.evidence_level})`)
);
type EvidenceStrength = "strong" | "moderate" | "limited" | "insufficient";
type ConsensusLevel = "high" | "moderate" | "mixed" | "low";

interface Source {
  id: string;
  title: string;
  url: string | null;
  publisher: string;
  publisher_short_name: string | null;
  evidence_level: "guideline" | "systematic_review" | "rct" | "observational" | "expert_opinion" | "review";
  trust_score: number;
  published_at: string | null;
  excerpt: string;
  passage: string | null;
}

interface AskResponse {
  question: string;
  answer: string;
  evidence_strength: EvidenceStrength;
  consensus_level: ConsensusLevel;
  last_updated: string | null;
  sources: Source[];
}

export async function askNutrition(question: string): Promise<AskResponse> {
  const r = await fetch("https://www.allnutrition.info/api/v1/ask", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ question }),
  });
  if (!r.ok) throw new Error(`HTTP ${r.status}: ${await r.text()}`);
  return r.json();
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    body, _ := json.Marshal(map[string]string{
        "question": "Is creatine safe for adolescents who lift weights?",
    })
    resp, err := http.Post(
        "https://www.allnutrition.info/api/v1/ask",
        "application/json",
        bytes.NewReader(body),
    )
    if err != nil { panic(err) }
    defer resp.Body.Close()
    out, _ := io.ReadAll(resp.Body)
    fmt.Println(string(out))
}

POST /api/v1/references/search

Use this when you want citations without an LLM-generated answer.

curl -X POST https://www.allnutrition.info/api/v1/references/search \
  -H "Content-Type: application/json" \
  -d '{
    "query": "intermittent fasting weight loss",
    "max_results": 5
  }'
import httpx

resp = httpx.post(
    "https://www.allnutrition.info/api/v1/references/search",
    json={"query": "intermittent fasting weight loss", "max_results": 5},
    timeout=30,
)
data = resp.json()
for src in data["results"]:
    print(f"{src['title']} — {src['publisher']} ({src['evidence_level']})")
    print(f"  trust={src['trust_score']:.2f}  url={src['url']}")
const r = await fetch("https://www.allnutrition.info/api/v1/references/search", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ query: "intermittent fasting weight loss", max_results: 5 }),
});
const { results } = await r.json();
results.forEach(s => console.log(`${s.title} — ${s.publisher}`));

Handling rate limits

Read the headers on every response and pause when remaining hits zero.

import httpx, time

with httpx.Client(timeout=60) as client:
    while True:
        r = client.post(
            "https://www.allnutrition.info/api/v1/ask",
            json={"question": "How much fibre should adults eat per day?"},
        )
        if r.status_code == 429:
            wait = int(r.headers.get("Retry-After", "60"))
            print(f"Rate limited. Sleeping {wait}s.")
            time.sleep(wait)
            continue

        r.raise_for_status()
        print(r.json()["answer"])

        remaining = int(r.headers.get("RateLimit-Remaining", "1"))
        if remaining <= 0:
            break
        time.sleep(1)