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

# Grok Imagine 공식 텍스트 투 이미지 API 레퍼런스

> Grok Imagine 공식 텍스트 투 이미지 API 레퍼런스 및 실시간 테스트 — 3개 모델, 1k / 1.5k / 2k 해상도 등급, 2.0의 low / medium 품질, 등급별 xAI와 동일한 가격 책정

> [!WARNING]
>
> **🔒 신청 시 부여되는 `GrokOfficial` 그룹 필요**: Grok Imagine Official은 `Default` 그룹에 포함되어 있지 않으므로, 호출하기 전에(이 페이지의 Playground 포함) 접근 권한을 신청해야 합니다. 접근 권한이 없거나 요청당 과금 Token을 사용하는 경우 모든 호출에서 `503`이 반환됩니다. 자세한 내용은 [Grok Imagine Official 개요 - 그룹 설정](/ko/api-capabilities/grok-imagine-image-official/overview#group-setup)을 참조하십시오.

> [!NOTE]
>
> 우측의 인터랙티브 Playground를 통해 엔드포인트를 직접 테스트할 수 있습니다. **Authorization**에 API Key를 입력하고(형식: `Bearer sk-xxx`), `prompt`을 입력한 뒤 모델, `resolution` 및 `aspect_ratio`(2.0의 경우 `quality` 추가)을 선택하고 전송하십시오.

> [!TIP]
>
> **이 페이지를 사용하는 경우**: 텍스트-투-이미지, 호출당 1장의 이미지. 이 채널은 아직 이미지 편집 기능을 제공하지 않습니다. 참조 기반 편집이나 호출당 여러 장의 이미지가 필요한 경우 [Grok Imagine Reverse](/ko/api-capabilities/grok-imagine-image/overview)를 사용하십시오.

> [!WARNING]
>
> **⚠️ 가장 흔히 발생하는 3가지 주의점**
>
> 1. **`size`가 아닌 `resolution`을 사용하십시오**: `size`은 해상도 티어에 매핑되지 않으므로 이미지는 기본값인 `1k`으로 생성되며 이에 따라 과금됩니다.
> 2. **잘못된 입력 시 오류 반환**: 범위를 벗어난 `resolution` / `aspect_ratio`은 422를 반환하고 `quality: "high"`은 400을 반환합니다. 이는 리버스 채널의 사일런트 폴백(silent fallback) 방식과 정반대입니다.
> 3. **항상 `n` = 1로 전송하십시오**: 여러 장의 이미지가 필요한 경우 여러 요청을 동시에 전송하십시오.

> [!NOTE]
>
> 모든 이미지 API는 **동기식**입니다. 비동기 작업 ID가 없으므로 클라이언트 연결이 끊어지면 결과는 유실되지만 요청에 대한 과금은 정상적으로 진행됩니다. `medium` 및 2K 환경의 `grok-imagine-image-2.0`은 약 60\~80초가 소요되므로 **클라이언트 타임아웃을 360초로 설정하십시오**. 자세한 내용은 [이미지 API 주의 사항 및 모범 사례](/ko/api-capabilities/image-api-best-practices)를 참조하십시오.

## 코드 예제

### Python (OpenAI SDK)

```python theme={null}
from openai import OpenAI
import urllib.request

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.apiyi.com/v1",
    timeout=360.0  # the image API is synchronous; give it a generous timeout
)

resp = client.images.generate(
    model="grok-imagine-image-2.0",
    prompt="A photorealistic red wooden boat moored on a glassy alpine lake at dawn, "
           "mist over the water, snow-capped peaks behind, cinematic photography",
    n=1,
    # resolution / aspect_ratio / quality are not standard OpenAI SDK fields; put them in extra_body
    extra_body={
        "resolution": "1.5k",
        "aspect_ratio": "16:9",
        "quality": "medium"
    }
)

# The default response is an image link; download and store it right away
urllib.request.urlretrieve(resp.data[0].url, "out.png")
```

### Python (requests)

```python theme={null}
import requests
import base64

API_KEY = "sk-your-api-key"

response = requests.post(
    "https://api.apiyi.com/v1/images/generations",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    },
    json={
        "model": "grok-imagine-image-quality",
        "prompt": "Rainy cyberpunk city at night, close-up of neon signs, cinematic lighting",
        "n": 1,
        "resolution": "2k",
        "aspect_ratio": "9:16",
        "response_format": "b64_json"
    },
    timeout=360
).json()

# b64_json is plain base64 (no data: prefix); decode and write it
with open("out.png", "wb") as f:
    f.write(base64.b64decode(response["data"][0]["b64_json"]))
```

### cURL

```bash theme={null}
curl -X POST "https://api.apiyi.com/v1/images/generations" \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-image",
    "prompt": "An orange cat in sunglasses sitting at a beach bar, photorealistic, warm sunset",
    "n": 1,
    "resolution": "1k",
    "aspect_ratio": "3:2"
  }'
```

### Node.js (fetch)

```javascript theme={null}
import fs from 'node:fs';

// Need 3 images: send 3 requests concurrently, each with n=1
const prompts = Array(3).fill('A serene Japanese garden with cherry blossoms, koi pond, golden hour');

const results = await Promise.all(prompts.map(prompt =>
    fetch('https://api.apiyi.com/v1/images/generations', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer sk-your-api-key'
        },
        body: JSON.stringify({
            model: 'grok-imagine-image-2.0',
            prompt,
            n: 1,
            resolution: '1k',
            aspect_ratio: '4:3',
            quality: 'low'
        }),
        signal: AbortSignal.timeout(360000)
    }).then(r => r.json())
));

for (const [i, data] of results.entries()) {
    const img = await fetch(data.data[0].url);
    fs.writeFileSync(`out-${i}.img`, Buffer.from(await img.arrayBuffer()));
}
```

## 파라미터 빠른 참조

| 파라미터 | 타입 | 필수 여부 | 기본값 | 참고사항 |
| - | - | - | - | - |
| `model` | string | ✅ | — | `grok-imagine-image` / `grok-imagine-image-quality` / `grok-imagine-image-2.0` |
| `prompt` | string | ✅ | — | 모든 언어의 prompt를 지원합니다. 피사체, 장면, 스타일, 조명을 설명합니다 |
| `n` | integer | ❌ | `1` | 이 채널에서는 **항상 1**입니다. 추가 생성이 필요한 경우 동시에 호출하십시오 |
| `resolution` | string | ❌ | `1k` | `1k` / `1.5k` / `2k`(소문자), 가격 등급을 설정하며 범위를 벗어난 값은 422를 반환합니다 |
| `aspect_ratio` | string | ❌ | `1:1` | 일반적인 값: `1:1` / `16:9` / `9:16` / `4:3` / `3:4` / `3:2` / `2:3`, 범위를 벗어난 값은 422를 반환합니다 |
| `quality` | string | ❌ | `low` | `grok-imagine-image-2.0` 전용: `low` 또는 `medium`, `high`은 400을 반환합니다 |
| `response_format` | string | ❌ | `url` | `url`은 이미지 링크를 반환하고, `b64_json`는 순수 base64를 반환합니다(`data:` 접두사 없음) |

**이미지당 가격**(xAI와 동일):

| 모델 | `1k` | `1.5k` | `2k` |
| - | - | - | - |
| `grok-imagine-image` | \$0.02 | \$0.02 | \$0.02 |
| `grok-imagine-image-quality` | \$0.05 | \$0.06 | \$0.07 |
| `grok-imagine-image-2.0` (`low`) | \$0.04 | \$0.05 | \$0.06 |
| `grok-imagine-image-2.0` (`medium`) | \$0.06 | \$0.07 | \$0.08 |

> [!NOTE]
>
> 모델 가격은 공식 사이트 기준에 맞춰 책정되며 변동 시 함께 조정될 수 있습니다. 위 표는 참고용일 뿐이며, 상단 내비게이션의 **모델 가격** 탭의 내용이 기준이 됩니다: [모델 가격](/en/models/index).

## 응답 형식

```json theme={null}
{
  "created": 0,
  "data": [
    { "url": "https://.../sync_xxxxxxxx_0.png" }
  ],
  "usage": {
    "prompt_tokens": 1000,
    "total_tokens": 1000
  }
}
```

> [!NOTE]
>
> * `data[]`의 각 항목에는 `response_format`에 따라 `url` 또는 `b64_json` 중 **하나**가 포함됩니다.
> * 반환된 이미지 링크는 즉시 다운로드하십시오. 해당 링크를 계속해서 참조하지 마십시오.
> * `usage`은 자리표시자(`prompt_tokens`은 항상 `1000 × image count`)이며 **대조 목적으로 사용할 수 없습니다** — 콘솔 과금 내역이 공식 기준입니다.
> * `created`은 항상 0이므로 시간 측정용으로 사용하지 마십시오.

## 관련 문서

* [Grok Imagine 공식 개요](/ko/api-capabilities/grok-imagine-image-official/overview) - 요금, 그룹 적용, 공식 vs 리버스
* [Grok Imagine 동영상](/ko/api-capabilities/grok-imagine-video/overview) - 동일 그룹, 초당 과금
* [Grok Imagine 리버스](/ko/api-capabilities/grok-imagine-image/overview) - 이미지 편집 및 호출당 다중 이미지 생성


## OpenAPI

````yaml api-reference/grok-imagine-image-official-generate-openapi-en.yaml POST /v1/images/generations
openapi: 3.1.0
info:
  title: Grok Imagine Official Text-to-Image API
  description: >
    xAI Grok Imagine official channel — text-to-image endpoint, priced the same
    as xAI and billed by resolution and quality tier.


    - Three models: `grok-imagine-image` (\$0.02 per image at every tier),
    `grok-imagine-image-quality` (\$0.05 / \$0.06 / \$0.07),
    `grok-imagine-image-2.0` (`low` \$0.04–0.06, `medium` \$0.06–0.08)

    - Resolutions `1k` / `1.5k` / `2k`, set with `resolution` — **do not send
    `size`** (it is not mapped and the image is generated and billed at the
    default 1k)

    - Strict validation: out-of-range `resolution` / `aspect_ratio` returns 422,
    `quality: high` returns 400

    - `n` is fixed at 1 on this channel; call concurrently for more images.
    Image editing is not offered yet


    **Authentication**: add `Authorization: Bearer YOUR_API_KEY` to the request
    headers


    **API Key setup**: the Token group must include **`GrokOfficial`** (granted
    on application) with billing mode **Pay-as-you-go Priority** or
    **Pay-as-you-go**; without access, or with a pay-per-request Token, calls
    return 503


    **Get an API Key**: create a Token in the [APIYI
    console](https://api.apiyi.com/token)
  version: 1.0.0
servers:
  - url: https://api.apiyi.com
    description: Primary endpoint
security:
  - bearerAuth: []
paths:
  /v1/images/generations:
    post:
      tags:
        - Text-to-Image
      summary: 'Text-to-image: generate an image from a prompt (official channel)'
      description: >
        Generate one image from a text prompt on the Grok Imagine official
        channel.


        - Required: `model`, `prompt`

        - Optional: `resolution`, `aspect_ratio`, `quality` (2.0 only),
        `response_format`

        - Synchronous; 2.0 at `medium` and 2K takes about 60–80 seconds, so use
        a client timeout of at least 360 seconds

        - No reference images: an `image` field is ignored and the image is
        generated from the prompt alone
      operationId: generateGrokImagineOfficialTextToImage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/GrokImagineOfficialGenerateRequest'
      responses:
        '200':
          description: Image generated successfully
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ImageResponse'
        '400':
          description: >-
            Invalid `quality` (such as `high`); the message lists the allowed
            values
        '401':
          description: Unauthorized - invalid API Key
        '422':
          description: '`resolution` / `aspect_ratio` outside the allowed set (not billed)'
        '429':
          description: Rate limit hit or insufficient balance
        '503':
          description: >-
            Token lacks the `GrokOfficial` group, or uses pay-per-request
            billing
      security:
        - bearerAuth: []
components:
  schemas:
    GrokImagineOfficialGenerateRequest:
      type: object
      required:
        - model
        - prompt
      properties:
        model:
          type: string
          description: >
            Model ID:

            - `grok-imagine-image` — standard, \$0.02 per image at every
            resolution

            - `grok-imagine-image-quality` — high quality, \$0.05 / \$0.06 /
            \$0.07 at 1k / 1.5k / 2k

            - `grok-imagine-image-2.0` — newer model, `low` \$0.04 / \$0.05 /
            \$0.06, `medium` \$0.06 / \$0.07 / \$0.08
          enum:
            - grok-imagine-image
            - grok-imagine-image-quality
            - grok-imagine-image-2.0
          default: grok-imagine-image
        prompt:
          type: string
          description: >-
            Prompt in any language. Describe the subject, scene, style, and
            lighting in detail
          example: >-
            A photorealistic red wooden boat moored on a glassy alpine lake at
            dawn, mist over the water, snow-capped peaks behind, cinematic
            photography
        'n':
          type: integer
          description: >-
            Image count. Fixed at 1 on this channel; call concurrently for more
            images
          enum:
            - 1
          default: 1
        resolution:
          type: string
          description: >
            Resolution tier (lowercase), which also sets the price: `1k`
            (default) / `1.5k` / `2k`.


            Out-of-range values (such as `4k` or `1K`) return 422. **Do not use
            `size` instead** — it is not mapped to a resolution tier.
          enum:
            - 1k
            - 1.5k
            - 2k
          default: 1k
        aspect_ratio:
          type: string
          description: >
            Output aspect ratio, default `1:1`. Measured examples:
            `grok-imagine-image` at `1k` + `3:2` outputs 1248×832; `-quality` at
            `2k` + `9:16` outputs 1584×2816.


            Out-of-range values (such as `5:7`) return 422.
          enum:
            - '1:1'
            - '16:9'
            - '9:16'
            - '4:3'
            - '3:4'
            - '3:2'
            - '2:3'
          default: '1:1'
        quality:
          type: string
          description: >
            Quality tier, **only for `grok-imagine-image-2.0`**: `low` (default)
            or `medium` (\$0.02 more per image, slower).


            `high` returns 400. The other two models take no `quality`.
          enum:
            - low
            - medium
        response_format:
          type: string
          description: >-
            Response format: `url` (default; download and store the image right
            away) or `b64_json` (plain base64, no `data:` prefix)
          enum:
            - url
            - b64_json
          default: url
    ImageResponse:
      type: object
      properties:
        created:
          type: integer
          description: Always 0; do not use it for timing
          example: 0
        data:
          type: array
          description: Image results (one item on this channel)
          items:
            type: object
            properties:
              url:
                type: string
                description: Image link, returned when `response_format=url`
              b64_json:
                type: string
                description: >-
                  Plain base64 image data, returned when
                  `response_format=b64_json`
        usage:
          type: object
          description: >-
            **Placeholder — do not reconcile with it.** `prompt_tokens` is
            always `1000 × image count`; the console billing records are
            authoritative
          properties:
            prompt_tokens:
              type: integer
              example: 1000
            total_tokens:
              type: integer
              example: 1000
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: API Key from the APIYI console (Token group must include GrokOfficial)

````

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