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: {status}")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"Task failed: {result}")
time.sleep(interval)
raise Exception("Task timeout")
# Usage example
task_id = "task_01KA040M0HP1GJWBJYZMKX1XS1"
result = wait_for_image(task_id)
print(f"Image 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: ${status}`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`Task failed: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('Task timeout');
}
// Usage example
const taskId = 'task_01KA040M0HP1GJWBJYZMKX1XS1';
waitForImage(taskId).then(result => {
console.log('Image 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("Status: %s\n", status)
if status == "completed" {
fmt.Println("Image generation completed!")
fmt.Println("Image 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,
"billing": {
"status": "pending"
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "completed",
"progress": 100,
"created_at": 1768381010,
"finished_at": 1768381063,
"completed_at": 1768381063,
"expires_at": 1768467463,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/1768381061_c55c1bbb.jpg"
}
]
},
"usage": {
"charge_type": "per_request",
"requests": 1
},
"billing": {
"status": "settled",
"credits": "100",
"cost_usd": "0.5"
}
}
{
"id": "img_73c450923a9a43e4aabf426e1c681d64",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "failed",
"progress": 0,
"created_at": 1768215312,
"billing": {
"status": "refunded",
"credits": "0",
"cost_usd": "0"
},
"error": {
"code": "generation_failed",
"message": "call upstream API failed: upstream returned status 422"
}
}
{
"id": "tsk_img_example",
"object": "generation.task",
"model": "gpt-image-2.5-flare-official",
"status": "completed",
"progress": 100,
"created_at": 1789099098,
"finished_at": 1789099158,
"completed_at": 1789099158,
"expires_at": 1789185558,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/example.png"
}
]
},
"usage": {
"charge_type": "per_token",
"billed_tokens": 1000,
"input_tokens": 100,
"output_tokens": 900,
"total_tokens": 1000,
"input_tokens_details": {
"text_tokens": 20,
"image_tokens": 80,
"cached_tokens": 30,
"cached_tokens_details": {
"text_tokens": 10,
"image_tokens": 20
}
},
"output_tokens_details": {
"text_tokens": 0,
"image_tokens": 900
}
},
"billing": {
"status": "settled",
"credits": "10",
"cost_usd": "0.05"
}
}
{
"error": {
"code": 404,
"message": "Task not found",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "Authentication failed, please check your API key",
"type": "authentication_error"
}
}
작업 관리
Get Image Task 상태
Query image generation task status and results
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: {status}")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"Task failed: {result}")
time.sleep(interval)
raise Exception("Task timeout")
# Usage example
task_id = "task_01KA040M0HP1GJWBJYZMKX1XS1"
result = wait_for_image(task_id)
print(f"Image 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: ${status}`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`Task failed: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('Task timeout');
}
// Usage example
const taskId = 'task_01KA040M0HP1GJWBJYZMKX1XS1';
waitForImage(taskId).then(result => {
console.log('Image 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("Status: %s\n", status)
if status == "completed" {
fmt.Println("Image generation completed!")
fmt.Println("Image 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,
"billing": {
"status": "pending"
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "completed",
"progress": 100,
"created_at": 1768381010,
"finished_at": 1768381063,
"completed_at": 1768381063,
"expires_at": 1768467463,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/1768381061_c55c1bbb.jpg"
}
]
},
"usage": {
"charge_type": "per_request",
"requests": 1
},
"billing": {
"status": "settled",
"credits": "100",
"cost_usd": "0.5"
}
}
{
"id": "img_73c450923a9a43e4aabf426e1c681d64",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "failed",
"progress": 0,
"created_at": 1768215312,
"billing": {
"status": "refunded",
"credits": "0",
"cost_usd": "0"
},
"error": {
"code": "generation_failed",
"message": "call upstream API failed: upstream returned status 422"
}
}
{
"id": "tsk_img_example",
"object": "generation.task",
"model": "gpt-image-2.5-flare-official",
"status": "completed",
"progress": 100,
"created_at": 1789099098,
"finished_at": 1789099158,
"completed_at": 1789099158,
"expires_at": 1789185558,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/example.png"
}
]
},
"usage": {
"charge_type": "per_token",
"billed_tokens": 1000,
"input_tokens": 100,
"output_tokens": 900,
"total_tokens": 1000,
"input_tokens_details": {
"text_tokens": 20,
"image_tokens": 80,
"cached_tokens": 30,
"cached_tokens_details": {
"text_tokens": 10,
"image_tokens": 20
}
},
"output_tokens_details": {
"text_tokens": 0,
"image_tokens": 900
}
},
"billing": {
"status": "settled",
"credits": "10",
"cost_usd": "0.05"
}
}
{
"error": {
"code": 404,
"message": "Task not found",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "Authentication failed, please check your API key",
"type": "authentication_error"
}
}
중국 본토 사용자 안내: 중국 본토 사용자는
https://toapis.cn 를 API 엔드포인트(Base URL)로 사용해 주세요. 본 문서의 예시에서 https://toapis.com 을 https://toapis.cn 로 바꿔 주세요.- Query async image generation task execution status and results
- Real-time status updates and progress tracking
- Get generated images when task completes
- Multi-language support (zh/en/ko/ja)
GET /v1/tasks/{task_id}로도 조회할 수 있으며 usage와 billing의 정의는 같습니다. 이 페이지는 상단에 표시된 생성 작업 조회 경로의 응답을 설명합니다.
예시는 필드 구조를 보여 주며 모델의 현재 가격이나 고정 과금 방식을 나타내지 않습니다. 실제 작업에서 반환된 필드와 금액을 확인하세요.
Authorizations
string
필수
All endpoints require Bearer Token authenticationGet your API Key:Visit the API Key Management Page to get your API KeyAdd it to the request header:
Authorization: Bearer YOUR_API_KEY
Path 파라미터
string
필수
Task ID returned by the image generation API
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: {status}")
if status == 'completed':
return result
elif status == 'failed':
raise Exception(f"Task failed: {result}")
time.sleep(interval)
raise Exception("Task timeout")
# Usage example
task_id = "task_01KA040M0HP1GJWBJYZMKX1XS1"
result = wait_for_image(task_id)
print(f"Image 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: ${status}`);
if (status === 'completed') {
return result;
} else if (status === 'failed') {
throw new Error(`Task failed: ${JSON.stringify(result)}`);
}
await new Promise(r => setTimeout(r, interval));
}
throw new Error('Task timeout');
}
// Usage example
const taskId = 'task_01KA040M0HP1GJWBJYZMKX1XS1';
waitForImage(taskId).then(result => {
console.log('Image 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("Status: %s\n", status)
if status == "completed" {
fmt.Println("Image generation completed!")
fmt.Println("Image 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,
"billing": {
"status": "pending"
}
}
{
"id": "img_5b8b19afe5c24ab3a92df996f1a33931",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "completed",
"progress": 100,
"created_at": 1768381010,
"finished_at": 1768381063,
"completed_at": 1768381063,
"expires_at": 1768467463,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/1768381061_c55c1bbb.jpg"
}
]
},
"usage": {
"charge_type": "per_request",
"requests": 1
},
"billing": {
"status": "settled",
"credits": "100",
"cost_usd": "0.5"
}
}
{
"id": "img_73c450923a9a43e4aabf426e1c681d64",
"object": "generation.task",
"model": "gemini-3-pro-image-preview",
"status": "failed",
"progress": 0,
"created_at": 1768215312,
"billing": {
"status": "refunded",
"credits": "0",
"cost_usd": "0"
},
"error": {
"code": "generation_failed",
"message": "call upstream API failed: upstream returned status 422"
}
}
{
"id": "tsk_img_example",
"object": "generation.task",
"model": "gpt-image-2.5-flare-official",
"status": "completed",
"progress": 100,
"created_at": 1789099098,
"finished_at": 1789099158,
"completed_at": 1789099158,
"expires_at": 1789185558,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/example.png"
}
]
},
"usage": {
"charge_type": "per_token",
"billed_tokens": 1000,
"input_tokens": 100,
"output_tokens": 900,
"total_tokens": 1000,
"input_tokens_details": {
"text_tokens": 20,
"image_tokens": 80,
"cached_tokens": 30,
"cached_tokens_details": {
"text_tokens": 10,
"image_tokens": 20
}
},
"output_tokens_details": {
"text_tokens": 0,
"image_tokens": 900
}
},
"billing": {
"status": "settled",
"credits": "10",
"cost_usd": "0.05"
}
}
{
"error": {
"code": 404,
"message": "Task not found",
"type": "not_found_error"
}
}
{
"error": {
"code": 401,
"message": "Authentication failed, please check your API key",
"type": "authentication_error"
}
}
응답
string
Unique task identifier
string
선택적 고객 업무 ID입니다. 작업 생성 시
client_business_id를 전달한 경우에만 반환합니다.string
Object type, always
generation.taskstring
Task status
queued- Queued for processingin_progress- Processingcompleted- Successfully completedfailed- Failed
integer
0-100 범위의 정수 진행률입니다.
string
Image generation model used
integer
Task creation time (Unix timestamp)
integer
작업 종료 시각, Unix 타임스탬프입니다. 이 조회 경로에서는 성공 또는 실패한 작업에 종료 시각이 저장된 경우 반환합니다.
integer
Task completion time (Unix timestamp, only returned when completed)
integer
Image URL expiration time (Unix timestamp, only returned on completion)
object
object
선택적으로 반환되는 이미지 작업 과금 정보입니다. 과금 상태는 생성 상태와 별개이므로
completed여도 정산이 완료되었다고 단정할 수 없습니다. 과금 정보를 확인할 수 없으면 billing 전체를 생략하며 null을 반환하지 않습니다. 생략되었다고 무료인 것은 아닙니다.표시 속성
표시 속성
string
pending은 정산 또는 환불이 아직 확인되지 않은 상태이며 금액을 생략합니다. settled는 최종 청구 금액이 확정된 상태입니다. refunded는 환불되었거나 실패한 작업의 순청구액이 0으로 확인된 상태이며, 과금 전에 실패한 경우도 포함합니다.string
플랫폼이 고객에게 실제로 청구한 크레딧을 십진수 문자열로 반환합니다.
settled 또는 refunded일 때만 반환합니다.string
플랫폼이 고객에게 실제로 청구한 USD 금액을 십진수 문자열로 반환합니다. 작업 과금 시 적용된 할인과 배율을 포함하며, 공급자 원가가 아닙니다.
object
선택적 과금 수량, 이미지 토큰 내역, 도구 사용 횟수입니다.
charge_type, requests, billed_tokens 등은 작업 사용량 필드를 참고하세요. 이미지 토큰 내역은 billing.status가 settled이고 저장된 사용량이 유효하며 최종 과금과 일치할 때만 반환합니다. 확인할 수 없는 부분은 생략해도 확정 금액과 이미지 결과는 반환됩니다.| 필드 | 유형 | 설명 |
|---|---|---|
input_tokens | integer | 텍스트와 이미지를 포함한 전체 입력 토큰 수 |
output_tokens | integer | 전체 출력 토큰 수 |
total_tokens | integer | input_tokens + output_tokens |
input_tokens_details.text_tokens | integer | 텍스트 입력 토큰 수 |
input_tokens_details.image_tokens | integer | 이미지 입력 토큰 수 |
input_tokens_details.cached_tokens | integer | 캐시된 입력 토큰 수. 전체 입력 토큰 수에 이미 포함됩니다 |
input_tokens_details.cached_tokens_details.text_tokens | integer | 캐시된 텍스트 입력 토큰 수 |
input_tokens_details.cached_tokens_details.image_tokens | integer | 캐시된 이미지 입력 토큰 수 |
output_tokens_details.text_tokens | integer | 텍스트 출력 토큰 수. 출력 세부 정보가 있을 때만 반환합니다 |
output_tokens_details.image_tokens | integer | 이미지 출력 토큰 수. 출력 세부 정보가 있을 때만 반환합니다 |
output_tokens_details.text_or_reasoning_tokens | integer | 텍스트와 사고 과정의 가격이 같아 구분하지 않은 출력 토큰 수. text_tokens에 포함하지 않으며 있을 때만 반환합니다 |
charge_type | string | 과금 방식: per_request(건당), per_token(토큰 기준) |
requests | integer | 과금 요청 횟수. per_request일 때 반환합니다. 요청의 n을 직접 곱하지 않습니다 |
billed_tokens | integer | 가격 계산에 사용한 토큰 수. per_token일 때 반환합니다 |
input_images | integer | 무료 한도를 제외하고 과금 대상이 된 입력 이미지 수. 0이면 생략합니다 |
tool_usage.web_search, tool_usage.image_search, tool_usage.grounding_queries | integer | 웹 검색, 이미지 검색, Grounding 쿼리 횟수. 사용한 경우에만 반환합니다 |
charge_type, requests, billed_tokens, input_images는 과금 수량이며 billing.status=settled와 함께만 반환합니다. 제출 시 한 번에 과금되는 건당 과금 작업도 실제 금액과 함께 settled를 반환합니다. 모든 토큰 수는 음수가 아닌 JSON 정수입니다. 캐시된 토큰은 입력 토큰의 일부이므로 다시 더하지 마세요. 출력 세부 정보가 없으면 output_tokens_details 전체를 생략합니다. usage.tool_usage.web_search는 단독으로 반환되거나 이미지 토큰과 함께 반환될 수 있습니다.과금 상태와 비용 집계
이 과금 규칙은 모델이나 채널에 관계없이 이미지 작업 조회에 적용됩니다. GPT-Image-2.5의 Sunburst 및 Flare VIP / Official 모델은 토큰 사용량을 지원하며, 다른 모델의 반환 여부는 저장된 정산 데이터에 따라 달라집니다. 예시 금액은 응답 형식을 설명하며 고정 단가가 아닙니다.| billing.status | 의미 | 금액 및 이미지 토큰 |
|---|---|---|
pending | 생성 중, 정산 대기 또는 환불 미확인 | 금액과 이미지 토큰 생략. 선차감액은 최종 비용이 아닙니다 |
settled | 최종 청구 금액 확정 | 금액 반환. 유효한 사용량이 있으면 이미지 토큰도 반환합니다. 무료 작업도 "0"을 반환할 수 있습니다 |
refunded | 환불 완료 또는 실패 후 순청구액이 0으로 확인됨 | credits와 cost_usd 모두 "0". 이미지 토큰 생략 |
- 금액은 작업의 확정된 최종 청구액입니다. 조회는 과금, 추가 청구, 환불 또는 현재 모델 가격에 따른 재계산을 수행하지 않습니다. 비용 집계에는 반환된 금액을 사용하고, 토큰 수에 현재 단가를 곱해 대체하지 마세요.
- 작업
id별로 금액을 갱신하고, 폴링할 때마다 같은 금액을 누적하지 마세요. 십진수 연산을 사용하세요.pending이거나 필드가 없으면 비용을 알 수 없는 것이며 0으로 처리하면 안 됩니다. - 금액은 십진수 문자열이며 소수 자릿수는 고정되어 있지 않습니다.
- 과금 기록이 없거나 일관되지 않으면
billing이 생략될 수 있습니다. 이미지가 아직 전달 가능한 상태가 아니어서 작업이 일시적으로in_progress로 표시되는 경우billing과usage가 모두 생략될 수도 있습니다. - 성공 Webhook의
data.usage와data.billing은 이 엔드포인트와 같은 확인 조건과 필드 값을 사용합니다. Webhook은 이벤트 생성 시점의 스냅샷이므로 필드가 없으면 이 엔드포인트를 대체 경로로 조회하세요. 가격 및 실제 청구 금액도 참고하세요.
Task 상태 Reference
| 상태 | 설명 | Is Final | Recommended Action |
|---|---|---|---|
queued | Task submitted, waiting for processing | ❌ | 5~10초 이상과 지터 후 조회 |
in_progress | Task is processing | ❌ | 5~10초 이상과 지터 후 조회 |
completed | Task completed successfully | ✅ | Get image from url field |
failed | Task processing failed | ✅ | Check error info |
Polling Strategy
Initial wait: 5 seconds
Polling interval: at least 5–10 seconds with random jitter
Max wait: 120 seconds
Typical time: 5-30 seconds
Python Polling Example
import time
import random
import requests
def poll_image_task(task_id, api_key, max_wait=120):
"""Poll image generation task until completion or timeout"""
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"Generation failed: {data['error']['message']}")
time.sleep(interval + random.uniform(0, 1))
raise TimeoutError("Task timeout")
Resource Expiration
Generated image URLs are valid for 24 hours
- Please download and save images within the validity period
expires_atfield indicates image expiration time (Unix timestamp)- Expired images cannot be accessed; to regenerate, submit a new task
오류와 실패 원인
요청 오류, 작업 실패의 구체적인 원인과 복구 방법은 오류 코드 빠른 참조 를 확인하세요. 조회 성공 후에도 작업 상태를 확인하고 HTTP 상태와 비즈니스 코드를 구분하세요.ToAPIs 통합 Task Webhook을 우선 사용하고 조회는 대체 경로로 사용하세요. 5~10초 이상과 지터,
429의 Retry-After를 따르세요. 배치는 최대 100개입니다. 속도 제한.