Nano Banana 2 API 使用教學:取得 Key、傳送請求與拿到結果
一步步呼叫 Nano Banana 2 API:建立 API Key、傳送 generateContent 請求、輪詢任務、新增參考圖,以及交給程式設計 Agent 執行。
以 Markdown 閱讀呼叫 Nano Banana 2 API 的步驟是:建立 API Key,把帶 model 欄位的 Google generateContent 請求體傳送到一個端點,然後輪詢回傳的任務,直到影像 URL 就緒。同樣的步驟也適用於 Nano Banana Pro 和 Nano Banana 2 Lite,只需修改 model 的值。
本教學用可執行的程式碼逐步講解每一步,然後介紹如何用參考圖編輯影像,以及如何把任務交給程式設計 Agent。
傳送第一個請求前需要準備什麼?
- 一個 API Key。 在 API Key 頁面建立,並儲存在你的服務端。絕不要把它放進瀏覽器端程式碼。
- 額度。 在帳單頁儲值餘額。額度永不過期,失敗的請求不收費。
- 一個模型 ID。
gemini-3.1-flash-image按每張圖的固定價計費;gemini-3.1-flash-image-official按 token 計費。選擇方法見價格指南。
export SEEDROUTER_API_KEY="your-key"如何傳送 Nano Banana 2 請求?
把請求 POST 到 /v1/images/generations。請求體就是 Google 的 generateContent 結構,再加上 model:
curl https://api.seedrouter.ai/v1/images/generations \
-H "Authorization: Bearer $SEEDROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.1-flash-image",
"contents": [{"parts": [{"text": "A ceramic teapot on a linen tablecloth, soft window light"}]}],
"generationConfig": {
"responseModalities": ["IMAGE"],
"imageConfig": {"aspectRatio": "16:9", "imageSize": "2K"}
}
}'回應是一個任務,而不是影像:
{
"id": "task_...",
"model": "gemini-3.1-flash-image",
"status": "processing",
"created_at": 1790310979
}如果你已經在呼叫 Google 的 API,這裡傳送的請求體與你發給 generateContent 的完全相同。SeedRouter 不支援直接呼叫 /v1beta/models/...:generateContent,請使用本端點。
如何拿到生成的影像?
每隔幾秒輪詢一次任務,直到 status 變為 completed 或 failed。Python 範例:
import os
import time
import requests
API = "https://api.seedrouter.ai/v1"
headers = {"Authorization": f"Bearer {os.environ['SEEDROUTER_API_KEY']}"}
response = requests.post(
f"{API}/images/generations",
headers=headers,
json={
"model": "gemini-3.1-flash-image",
"contents": [{"parts": [{"text": "A ceramic teapot on a linen tablecloth, soft window light"}]}],
"generationConfig": {
"responseModalities": ["IMAGE"],
"imageConfig": {"aspectRatio": "16:9", "imageSize": "2K"},
},
},
timeout=60,
)
response.raise_for_status()
task_id = response.json()["id"]
deadline = time.monotonic() + 600
while time.monotonic() < deadline:
result = requests.get(f"{API}/tasks/{task_id}", headers=headers, timeout=30)
result.raise_for_status()
task = result.json()
if task["status"] == "completed":
for image in task["output"]["data"]:
print(image["url"])
break
if task["status"] == "failed":
raise RuntimeError(task["error"]["message"])
time.sleep(3)
else:
raise TimeoutError(f"Still waiting. Resume polling task {task_id}.")已完成的任務在 output.data[0].url 中回傳影像 URL,並附帶 token 用量。設定 "responseModalities": ["TEXT", "IMAGE"] 時,模型寫出的文字會在 output.text 中回傳。如需長期儲存,請把影像下載到你自己的儲存中。
輪詢時超時並不意味著出圖失敗。請保留任務 ID 並再次查詢;提交新請求就意味著要為第二張圖付費。
如何編輯影像或使用參考圖?
在文字旁邊新增 fileData part。每個 part 包含一個公開 URL 及其 MIME 型別:
curl https://api.seedrouter.ai/v1/images/generations \
-H "Authorization: Bearer $SEEDROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.1-flash-image",
"contents": [{
"role": "user",
"parts": [
{"text": "Turn this photo into a watercolor painting. Keep the composition."},
{"fileData": {"mimeType": "image/jpeg", "fileUri": "https://example.com/photo.jpg"}}
]
}]
}'Nano Banana 2 每次請求最多接受 14 個參考素材:影像、影片或 PDF,每個小於 50 MB。參考素材必須是 URL,不接受 base64 inlineData。如果某個 URL 無法拉取,任務會失敗且不收費。進行後續編輯時,把之前的輪次作為 user 和 model 條目傳送,並以一個新的 user 輪次結尾。
哪些參數最重要?
| 參數 | 作用 |
|---|---|
imageConfig.imageSize | 512、1K、2K 或 4K;預設 1K |
imageConfig.aspectRatio | 從 1:8 到 8:1 共 14 種寬高比;省略時跟隨第一張參考圖 |
responseModalities | ["IMAGE"] 只回傳影像,["TEXT", "IMAGE"] 同時回傳文字 |
systemInstruction | 固定規則,例如品牌統一風格 |
seed | 複用它可以更接近之前的結果 |
mediaResolution | 每個參考素材佔用多少 token;在 Official 上越低越便宜 |
Nano Banana 2 API 文件列出了每個欄位和限制。未知欄位會在任何扣費發生之前被拒絕,Google Search grounding(tools)暫不可用。
如何讓程式設計 Agent 呼叫 Nano Banana 2 API?
Claude Code、Codex 或 Cursor 這類程式設計 Agent 可以透過一條 shell 命令或一段簡短指令碼呼叫 API。SeedRouter 不提供 MCP 伺服器或打包好的 skill;下面這段提示詞就是全部的接入方式。先匯出 Key,然後貼上:
Use the SeedRouter API to generate a Nano Banana 2 image for me.
Security: read SEEDROUTER_API_KEY from my local environment. Never ask me to paste it and never print it.
Goal: [subject, setting, style, what the image is for]
Size: [512 | 1K | 2K | 4K] Aspect ratio: [e.g. 1:1, 16:9, 9:16]
References: [public image URLs, or none]
Send POST https://api.seedrouter.ai/v1/images/generations with
{"model": "gemini-3.1-flash-image",
"contents": [{"parts": [{"text": "..."}, {"fileData": {"mimeType": "image/jpeg", "fileUri": "https://..."}}]}],
"generationConfig": {"responseModalities": ["IMAGE"],
"imageConfig": {"aspectRatio": "...", "imageSize": "..."}}}
Accepted top-level fields: model, contents, systemInstruction, safetySettings,
generationConfig. References must be fileData URLs (up to 14), never base64.
Do not add tools or any other field.
Before sending, show me the request body and wait for my approval: each
request is charged. Then poll GET https://api.seedrouter.ai/v1/tasks/{id}
every 3 seconds until status is completed or failed. If polling times out,
keep checking the same task; never resubmit. Save output.data[0].url into
./images/ and tell me the file path.審批這一步很重要:Agent 花的是你的餘額,所以它絕不應該自行提交請求。
常見問題
如何取得 Nano Banana 2 API Key?
登入後開啟 API Key 頁面並建立一個 Key。同一個 Key 可用於 Nano Banana 2、Nano Banana Pro、Nano Banana 2 Lite 以及 SeedRouter 上的其他模型。
Nano Banana 2 API 支援批次請求嗎?
每張圖傳送一個請求,並行輪詢這些任務。每個請求回傳一張圖,每個任務單獨計費。
需要處理哪些錯誤?
400 表示請求體違反了某條規則,例如存在未知欄位或尺寸不受支援,此時不會扣費。以 failed 結束的任務會帶有錯誤資訊,同樣不收費。錯誤指南列出了每個錯誤碼以及何時應該重試。
傳送你的第一個請求
建立一個 Key,儲值少量餘額,然後執行上面的 Python 範例;也可以在 Nano Banana 2 Playground 裡無需程式碼試用同樣的請求。遇到複雜提示詞時,把模型改為 gemini-3-pro-image 即可使用 Nano Banana Pro。



