curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "grok-imagine-image",
"prompt": "A photorealistic red wooden boat moored on a glassy alpine lake at dawn, mist over the water, snow-capped peaks behind, cinematic photography"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "grok-imagine-image",
"prompt": "A photorealistic red wooden boat moored on a glassy alpine lake at dawn, mist over the water, snow-capped peaks behind, cinematic photography"
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
model: 'grok-imagine-image',
prompt: 'A photorealistic red wooden boat moored on a glassy alpine lake at dawn, mist over the water, snow-capped peaks behind, cinematic photography'
})
};
fetch('https://api.apiyi.com/v1/images/generations', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.apiyi.com/v1/images/generations",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'model' => 'grok-imagine-image',
'prompt' => 'A photorealistic red wooden boat moored on a glassy alpine lake at dawn, mist over the water, snow-capped peaks behind, cinematic photography'
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.apiyi.com/v1/images/generations"
payload := strings.NewReader("{\n \"model\": \"grok-imagine-image\",\n \"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}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.apiyi.com/v1/images/generations")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"grok-imagine-image\",\n \"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}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.apiyi.com/v1/images/generations")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"grok-imagine-image\",\n \"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}"
response = http.request(request)
puts response.read_body{
"created": 0,
"data": [
{
"url": "<string>",
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000
}
}Справочник по официальному API генерации изображений по тексту Grok Imagine
Справочник и интерактивное тестирование официального API генерации изображений по тексту Grok Imagine — три модели, уровни разрешения 1k / 1.5k / 2k, качество low / medium в 2.0, тарификация по уровням аналогично xAI
curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "grok-imagine-image",
"prompt": "A photorealistic red wooden boat moored on a glassy alpine lake at dawn, mist over the water, snow-capped peaks behind, cinematic photography"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "grok-imagine-image",
"prompt": "A photorealistic red wooden boat moored on a glassy alpine lake at dawn, mist over the water, snow-capped peaks behind, cinematic photography"
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
model: 'grok-imagine-image',
prompt: 'A photorealistic red wooden boat moored on a glassy alpine lake at dawn, mist over the water, snow-capped peaks behind, cinematic photography'
})
};
fetch('https://api.apiyi.com/v1/images/generations', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.apiyi.com/v1/images/generations",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'model' => 'grok-imagine-image',
'prompt' => 'A photorealistic red wooden boat moored on a glassy alpine lake at dawn, mist over the water, snow-capped peaks behind, cinematic photography'
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.apiyi.com/v1/images/generations"
payload := strings.NewReader("{\n \"model\": \"grok-imagine-image\",\n \"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}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.apiyi.com/v1/images/generations")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"grok-imagine-image\",\n \"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}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.apiyi.com/v1/images/generations")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"grok-imagine-image\",\n \"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}"
response = http.request(request)
puts response.read_body{
"created": 0,
"data": [
{
"url": "<string>",
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000
}
}GrokOfficial, доступ предоставляется по заявке: Grok Imagine Official не входит в группу Default; перед вызовом необходимо запросить доступ (включая Playground на этой странице). Без доступа или с pay-per-request Token каждый вызов возвращает 503. См. Обзор Grok Imagine Official — Настройка группы.Bearer sk-xxx), заполните prompt, выберите модель, resolution и aspect_ratio (а также quality для 2.0) и выполните отправку.- Используйте
resolution, а неsize:sizeне привязан к уровню разрешения, поэтому изображение генерируется и тарифицируется по умолчанию как1k. - Ошибки возвращают код ошибки: выход
resolution/aspect_ratioза пределы диапазона возвращает 422, аquality: "high"возвращает 400 — в отличие от незаметного отката к значениям по умолчанию в reverse-канале. - Всегда передавайте
n= 1: для получения нескольких изображений отправляйте несколько параллельных запросов.
grok-imagine-image-2.0 при medium и 2K занимает около 60–80 секунд, поэтому установите таймаут клиента на 360 секунд. См. Примечания и рекомендации по Image API.Примеры кода
Python (OpenAI SDK)
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)
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
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)
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:) |
| Модель | 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 |
Формат ответа
{
"created": 0,
"data": [
{ "url": "https://.../sync_xxxxxxxx_0.png" }
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000
}
}
- Каждый элемент в
data[]содержит либоurl, либоb64_json, в зависимости отresponse_format. - Скачивайте изображения по полученным ссылкам сразу же; не используйте эти ссылки для постоянного обращения.
usageявляется плейсхолдером (prompt_tokensвсегда1000 × image count) и не может использоваться для сверки — определяющими являются записи тарификации в консоли.createdвсегда равен 0; не используйте его для измерения времени.
Связанная документация
- Grok Imagine: официальный обзор — цены, применение группы, официальный релей против reverse
- Grok Imagine: видео — та же группа, посекундная тарификация
- Grok Imagine: reverse — редактирование изображений и несколько изображений за вызов
Авторизации
API Key from the APIYI console (Token group must include GrokOfficial)
Тело
Model ID:
grok-imagine-image— standard, $0.02 per image at every resolutiongrok-imagine-image-quality— high quality, $0.05 / $0.06 / $0.07 at 1k / 1.5k / 2kgrok-imagine-image-2.0— newer model,low$0.04 / $0.05 / $0.06,medium$0.06 / $0.07 / $0.08
grok-imagine-image, grok-imagine-image-quality, grok-imagine-image-2.0 Prompt in any language. Describe the subject, scene, style, and lighting in detail
"A photorealistic red wooden boat moored on a glassy alpine lake at dawn, mist over the water, snow-capped peaks behind, cinematic photography"
Image count. Fixed at 1 on this channel; call concurrently for more images
1 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.
1k, 1.5k, 2k 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.
1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3 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.
low, medium Response format: url (default; download and store the image right away) or b64_json (plain base64, no data: prefix)
url, b64_json Ответ
Image generated successfully
Была ли эта страница полезной?