> ## 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 概要 - グループ設定](/ja/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回の呼び出しにつき1枚の画像。このチャネルは現時点では画像編集を提供していません。参照画像に基づく編集や1回の呼び出しで複数枚の画像を生成する場合は、[Grok Imagine Reverse](/ja/api-capabilities/grok-imagine-image/overview)をご利用ください。

> [!WARNING]
>
> **⚠️ よくある3つの落とし穴**
>
> 1. **`size` ではなく `resolution` を使用する**: `size` は解像度階層にマッピングされないため、画像はデフォルトの `1k` で生成され、課金されます。
> 2. **誤りがあるとエラーが返される**: 範囲外の `resolution` / `aspect_ratio` は 422 を返し、`quality: "high"` は 400 を返します。これはリバースチャネルのサイレントフォールバックとは逆の動作です。
> 3. **常に `n` = 1 を送信する**: 複数枚の画像が必要な場合は、複数のリクエストを並行して送信してください。

> [!NOTE]
>
> すべての画像 API は**同期型**です。非同期タスク ID は存在しないため、クライアントが切断されると結果は失われますが、リクエストは課金されます。`medium` および 2K での `grok-imagine-image-2.0` には約60〜80秒かかるため、**クライアントのタイムアウトを360秒に設定してください**。詳細は[画像 API の注意事項とベストプラクティス](/ja/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:`プレフィックスなし） |

**画像1枚あたりの価格**（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[]` の各項目には、**いずれか**の `url` または `b64_json` が含まれ、どちらになるかは `response_format` によって異なります。
> * 返却された画像リンクはすぐにダウンロードしてください。そのまま参照し続けないでください。
> * `usage` はプレースホルダーであり（`prompt_tokens` は常に `1000 × image count` です）、**照合には使用できません** — コンソールの課金記録が正式な情報となります。
> * `created` は常に 0 です。時間計測には使用しないでください。

## 関連ドキュメント

* [Grok Imagine 公式概要](/ja/api-capabilities/grok-imagine-image-official/overview) - 料金、グループの適用、公式とリバースの比較
* [Grok Imagine 動画生成](/ja/api-capabilities/grok-imagine-video/overview) - 同一グループ、秒単位での課金
* [Grok Imagine リバース](/ja/api-capabilities/grok-imagine-image/overview) - 画像編集および1回のリクエストでの複数画像生成


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