Skip to content

Streaming ​

A big plate can take a minute to scan. Add "stream": true to the request and the same call answers at once with text/event-stream. The items the photo shows arrive after about 10 to 15 seconds, and the full result follows when it is ready. Show the items to your user while the numbers load.

bash
curl -N https://platform-api.nutriscan.app/v1/scans \
  -H "Authorization: Bearer $NUTRISCAN_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "type": "meal", "image_url": "https://example.com/lunch.jpg", "stream": true }'

The stream looks like this:

text
event: scan.started
data: {"id":"scn_8Kd2…","status":"processing"}

event: items.detected
data: {"id":"scn_8Kd2…","dish_name":"Tofu salad bowl","items":[{"name":"Tofu","portion":"100 g"}, …]}

: ping

event: scan.completed
data: { …the same JSON as a normal response… }

Events ​

EventWhenData
scan.startedAt onceThe scan id. Keep it: if the connection drops, the scan still finishes and GET /v1/scans/{id} returns it.
items.detectedAfter about 10 to 15 sdish_name and items with name and portion. A first look: the final result can rename, add or drop items.
scan.completedWhen doneThe full result, the same JSON as without streaming.
errorInstead of scan.completed{"status": 422 or 500, "error": {"code", "message"}}, for example no_food_detected.
: pingEvery 15 sA comment line that keeps the connection open. Ignore it.

What still comes back as plain JSON ​

Errors found before the scan starts come back as a normal JSON error with their status code, not as a stream: a bad key, a bad body, the rate limit, or too few credits. Check the response status and Content-Type before you start reading events.

A streamed scan can run up to 140 seconds and uses the same credits as a normal call.

Reading the stream in code ​

Browsers' EventSource only does GET, so read the response body yourself. These examples run on your server.

js
const resp = await fetch("https://platform-api.nutriscan.app/v1/scans", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.NUTRISCAN_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ type: "meal", image_url: "https://example.com/lunch.jpg", stream: true }),
  signal: AbortSignal.timeout(150_000), // a streamed scan can run up to 140 seconds
});
if (!resp.headers.get("content-type")?.startsWith("text/event-stream")) {
  throw new Error((await resp.json()).error.code); // rejected before the scan started
}

const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of resp.body) {
  buffer += decoder.decode(chunk, { stream: true });
  let end;
  while ((end = buffer.indexOf("\n\n")) !== -1) {
    const block = buffer.slice(0, end);
    buffer = buffer.slice(end + 2);
    const event = block.match(/^event: (.+)$/m)?.[1];
    const data = block.match(/^data: (.+)$/m)?.[1];
    if (!event || !data) continue; // ": ping" comments land here
    const payload = JSON.parse(data);
    if (event === "items.detected") console.log("Items:", payload.items.map((i) => i.name));
    if (event === "scan.completed") console.log("Done:", payload.meal.totals.calories, "kcal");
    if (event === "error") console.error(payload.status, payload.error.code);
  }
}
python
import json, os, requests

resp = requests.post(
    "https://platform-api.nutriscan.app/v1/scans",
    headers={"Authorization": f"Bearer {os.environ['NUTRISCAN_KEY']}"},
    json={"type": "meal", "image_url": "https://example.com/lunch.jpg", "stream": True},
    stream=True,
    timeout=150,  # a streamed scan can run up to 140 seconds
)
if not resp.headers.get("content-type", "").startswith("text/event-stream"):
    raise RuntimeError(resp.json()["error"]["code"])  # rejected before the scan started

event = None
for line in resp.iter_lines(decode_unicode=True):
    if line.startswith("event: "):
        event = line[7:]
    elif line.startswith("data: ") and event:
        payload = json.loads(line[6:])
        if event == "items.detected":
            print("Items:", [i["name"] for i in payload["items"]])
        elif event == "scan.completed":
            print("Done:", payload["meal"]["totals"]["calories"], "kcal")
        elif event == "error":
            print("Error:", payload["status"], payload["error"]["code"])

What happens if the stream drops? ​

The scan keeps running on our side, and you are not charged a second time. Keep the id from scan.started, wait a moment, then call GET /v1/scans/{id} to collect the finished result.

When should you use streaming? ​

Use streaming when a person waits on a screen for the result, and a plain call for background jobs.

  • Use it when a person is waiting on a screen. The detected items give them something to look at, and they can spot a wrong item early.
  • Skip it for background jobs. A plain call with a 100 second timeout is simpler.

Related pages: create a scan for every request field, the result for the fields in scan.completed, Nutrition API pricing for credit costs and the Nutrition API overview.