curl --request GET \
--url 'https://toapis.com/v1/images/generations/task_01KA040M0HP1GJWBJYZMKX1XS1' \
--header 'Authorization: Bearer <token>'
import requests
import time
API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def get_image_status(task_id):
response = requests.get(f'{API_BASE}/v1/images/generations/{task_id}', headers=headers)
return response.json()
def wait_for_image(task_id, max_attempts=60, interval=3):
for _ in range(max_attempts):
result = get_image_status(task_id)
status = result.get('status')
print(f"狀態: {status}")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"任務失敗: {result}")
time.sleep(interval)
raise Exception("任務超時")
# 使用示例
task_id = "task_01KA040M0HP1GJWBJYZMKX1XS1"
result = wait_for_image(task_id)
print(f"圖片URL: {result['url']}")
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';
async function getImageStatus(taskId) {
const response = await fetch(`${API_BASE}/v1/images/generations/${taskId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
async function waitForImage(taskId, maxAttempts = 60, interval = 3000) {
for (let i = 0; i < maxAttempts; i++) {
const result = await getImageStatus(taskId);
const status = result.status;
console.log(`狀態: ${status}`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`任務失敗: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('任務超時');
}
// 使用示例
const taskId = 'task_01KA040M0HP1GJWBJYZMKX1XS1';
waitForImage(taskId).then(result => {
console.log('圖片URL:', result.url);
});
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func getImageStatus(taskId string) (map[string]interface{}, error) {
url := fmt.Sprintf("https://toapis.com/v1/images/generations/%s", taskId)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer <token>")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
func main() {
taskId := "task_01KA040M0HP1GJWBJYZMKX1XS1"
for i := 0; i < 60; i++ {
result, _ := getImageStatus(taskId)
status := result["status"].(string)
fmt.Printf("狀態: %s\n", status)
if status == "completed" {
fmt.Println("圖片生成完成!")
fmt.Println("圖片URL:", result["url"])
break
}
time.Sleep(3 * time.Second)
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "in_progress",
"progress": 50,
"created_at": 1768381010
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"client_business_id": "order_20260428_001",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "completed",
"progress": 100,
"created_at": 1768381010,
"completed_at": 1768381063,
"expires_at": 1768467463,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/1768381061_c55c1bbb.jpg"
}
]
}
}
{
"id": "img_73c450923a9a43e4aabf426e1c681d64",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "failed",
"progress": 0,
"created_at": 1768215312,
"error": {
"code": "generation_failed",
"message": "call upstream API failed: upstream returned status 422"
}
}
{
"error": {
"code": 404,
"message": "任務不存在",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "身份驗證失敗,請檢查您的API密鑰",
"type": "authentication_error"
}
}
獲取圖片任務狀態
獲取圖片任務狀態
查詢圖片生成任務的狀態和結果
GET
/
v1
/
images
/
generations
/
{task_id}
curl --request GET \
--url 'https://toapis.com/v1/images/generations/task_01KA040M0HP1GJWBJYZMKX1XS1' \
--header 'Authorization: Bearer <token>'
import requests
import time
API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def get_image_status(task_id):
response = requests.get(f'{API_BASE}/v1/images/generations/{task_id}', headers=headers)
return response.json()
def wait_for_image(task_id, max_attempts=60, interval=3):
for _ in range(max_attempts):
result = get_image_status(task_id)
status = result.get('status')
print(f"狀態: {status}")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"任務失敗: {result}")
time.sleep(interval)
raise Exception("任務超時")
# 使用示例
task_id = "task_01KA040M0HP1GJWBJYZMKX1XS1"
result = wait_for_image(task_id)
print(f"圖片URL: {result['url']}")
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';
async function getImageStatus(taskId) {
const response = await fetch(`${API_BASE}/v1/images/generations/${taskId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
async function waitForImage(taskId, maxAttempts = 60, interval = 3000) {
for (let i = 0; i < maxAttempts; i++) {
const result = await getImageStatus(taskId);
const status = result.status;
console.log(`狀態: ${status}`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`任務失敗: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('任務超時');
}
// 使用示例
const taskId = 'task_01KA040M0HP1GJWBJYZMKX1XS1';
waitForImage(taskId).then(result => {
console.log('圖片URL:', result.url);
});
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func getImageStatus(taskId string) (map[string]interface{}, error) {
url := fmt.Sprintf("https://toapis.com/v1/images/generations/%s", taskId)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer <token>")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
func main() {
taskId := "task_01KA040M0HP1GJWBJYZMKX1XS1"
for i := 0; i < 60; i++ {
result, _ := getImageStatus(taskId)
status := result["status"].(string)
fmt.Printf("狀態: %s\n", status)
if status == "completed" {
fmt.Println("圖片生成完成!")
fmt.Println("圖片URL:", result["url"])
break
}
time.Sleep(3 * time.Second)
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "in_progress",
"progress": 50,
"created_at": 1768381010
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"client_business_id": "order_20260428_001",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "completed",
"progress": 100,
"created_at": 1768381010,
"completed_at": 1768381063,
"expires_at": 1768467463,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/1768381061_c55c1bbb.jpg"
}
]
}
}
{
"id": "img_73c450923a9a43e4aabf426e1c681d64",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "failed",
"progress": 0,
"created_at": 1768215312,
"error": {
"code": "generation_failed",
"message": "call upstream API failed: upstream returned status 422"
}
}
{
"error": {
"code": 404,
"message": "任務不存在",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "身份驗證失敗,請檢查您的API密鑰",
"type": "authentication_error"
}
}
- 查詢異步圖片生成任務的執行狀態和結果
- 實時狀態更新和進度跟蹤
- 任務完成時獲取生成的圖片
- 支持多語言返回(zh/en/ko/ja)
創建任務時傳入業務 ID
創建圖片任務時,可以在請求體頂層傳入client_business_id。該字段用於保存您系統內的訂單號、流水號或業務任務 ID,方便後續按業務 ID 查詢生成結果。
{
"model": "gpt-4o-image",
"client_business_id": "order_20260428_001",
"prompt": "一隻可愛的熊貓",
"size": "1:1",
"n": 1
}
metadata.client_business_id 中,但推薦使用頂層字段。
Authorizations
string
必填
所有接口均需要使用 Bearer Token 進行認證獲取 API Key:訪問 API Key 管理頁面 獲取您的 API Key使用時在請求頭中添加:
Authorization: Bearer YOUR_API_KEY
Path Parameters
string
必填
圖片生成 API 返回的任務 ID。也可以傳創建任務時提交的
client_business_id,用於按客戶側業務 ID 查詢任務狀態和結果。如果創建圖片任務時傳入
client_business_id,可直接使用同一個狀態查詢接口:
GET /v1/images/generations/{client_business_id}。業務 ID 會限定在當前 API Key 所屬用戶下查詢。curl --request GET \
--url 'https://toapis.com/v1/images/generations/task_01KA040M0HP1GJWBJYZMKX1XS1' \
--header 'Authorization: Bearer <token>'
import requests
import time
API_BASE = 'https://toapis.com'
API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx'
headers = {
'Authorization': f'Bearer {API_KEY}'
}
def get_image_status(task_id):
response = requests.get(f'{API_BASE}/v1/images/generations/{task_id}', headers=headers)
return response.json()
def wait_for_image(task_id, max_attempts=60, interval=3):
for _ in range(max_attempts):
result = get_image_status(task_id)
status = result.get('status')
print(f"狀態: {status}")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"任務失敗: {result}")
time.sleep(interval)
raise Exception("任務超時")
# 使用示例
task_id = "task_01KA040M0HP1GJWBJYZMKX1XS1"
result = wait_for_image(task_id)
print(f"圖片URL: {result['url']}")
const API_BASE = 'https://toapis.com';
const API_KEY = 'sk-xxxxxxxxxxxxxxxxxxxxxx';
async function getImageStatus(taskId) {
const response = await fetch(`${API_BASE}/v1/images/generations/${taskId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
return response.json();
}
async function waitForImage(taskId, maxAttempts = 60, interval = 3000) {
for (let i = 0; i < maxAttempts; i++) {
const result = await getImageStatus(taskId);
const status = result.status;
console.log(`狀態: ${status}`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`任務失敗: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('任務超時');
}
// 使用示例
const taskId = 'task_01KA040M0HP1GJWBJYZMKX1XS1';
waitForImage(taskId).then(result => {
console.log('圖片URL:', result.url);
});
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
func getImageStatus(taskId string) (map[string]interface{}, error) {
url := fmt.Sprintf("https://toapis.com/v1/images/generations/%s", taskId)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Authorization", "Bearer <token>")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
return result, nil
}
func main() {
taskId := "task_01KA040M0HP1GJWBJYZMKX1XS1"
for i := 0; i < 60; i++ {
result, _ := getImageStatus(taskId)
status := result["status"].(string)
fmt.Printf("狀態: %s\n", status)
if status == "completed" {
fmt.Println("圖片生成完成!")
fmt.Println("圖片URL:", result["url"])
break
}
time.Sleep(3 * time.Second)
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "in_progress",
"progress": 50,
"created_at": 1768381010
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"client_business_id": "order_20260428_001",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "completed",
"progress": 100,
"created_at": 1768381010,
"completed_at": 1768381063,
"expires_at": 1768467463,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/1768381061_c55c1bbb.jpg"
}
]
}
}
{
"id": "img_73c450923a9a43e4aabf426e1c681d64",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "failed",
"progress": 0,
"created_at": 1768215312,
"error": {
"code": "generation_failed",
"message": "call upstream API failed: upstream returned status 422"
}
}
{
"error": {
"code": 404,
"message": "任務不存在",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "身份驗證失敗,請檢查您的API密鑰",
"type": "authentication_error"
}
}
Response
string
任務唯一標識符
string
客戶側業務 ID。僅當創建任務時傳入
client_business_id 時返回。string
對象類型,固定爲
generation.taskstring
使用的圖片生成模型
string
任務狀態
queued- 排隊等待處理in_progress- 處理中completed- 成功完成failed- 失敗
integer
任務進度百分比(0-100)
integer
任務創建時間(Unix 時間戳)
integer
任務完成時間(Unix 時間戳,僅完成時返回)
integer
圖片 URL 過期時間(Unix 時間戳,僅完成時返回)
任務狀態說明
| 狀態 | 說明 | 是否終態 | 建議操作 |
|---|---|---|---|
queued | 任務排隊等待處理 | ❌ | 等待至少 5-10 秒並加入抖動後查詢 |
in_progress | 任務正在處理中 | ❌ | 等待至少 5-10 秒並加入抖動後查詢 |
completed | 任務成功完成 | ✅ | 從 result.data[0].url 獲取圖片 |
failed | 任務處理失敗 | ✅ | 檢查 error 信息 |
輪詢策略建議
初始等待: 5 秒
輪詢間隔: 至少 5-10 秒並加入隨機抖動
最大等待: 120 秒
典型耗時: 5-30 秒
Python 輪詢示例
import time
import random
import requests
def poll_image_task(task_id, api_key, max_wait=120):
"""輪詢圖片生成任務直到完成或超時"""
start_time = time.time()
interval = 5
while time.time() - start_time < max_wait:
response = requests.get(
f'https://toapis.com/v1/images/generations/{task_id}',
headers={'Authorization': f'Bearer {api_key}'}
)
if response.status_code == 429:
retry_after = int(response.headers.get('Retry-After', interval))
time.sleep(retry_after + random.uniform(0, 1))
interval = min(interval * 2, 60)
continue
response.raise_for_status()
data = response.json()
if data['status'] == 'completed':
return data['url']
elif data['status'] == 'failed':
raise Exception(f"生成失敗: {data['error']['message']}")
time.sleep(interval + random.uniform(0, 1))
raise TimeoutError("任務超時")
圖片資源有效期
生成的圖片 URL 有效期爲 24 小時
- 請在有效期內下載保存圖片
expires_at字段標識圖片過期時間(Unix 時間戳)- 圖片過期後無法訪問,如需重新獲取,需要重新提交生成任務
常見錯誤
| 錯誤碼 | 錯誤類型 | 說明 |
|---|---|---|
| 400 | invalid_request | 請求參數無效 |
| 401 | unauthorized | 認證失敗,檢查 API Key |
| 402 | insufficient_quota | 餘額不足 |
| 404 | task_not_found | 任務不存在 |
| 422 | content_policy_violation | 內容違規 |
| 429 | rate_limit_exceeded | 請求頻率超限 |
| 500 | internal_error | 服務器內部錯誤 |
⌘I