Text-to-image: generate an image from a prompt (official channel)
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
}
}Grok Imagine 공식 이미지 생성
Grok Imagine 공식 텍스트-이미지 API 레퍼런스
Grok Imagine 공식 텍스트-이미지 API 레퍼런스 및 실시간 테스트 — 3개 모델, 1k / 1.5k / 2k 해상도 등급, 2.0에서 낮음 / 중간 품질 지원, 등급별로 xAI와 동일한 가격
POST
/
v1
/
images
/
generations
Text-to-image: generate an image from a prompt (official channel)
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 공식은 Default 그룹에 속하지 않으므로 호출하려면 먼저 액세스를 요청해야 합니다(이 페이지의 플레이그라운드 포함). 액세스 권한이 없거나 요청당 결제 Token을 사용하는 경우 모든 호출이 503를 반환합니다. Grok Imagine 공식 개요 - 그룹 설정을 참조하십시오.오른쪽의 대화형 플레이그라운드에서 엔드포인트를 직접 테스트할 수 있습니다. Authorization에 API Key를 입력하고(형식:
Bearer sk-xxx), prompt를 입력한 다음 모델을 선택하고, resolution 및 aspect_ratio(2.0의 경우 quality도 포함)을 설정한 후 전송하십시오.이 페이지를 사용해야 하는 경우: 텍스트-이미지 변환 및 호출당 이미지 한 장입니다. 이 채널은 아직 이미지 편집을 제공하지 않습니다. 참조 기반 편집이나 호출당 여러 이미지를 사용하려면 Grok Imagine 역방향을 사용하십시오.
⚠️ 가장 흔한 실수 세 가지
size가 아닌resolution사용:size는 해상도 등급에 매핑되지 않으므로 이미지가 기본1k로 생성되고 과금됩니다.- 실수하면 오류가 반환됩니다: 범위를 벗어난
resolution/aspect_ratio는 422를 반환하고quality: "high"는 400을 반환합니다. 이는 역방향 채널에서 자동으로 대체되는 동작과 반대입니다. - 항상
n= 1 전송: 여러 이미지를 생성하려면 여러 요청을 동시에 전송하십시오.
모든 이미지 API는 동기식입니다. 비동기 작업 ID가 없으므로 클라이언트 연결이 끊기면 결과는 손실되지만 요청에는 계속 과금됩니다. 80초가 걸리고 2K는 약 6080초가 걸리므로 클라이언트 타임아웃을 360초로 설정하십시오. 이미지 API 참고 사항 및 모범 사례를 참조하십시오.
grok-imagine-image-2.0는 medium에서 약 60코드 예제
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 | 문자열 | ✅ | — | grok-imagine-image / grok-imagine-image-quality / grok-imagine-image-2.0 |
prompt | 문자열 | ✅ | — | 모든 언어로 작성할 수 있는 prompt입니다. 주제, 장면, 스타일 및 조명을 설명합니다 |
n | 정수 | ❌ | 1 | 이 채널에서는 항상 1입니다. 더 많은 이미지를 생성하려면 동시에 호출합니다 |
resolution | 문자열 | ❌ | 1k | 1k / 1.5k / 2k(소문자)이며, 가격 등급을 설정합니다. 범위를 벗어난 값은 422를 반환합니다 |
aspect_ratio | 문자열 | ❌ | 1:1 | 일반적인 값: 1:1 / 16:9 / 9:16 / 4:3 / 3:4 / 3:2 / 2:3입니다. 범위를 벗어난 값은 422를 반환합니다 |
quality | 문자열 | ❌ | low | grok-imagine-image-2.0만 지원합니다: low 또는 medium입니다. high은 400을 반환합니다 |
response_format | 문자열 | ❌ | 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[]의 각 항목에는response_format에 따라url또는b64_json가 있습니다.- 반환된 이미지 링크는 즉시 다운로드하고 계속 참조하지 마십시오.
usage은 플레이스홀더입니다(prompt_tokens은 항상1000 × image count임). 대조에 사용할 수 없으며, 콘솔 과금 기록이 기준입니다.created은 항상 0이므로 타이밍에 사용하지 마십시오.
관련 문서
- Grok Imagine 공식 개요 - 가격, 그룹 신청, 공식 릴레이와 리버스 릴레이
- Grok Imagine 동영상 - 동일한 그룹, 초당 과금
- Grok Imagine 리버스 - 이미지 편집 및 호출당 여러 이미지
본문
application/json
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 응답
Image generated successfully
이 페이지가 도움이 되었나요?