Skip to content

Errors ​

Every error has the same body:

json
{ "error": { "code": "insufficient_credits", "message": "…" } }

Branch on code. The message is written for people and can change; it names the field when a request is malformed.

All errors ​

StatusCodeWhat to do
400invalid_request, invalid_image, image_too_large, image_url_unreachableFix the request. The message names the field.
401invalid_api_keyCheck the key and the Bearer prefix.
402insufficient_creditsBuy credits in the console. A scan needs 20 credits to start.
403key_revoked, account_suspendedCreate a new key in the console, or email support@nutriscan.app.
409idempotency_conflict, idempotency_mode_conflict, idempotency_in_progressUse a new Idempotency-Key for a new body or for the other key mode, or retry shortly.
413request_too_largeSend an image of 10 MB or less, in a body of 14.5 MB or less.
422no_food_detectedNothing to scan. Charged for the work it used, at least 20 credits; the message says how many.
429rate_limited, platform_busyrate_limited: over 60 scans a minute; wait for Retry-After (60 seconds). platform_busy: the service is at capacity; retry after a short wait.
500scan_failedRetry. A failed scan costs 0 credits.
503platform_unavailableRetry later.

Which errors should you retry? ​

Retry 429, 500, 503 and 409 idempotency_in_progress. Do not retry the other 4xx errors, and top up before you retry a 402.

  • Retry: 429 after Retry-After, 500 scan_failed, 503 platform_unavailable with a growing wait, and 409 idempotency_in_progress after a few seconds.
  • Do not retry: 400, 401, 403, 413 and 422. The same request will fail the same way. For 422 no_food_detected, ask the user for a new photo.
  • Fix the balance first: 402. Retrying before a top-up returns 402 again.

Send an Idempotency-Key on every scan so a retry with the same body uses credits once. If the first try failed with 402 or 500, the same key runs a fresh scan, so you can keep it across retries.

Errors in a stream ​

With "stream": true, errors found before the scan starts (a bad key, a bad body, the rate limit, too few credits) still come back as a plain JSON error with a status code. An error during the scan arrives as an error event in place of scan.completed:

text
event: error
data: {"status": 422, "error": {"code": "no_food_detected", "message": "…"}}

See streaming.

A handler ​

python
import os, time, requests

RETRY = {429, 500, 503}

def scan(body, idempotency_key, attempts=4):
    for attempt in range(attempts):
        resp = requests.post(
            "https://platform-api.nutriscan.app/v1/scans",
            headers={
                "Authorization": f"Bearer {os.environ['NUTRISCAN_KEY']}",
                "Idempotency-Key": idempotency_key,
            },
            json=body,
            timeout=100,
        )
        if resp.ok:
            return resp.json()
        code = resp.json()["error"]["code"]
        if resp.status_code in RETRY or code == "idempotency_in_progress":
            time.sleep(int(resp.headers.get("Retry-After", 2 ** attempt)))
            continue
        raise RuntimeError(f"{resp.status_code} {code}")
    raise RuntimeError("gave up after retries")
js
const RETRY = new Set([429, 500, 503]);

async function scan(body, idempotencyKey, attempts = 4) {
  for (let attempt = 0; attempt < attempts; attempt++) {
    const resp = await fetch("https://platform-api.nutriscan.app/v1/scans", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.NUTRISCAN_KEY}`,
        "Content-Type": "application/json",
        "Idempotency-Key": idempotencyKey,
      },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(100_000),
    });
    const json = await resp.json();
    if (resp.ok) return json;
    const code = json.error.code;
    if (RETRY.has(resp.status) || code === "idempotency_in_progress") {
      const wait = Number(resp.headers.get("retry-after")) || 2 ** attempt;
      await new Promise((r) => setTimeout(r, wait * 1000));
      continue;
    }
    throw new Error(`${resp.status} ${code}`);
  }
  throw new Error("gave up after retries");
}

What to show your users ​

  • 422 no_food_detected: "We could not find food in this photo. Try again with the plate in the frame."
  • 402 insufficient_credits: this is your account, not theirs. Alert your team and show a neutral "Scanning is paused, try again soon."
  • 429 and 503: retry quietly in the background before you show anything.

Related pages: the result for the success response, limits for the numbers behind 413 and 429, Nutrition API pricing for what a 422 costs and the Nutrition API overview.