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,
"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,
"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,
"completed_at": 1789099158,
"expires_at": 1789185558,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/example.png"
}
]
},
"usage": {
"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": "0",
"cost_usd": "0"
}
}
{
"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,
"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,
"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,
"completed_at": 1789099158,
"expires_at": 1789185558,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/example.png"
}
]
},
"usage": {
"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": "0",
"cost_usd": "0"
}
}
{
"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)
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,
"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,
"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,
"completed_at": 1789099158,
"expires_at": 1789185558,
"result": {
"type": "image",
"data": [
{
"url": "https://files.toapis.com/generated/example.png"
}
]
},
"usage": {
"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": "0",
"cost_usd": "0"
}
}
{
"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
Object type, always
generation.taskstring
Task status
queued- Queued for processingin_progress- Processingcompleted- Successfully completedfailed- Failed
string
Image generation model used
integer
Task creation time (Unix timestamp)
integer
Task completion time (Unix timestamp, only returned when completed)
string
Generated image URL (only returned on success)
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
선택적으로 반환되는 정산 완료 이미지 토큰 사용량입니다.
모든 토큰 수는 음수가 아닌 JSON 정수입니다. 캐시된 토큰은 입력 토큰의 일부이므로 다시 더하지 마세요. 출력 세부 정보가 없으면
billing.status가 settled이고 저장된 사용량이 유효하며 최종 청구 금액과 일치할 때만 이미지 토큰 필드를 반환합니다. 사용량이 없거나 검증할 수 없으면 생략하며, 추정하거나 0으로 대체하지 않습니다. 확정된 금액과 이미지 결과는 계속 반환할 수 있습니다.| 필드 | 유형 | 설명 |
|---|---|---|
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 전체를 생략합니다. 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에는 확정 청구 금액이 포함될 수 있습니다. 어느 한쪽이 없으면 이 엔드포인트를 대체 경로로 조회하세요. 가격 및 실제 청구 금액도 참고하세요.
Task 상태 Reference
| 상태 | 설명 | Is Final | Recommended Action |
|---|---|---|---|
submitted | 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
오류 Codes
| HTTP Code | 오류 Type | 설명 |
|---|---|---|
| 400 | invalid_request | Invalid request parameters |
| 401 | unauthorized | 인증 failed, check API Key |
| 402 | insufficient_quota | Insufficient balance |
| 404 | task_not_found | Task not found |
| 422 | content_policy_violation | Content policy violation |
| 429 | rate_limit_exceeded | Rate limit exceeded |
| 500 | internal_error | Internal server error |
ToAPIs 통합 Task Webhook을 우선 사용하고 조회는 대체 경로로 사용하세요. 5~10초 이상과 지터,
429의 Retry-After를 따르세요. 배치는 최대 100개입니다. 속도 제한.