> ## Documentation Index
> Fetch the complete documentation index at: https://docs.toapis.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Get Image Task 상태

> Query image generation task status and results

> [!NOTE]
>
> **중국 본토 사용자 안내:** 중국 본토 사용자는 `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)

All image generation tasks are executed asynchronously. After submitting a task, you need to query the status and results via the query endpoint.

일반 이미지와 동영상 작업은 `GET /v1/tasks/{task_id}`로도 조회할 수 있으며 `usage`와 `billing`의 정의는 같습니다. 이 페이지는 상단에 표시된 생성 작업 조회 경로의 응답을 설명합니다.

예시는 필드 구조를 보여 주며 모델의 현재 가격이나 고정 과금 방식을 나타내지 않습니다. 실제 작업에서 반환된 필드와 금액을 확인하세요.

## Authorizations

**Authorization** `string` *required*

All endpoints require Bearer Token authentication

Get your API Key:

Visit the [API Key Management Page](https://toapis.com/console/token) to get your API Key

Add it to the request header:

```
Authorization: Bearer YOUR_API_KEY
```

## Path 파라미터

**task\_id** `string` *required*

Task ID returned by the image generation API

```bash cURL theme={null}
curl --request GET \
  --url 'https://toapis.com/v1/images/generations/task_01KA040M0HP1GJWBJYZMKX1XS1' \
  --header 'Authorization: Bearer <token>'
```

```python Python theme={null}
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']}")
```

```javascript JavaScript theme={null}
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);
});
```

```go Go theme={null}
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)
    }
}
```

```json 200 - In Progress theme={null}
{
  "id": "img_5b8b19afe5c24ab3a92df996f1a33931",
  "object": "generation.task",
  "model": "gemini-3-pro-image-preview",
  "status": "in_progress",
  "progress": 50,
  "created_at": 1768381010,
  "billing": {
    "status": "pending"
  }
}
```

```json 200 - Completed theme={null}
{
  "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"
  }
}
```

```json 200 - Failed theme={null}
{
  "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"
  }
}
```

```json 200 - 완료 - 무료 작업 및 사용량 theme={null}
{
  "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"
  }
}
```

```json 404 theme={null}
{
  "error": {
    "code": 404,
    "message": "Task not found",
    "type": "not_found_error"
  }
}
```

```json 401 theme={null}
{
  "error": {
    "code": 401,
    "message": "Authentication failed, please check your API key",
    "type": "authentication_error"
  }
}
```

## 응답

**id** `string`

Unique task identifier

**client\_business\_id** `string`

선택적 고객 업무 ID입니다. 작업 생성 시 `client_business_id`를 전달한 경우에만 반환합니다.

**object** `string`

Object type, always `generation.task`

**status** `string`

Task status

* `queued` - Queued for processing
* `in_progress` - Processing
* `completed` - Successfully completed
* `failed` - Failed

**progress** `integer`

0-100 범위의 정수 진행률입니다.

**model** `string`

Image generation model used

**created\_at** `integer`

Task creation time (Unix timestamp)

**finished\_at** `integer`

작업 종료 시각, Unix 타임스탬프입니다. 이 조회 경로에서는 성공 또는 실패한 작업에 종료 시각이 저장된 경우 반환합니다.

**completed\_at** `integer`

Task completion time (Unix timestamp, only returned when completed)

**expires\_at** `integer`

Image URL expiration time (Unix timestamp, only returned on completion)

**result** `object`

Task result (only returned on success)

**Properties**

**type** `string`

Result type, always `image`

**data** `array`

Image data array

**Array Elements**

**url** `string`

Generated image URL

**billing** `object`

선택적으로 반환되는 이미지 작업 과금 정보입니다. 과금 상태는 생성 상태와 별개이므로 `completed`여도 정산이 완료되었다고 단정할 수 없습니다. 과금 정보를 확인할 수 없으면 `billing` 전체를 생략하며 `null`을 반환하지 않습니다. 생략되었다고 무료인 것은 아닙니다.

**속성**

**status** `string`

`pending`은 정산 또는 환불이 아직 확인되지 않은 상태이며 금액을 생략합니다. `settled`는 최종 청구 금액이 확정된 상태입니다. `refunded`는 환불되었거나 실패한 작업의 순청구액이 0으로 확인된 상태이며, 과금 전에 실패한 경우도 포함합니다.

**credits** `string`

플랫폼이 고객에게 실제로 청구한 크레딧을 십진수 문자열로 반환합니다. `settled` 또는 `refunded`일 때만 반환합니다.

**cost\_usd** `string`

플랫폼이 고객에게 실제로 청구한 USD 금액을 십진수 문자열로 반환합니다. 작업 과금 시 적용된 할인과 배율을 포함하며, 공급자 원가가 아닙니다.

**usage** `object`

선택적 과금 수량, 이미지 토큰 내역, 도구 사용 횟수입니다. `charge_type`, `requests`, `billed_tokens` 등은 [작업 사용량 필드](https://docs.toapis.com/docs/ko/api-reference/account/pricing.md)를 참고하세요. 이미지 토큰 내역은 `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`는 단독으로 반환되거나 이미지 토큰과 함께 반환될 수 있습니다.

**error** `object`

오류 information (only returned on failure)

**Properties**

**code** `string`

오류 code

**message** `string`

오류 description

## 과금 상태와 비용 집계

이 과금 규칙은 모델이나 채널에 관계없이 이미지 작업 조회에 적용됩니다. 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은 이벤트 생성 시점의 스냅샷이므로 필드가 없으면 이 엔드포인트를 대체 경로로 조회하세요. [가격 및 실제 청구 금액](https://docs.toapis.com/docs/ko/api-reference/account/pricing.md)도 참고하세요.

## 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

```python theme={null}
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

> [!WARNING]
>
> Generated image URLs are valid for **24 hours**
>
> * Please download and save images within the validity period
> * `expires_at` field indicates image expiration time (Unix timestamp)
> * Expired images cannot be accessed; to regenerate, submit a new task

## 오류와 실패 원인

요청 오류, 작업 실패의 구체적인 원인과 복구 방법은 [오류 코드 빠른 참조](https://docs.toapis.com/docs/ko/api-reference/errors.md) 를 확인하세요. 조회 성공 후에도 작업 상태를 확인하고 HTTP 상태와 비즈니스 코드를 구분하세요.

> [!NOTE]
>
> ToAPIs 통합 [Task Webhook](https://docs.toapis.com/docs/ko/api-reference/webhooks/task-webhooks.md)을 우선 사용하고 조회는 대체 경로로 사용하세요. 5\~10초 이상과 지터, `429`의 `Retry-After`를 따르세요. 배치는 최대 100개입니다. [속도 제한](https://docs.toapis.com/docs/ko/api-reference/rate-limits/async-tasks.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.