クイックスタート
このページでは、アカウントがない状態から、スキャンが動くところまでを進めます。必要なものはターミナルです。コードで試す場合は、requests を入れたPython 3、またはNode 18以降も使います。
1. テストキーを取得する
platform.nutriscan.app にアクセスし、メールアドレスでサインインします。6桁のコードがメールで届き、アカウントはその場で作られます。新しいアカウントには、テストキーが無料で付いてきます。
テストキー(ns_test_ で始まります)をコピーして、環境変数に設定します。
export NUTRISCAN_KEY="ns_test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"テストキーは固定のサンプル結果を返し、クレジットは使いません。サンプルは、グリルチキンにライスとサラダを添えた1皿で、NutriScoreはB、515 kcalです。ライブのスキャンと同じJSON形式なので、ここで作ったものは、あとでそのまま動きます。
2. スキャンを送る
食事の写真をURLで送ります。画像は公開された https のURLに置いてください。取得は1回だけです。
curl 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", "language": "en" }'import os
import 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", "language": "en"},
timeout=100, # a scan can take up to 95 seconds
)
scan = resp.json()
if resp.status_code != 200:
raise RuntimeError(f"{resp.status_code} {scan['error']['code']}: {scan['error']['message']}")
print(scan["meal"]["name"], scan["meal"]["nutri_score"], scan["meal"]["totals"]["calories"])// Node 18 or newer: fetch is built in
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", language: "en" }),
signal: AbortSignal.timeout(100_000), // a scan can take up to 95 seconds
});
const scan = await resp.json();
if (!resp.ok) throw new Error(`${resp.status} ${scan.error.code}: ${scan.error.message}`);
console.log(scan.meal.name, scan.meal.nutri_score, scan.meal.totals.calories);テストキーでは Grilled chicken with rice and salad B 515 と出力されます。
URLの代わりにファイルをアップロードする
写真が自社のサーバーにあって公開されていない場合は、image_url の代わりに、base64にして image_base64 で送ります。どちらか一方だけを送り、両方は送らないでください。
import base64
with open("lunch.jpg", "rb") as f:
image_b64 = base64.b64encode(f.read()).decode()
resp = requests.post(
"https://platform-api.nutriscan.app/v1/scans",
headers={"Authorization": f"Bearer {os.environ['NUTRISCAN_KEY']}"},
json={"type": "meal", "image_base64": image_b64},
timeout=100,
)import { readFile } from "node:fs/promises";
const image_base64 = (await readFile("lunch.jpg")).toString("base64");
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_base64 }),
signal: AbortSignal.timeout(100_000),
});JPEG、PNG、WebPは10 MBまで使えます。HEICにはまだ対応していません。iPhoneの写真は、端末側で変換してから送ってください。
3. 結果を読む
多くのアプリが最初に表示するフィールドは次のとおりです。
meal.nameとmeal.nutri_score。meal.nutri_score_reasonは1行の説明です。meal.totals.calories、protein_g、carbs_g、fat_g。items[]。それぞれにname、portion.display(たとえば"1 cup (158 g)")、caloriesがあります。
すべてのフィールドは結果にまとめています。
4. 本番に切り替える
テストキーで連携が動いたら、次の手順に進みます。
- コンソールでクレジットパックを購入します(料金をご覧ください)。
- ライブキーを作成します。
ns_live_で始まります。 - サーバーの環境にあるテストキーを置き換えます。コードの変更は不要です。
ライブの結果には credits_used が加わり、末尾に usage.credits_left が付くので、残高を見ながら進められます。
次のステップ
- 量の多い皿は時間がかかります。ストリーミングを使うと、検出したアイテムを約10〜15秒後に表示できます。
- 再試行は起こります。スキャンの作成の説明どおりに
Idempotency-Keyヘッダーを付けると、同じボディでの再試行でクレジットを使うのは1回だけになります。 - 公開前に、
402、422、429の処理を入れてください。それぞれの対処法はエラーのページにあります。
関連ページ:APIドキュメントの概要、テストキーとライブキーは認証、クレジットの消費は栄養APIの料金、全体像は栄養APIの概要をご覧ください。