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": "https://apac.ossforai.com/2026/08/12/1ab87d04-3637-464f-bafd-f026cac05dd3.jpg",
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"output_tokens": 0
}
}텍스트-이미지 API 레퍼런스
Grok Imagine 2 텍스트-이미지 API 레퍼런스 및 실시간 테스트 — prompt만으로 생성하는 방식으로 5개 화면 비율, 1K/2K 등급, 호출당 최대 10장까지 이미지 생성
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": "https://apac.ossforai.com/2026/08/12/1ab87d04-3637-464f-bafd-f026cac05dd3.jpg",
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"output_tokens": 0
}
}Bearer sk-xxx), prompt을 입력한 다음, aspect_ratio / resolution를 선택하고 전송합니다.image / image_url / images를 전달해도 오류가 발생하지 않습니다. 200을 반환하고 prompt에서 새 이미지를 생성합니다 — 참조 이미지는 조용히 버려지며 여전히 과금됩니다.오류 신호가 없으므로, 보통은 출력이 입력과 전혀 관련이 없다는 것을 누군가 알아차릴 때서야 드러납니다. 참조 이미지가 포함된 모든 워크플로우는 /v1/images/edits를 사용해야 합니다.aspect_ratio(예: 5:7), resolution(예: 1K, 1024x1024) 및 response_format(예: base64)는 모두 기본값으로 조용히 되돌아가며 여전히 이미지를 반환합니다. 출력이 예상과 다르면 먼저 매개변수 철자를 확인하십시오 — resolution 값은 소문자 1k / 2k입니다.예외가 하나 있습니다: resolution: "4k"는 503 model_service_unavailable를 반환하며, 이는 티어가 지원되지 않음을 의미하고 채널이 다운되었다는 뜻이 아닙니다. 재시도해도 도움이 되지 않습니다.코드 예제
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 # image APIs are synchronous — allow plenty of time
)
resp = client.images.generate(
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",
n=1,
# aspect_ratio / resolution are not standard OpenAI SDK fields — pass via extra_body
extra_body={
"aspect_ratio": "16:9",
"resolution": "1k",
"response_format": "url"
}
)
# response_format defaults to url, returning a direct link (.jpg for 1K, .png for 2K)
urllib.request.urlretrieve(resp.data[0].url, "out.jpg")
Python (raw 요청)
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",
"prompt": "Cyberpunk city on a rainy night, neon signage close-up, cinematic lighting",
"n": 1,
"aspect_ratio": "16:9",
"resolution": "2k", # 2k returns PNG at 5-6 MB per image
"response_format": "b64_json"
},
timeout=360 # 2K takes 15-17s and longer at peak; 60s causes spurious timeouts
).json()
# b64_json is raw base64 with no data: prefix — decode and write directly
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-quality",
"prompt": "An orange tabby cat wearing sunglasses at a seaside bar, photorealistic, warm sunset tones",
"n": 1,
"aspect_ratio": "16:9",
"resolution": "1k",
"response_format": "url"
}'
Node.js (기본 fetch)
import fs from 'node:fs';
const resp = await 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',
prompt: 'A serene Japanese garden with cherry blossoms, koi pond, golden hour',
n: 2, // up to 10 per call, billed per image
aspect_ratio: '4:3',
resolution: '1k',
response_format: 'url'
}),
// Node 18+ has no default timeout — use AbortSignal.timeout in production
signal: AbortSignal.timeout(360000)
});
const data = await resp.json();
// with n=2 the data array holds two entries — download each
for (const [i, item] of data.data.entries()) {
const img = await fetch(item.url);
fs.writeFileSync(`out-${i}.jpg`, Buffer.from(await img.arrayBuffer()));
}
브라우저 JavaScript
// ⚠️ Demo only: a front-end key is exposed — use a backend proxy in production
const resp = await 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',
prompt: 'a minimalist poster of a mountain at sunrise, flat vector style',
aspect_ratio: '3:4',
resolution: '1k',
response_format: 'url' // url is far lighter than b64_json in a browser
})
});
const data = await resp.json();
document.querySelector('#preview').src = data.data[0].url;
매개변수 참조
| 매개변수 | 유형 | 필수 여부 | 기본값 | 설명 |
|---|---|---|---|---|
model | string | ✅ | — | grok-imagine-image ($0.02/이미지) 또는 grok-imagine-image-quality ($0.045/이미지) |
prompt | string | ✅ | — | 영어 또는 중국어로 된 prompt입니다. 주제, 장면, 스타일, 조명을 설명하십시오 |
n | integer | ❌ | 1 | 호출당 이미지 수, 1-10, 이미지당 과금됩니다. 0는 1가 되며; ≥11은 400을 반환합니다 |
aspect_ratio | string | ❌ | 1:1 | 1:1 / 16:9 / 9:16 / 4:3 / 3:4; 다른 값은 조용히 1:1로 대체됩니다 |
resolution | string | ❌ | 1k | 1k (JPEG, ~1 MP) 또는 2k (PNG, ~4.2-4.5 MP). 가격은 동일합니다; 4k은 503을 반환합니다 |
response_format | string | ❌ | url | url은 직접 링크를 반환하고; b64_json은 원시 base64를 반환합니다(no data: 접두사) |
aspect_ratio | 1k | 2k |
|---|---|---|
1:1 | 1024x1024 | 2048x2048 |
16:9 | 1280x720 | 2816x1584 |
9:16 | 720x1280 | 1584x2816 |
4:3 | 1152x864 | 2368x1776 |
3:4 | 864x1152 | 1776x2368 |
seed은 지원되지 않습니다(오류 없이 수락되지만 아무 효과가 없으며 — 결과를 재현할 수 없습니다), 마스크 inpainting도 지원되지 않습니다. size / quality / style와 같은 OpenAI 스타일 필드는 조용히 무시됩니다.응답 형식
{
"created": 0,
"data": [
{
"url": "https://apac.ossforai.com/2026/08/12/1ab87d04-3637-464f-bafd-f026cac05dd3.jpg"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"output_tokens": 0
}
}
- 각
data[]항목에는response_format에 따라url또는b64_json중 하나만 포함됩니다 — 둘 다 포함되지 않습니다. revised_prompt은 반환되지 않습니다, 또한respect_moderation/model도 반환되지 않습니다. 존재한다고 가정하지 마십시오.b64_json은data:image/...;base64,접두사가 없는 원시 base64입니다 — 직접 디코딩하십시오.created는 항상0이며 타임스탬프로 사용할 수 없습니다.n > 1을 사용할 때data배열에는 여러 항목이 들어 있습니다 —data[0]만 읽지 마십시오.
usage는 정산에 사용할 수 없습니다: prompt_tokens은 실제 prompt 길이와 무관하게 항상 1000 x n입니다. 이 계열은 이미지당 정액 요금($0.02 / $0.045)으로 과금됩니다; 실제 청구 금액은 APIYI 콘솔 과금 기록을 사용하십시오.인증
API Key created in the APIYI Console
본문
Model ID. The quality variant delivers higher fidelity at a higher price
grok-imagine-image, grok-imagine-image-quality Prompt, English or Chinese. Describe 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"
Number of images, 1-10. Values of 11 or above return 400; 0 is silently treated as 1
1 <= x <= 101
Output aspect ratio. Actual pixel dimensions per resolution tier:
| Aspect ratio | 1k | 2k |
|---|---|---|
1:1 | 1024x1024 | 2048x2048 |
16:9 | 1280x720 | 2816x1584 |
9:16 | 720x1280 | 1584x2816 |
4:3 | 1152x864 | 2368x1776 |
3:4 | 864x1152 | 1776x2368 |
Values outside this enum do not raise an error — they silently fall back to 1:1.
1:1, 16:9, 9:16, 4:3, 3:4 "16:9"
Resolution tier. 1k is roughly 0.9-1.05 megapixels and returns JPEG;
2k is roughly 4.2-4.5 megapixels and returns PNG (5-6 MB per image).
Both tiers cost the same.
4k returns 503; other invalid values (such as 1K or 1024x1024) silently fall back to 1k.
1k, 2k "1k"
Response format. url returns a direct image link (no signed query params);
b64_json returns a raw base64 string (without the data: prefix).
Invalid values silently fall back to the default url.
url, b64_json "url"
응답
Images generated successfully
Creation timestamp. Always 0 for this model — do not use it for timing
0
Array of image results, length equals the requested n
Show child attributes
Show child attributes
Placeholder values — do not use for billing reconciliation. prompt_tokens is always
1000 x n, regardless of actual prompt length. Use the Console billing records instead.
Show child attributes
Show child attributes
이 페이지가 도움이 되었나요?