Text-to-Image: generate an image from a text prompt
curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "gpt-image-2-all",
"prompt": "Landscape 16:9 cinematic, old lighthouse at sunset"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "gpt-image-2-all",
"prompt": "Landscape 16:9 cinematic, old lighthouse at sunset"
}
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: 'gpt-image-2-all',
prompt: 'Landscape 16:9 cinematic, old lighthouse at sunset'
})
};
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' => 'gpt-image-2-all',
'prompt' => 'Landscape 16:9 cinematic, old lighthouse at sunset'
]),
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\": \"gpt-image-2-all\",\n \"prompt\": \"Landscape 16:9 cinematic, old lighthouse at sunset\"\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\": \"gpt-image-2-all\",\n \"prompt\": \"Landscape 16:9 cinematic, old lighthouse at sunset\"\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\": \"gpt-image-2-all\",\n \"prompt\": \"Landscape 16:9 cinematic, old lighthouse at sunset\"\n}"
response = http.request(request)
puts response.read_body{
"data": [
{
"b64_json": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}
],
"created": 1778037127,
"usage": {
"input_tokens": 98,
"output_tokens": 1185,
"total_tokens": 1283
}
}GPT-Image-2-All 이미지 생성
텍스트-투-이미지 API 레퍼런스
gpt-image-2-all 텍스트-투-이미지 API 레퍼런스 및 인터랙티브 플레이그라운드 — 텍스트 프롬프트로 이미지를 생성합니다, $0.03/이미지
POST
/
v1
/
images
/
generations
Text-to-Image: generate an image from a text prompt
curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "gpt-image-2-all",
"prompt": "Landscape 16:9 cinematic, old lighthouse at sunset"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "gpt-image-2-all",
"prompt": "Landscape 16:9 cinematic, old lighthouse at sunset"
}
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: 'gpt-image-2-all',
prompt: 'Landscape 16:9 cinematic, old lighthouse at sunset'
})
};
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' => 'gpt-image-2-all',
'prompt' => 'Landscape 16:9 cinematic, old lighthouse at sunset'
]),
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\": \"gpt-image-2-all\",\n \"prompt\": \"Landscape 16:9 cinematic, old lighthouse at sunset\"\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\": \"gpt-image-2-all\",\n \"prompt\": \"Landscape 16:9 cinematic, old lighthouse at sunset\"\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\": \"gpt-image-2-all\",\n \"prompt\": \"Landscape 16:9 cinematic, old lighthouse at sunset\"\n}"
response = http.request(request)
puts response.read_body{
"data": [
{
"b64_json": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
}
],
"created": 1778037127,
"usage": {
"input_tokens": 98,
"output_tokens": 1185,
"total_tokens": 1283
}
}오른쪽의 대화형 Playground는 직접 온라인 테스트를 지원합니다. Authorization 필드에 API 키를 입력하고(형식:
Bearer sk-xxx), prompt를 입력한 뒤 전송을 클릭합니다.범위: 이 페이지는 텍스트-투-이미지 생성용입니다. prompt만 입력하면 되며 이미지 업로드는 필요하지 않습니다. 기존 이미지를 편집하거나 합성하려면 이미지 편집 엔드포인트를 사용하십시오.
🖥️ 브라우저 Playground 제한(기본 b64_json 모드)이 엔드포인트는 기본적으로
response_format: "b64_json"를 사용하므로, 응답에 수 MB 크기의 base64 문자열이 포함되고 브라우저 Playground에 请求时发生错误: unable to complete request가 표시될 수 있습니다. — 요청은 실제로 성공한 것입니다; 브라우저가 이렇게 긴 base64 문자열을 렌더링할 수 없을 뿐입니다.권장 워크플로:- Playground에서 이미지만 확인하고 싶으신가요?
"response_format": "url"를 명시적으로 전달하십시오 — 응답은 단일 R2 링크이며 문제없이 렌더링됩니다. - base64가 필요하신가요? 아래 코드 샘플을 복사해 로컬에서 실행하십시오 — 코드가 이미지를 자동으로 디코딩하고 파일로 저장합니다.
모든 이미지 API는 동기식입니다 — 조회할 task ID가 없으며, 클라이언트가 연결을 끊으면 요청은 여전히 과금된 상태로 유지되지만 결과는 사라집니다. 이 모델에는 넉넉한 timeout을 설정하십시오. Image API Essentials & Best Practices를 참조하십시오.
⚠️ 파라미터 지원
size: 이 필드는 효과가 없습니다 —auto나 어떤 구체적인 값을 보내도 오류는 발생하지 않지만, 해당 값은 서버에서 조용히 무시됩니다. 크기는 전적으로 prompt에 의해 결정됩니다:- prompt에 크기/비율이 언급된 경우(예: “Landscape 16:9”) → 모델이 prompt를 따릅니다
- prompt에 크기 힌트가 없는 경우 → 같은 prompt라도 호출마다 서로 다른 크기가 나오며, 마치 “다른 카드를 뽑는 것”과 같습니다 — 여러 구성을 탐색할 때 유용합니다
- 크기를 엄격하게 고정하려면
gpt-image-2-vip를 사용하십시오(auto+ 30개의 명시적 크기 지원)
n/quality/aspect_ratio: ❌ 거부됩니다. 이를 보내면 파라미터 검증 오류가 발생할 수 있습니다.
prompt에 직접 작성하십시오. 예:Landscape 16:9 cinematic, old lighthouse by the sea at duskPortrait 9:16 phone wallpaper, cyberpunk city rainy night1024×1024 square logo, minimalist cat line art
코드 예시
Python
import requests
API_KEY = "sk-your-api-key"
response = requests.post(
"https://api.apiyi.com/v1/images/generations",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"model": "gpt-image-2-all",
"prompt": "Landscape 16:9 cinematic, old lighthouse at sunset, photorealistic",
"response_format": "url"
},
timeout=300 # conservative — absorbs tail latency + image download time
).json()
image_url = response["data"][0]["url"]
print(image_url)
import base64
import requests
response = requests.post(
"https://api.apiyi.com/v1/images/generations",
headers={"Authorization": "Bearer sk-your-api-key"},
json={
"model": "gpt-image-2-all",
"prompt": "1024x1024 square logo, minimalist cat line art",
"response_format": "b64_json"
},
timeout=300 # conservative — absorbs tail latency + image download time
).json()
# Verified 2026-07: b64_json is raw base64 (no data: prefix); earlier versions included the prefix — a check is safest
b64 = response["data"][0]["b64_json"]
if b64.startswith("data:"):
b64 = b64.split(",", 1)[1]
with open("output.png", "wb") as f:
f.write(base64.b64decode(b64))
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": "gpt-image-2-all",
"prompt": "Landscape 16:9 cinematic, old lighthouse at sunset",
"response_format": "url"
}'
Node.js
const API_KEY = "sk-your-api-key";
const response = await fetch(
"https://api.apiyi.com/v1/images/generations",
{
method: "POST",
headers: {
"Authorization": `Bearer ${API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "gpt-image-2-all",
prompt: "1024x1024 square logo, minimalist cat line art",
response_format: "b64_json"
})
}
);
const data = await response.json();
// Verified raw base64 (no data: prefix) — prepend before rendering; earlier versions included the prefix, so check first
let b64 = data.data[0].b64_json;
if (!b64.startsWith("data:")) b64 = `data:image/png;base64,${b64}`;
document.getElementById("result").src = b64;
브라우저 JavaScript (Fetch)
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: 'gpt-image-2-all',
prompt: 'Portrait 9:16 phone wallpaper, cyberpunk city rainy night',
response_format: 'b64_json'
})
});
const { data } = await resp.json();
let b64 = data[0].b64_json;
if (!b64.startsWith('data:')) b64 = `data:image/png;base64,${b64}`;
document.getElementById('result').src = b64;
파라미터 빠른 참조
| 파라미터 | 유형 | 필수 | 설명 |
|---|---|---|---|
model | string | Yes | 고정값: gpt-image-2-all |
prompt | string | Yes | Prompt. 크기/비율/스타일을 여기에 포함합니다 |
size | string | No | auto만 허용됩니다(동일한 prompt라도 서로 다른 크기가 생성됩니다). 엄격하게 크기를 고정하려면 gpt-image-2-vip을 사용하십시오 |
response_format | string | No | b64_json(기본값, raw base64) 또는 url(R2 CDN 링크를 반환함); 항상 명시적으로 전달하십시오 |
자세한 파라미터 제약과 허용 값은 오른쪽 Playground에 표시됩니다.
response_format 필드는 드롭다운 선택을 지원합니다.응답 형식
data[0]는 url 또는 b64_json 중 하나만 반환합니다 — 둘 다는 아닙니다 (response_format에 따라 다릅니다). 이 엔드포인트는 기본값이 b64_json입니다.
b64_json 모드 (기본값):
{
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAA..."
}
],
"created": 1778037127,
"usage": {
"input_tokens": 98,
"output_tokens": 1185,
"total_tokens": 1283
}
}
url 모드 (명시적인 "response_format": "url"가 필요합니다, R2 CDN 전역 가속 적용):
{
"data": [
{
"url": "https://r2cdn.copilotbase.com/r2cdn2/0e82148a-bec0-4b42-bbca-117c6b42581b.png"
}
],
"created": 1778037331,
"usage": {
"input_tokens": 30,
"output_tokens": 2074,
"total_tokens": 2104
}
}
호환성 참고: 2026년 7월 검증됨 —
b64_json 필드는 data: 접두사가 없는 원시 base64입니다. 파일을 기록하려면 디코드하거나, 렌더링하기 전에 직접 접두사를 추가하십시오. 이전 버전에는 접두사가 포함되어 있었습니다, 따라서 두 형태를 모두 처리할 수 있도록 항상 먼저 startsWith('data:') 검사를 실행하십시오.인증
API Key from the API易 Console
본문
application/json
Model name, fixed to gpt-image-2-all
사용 가능한 옵션:
gpt-image-2-all Prompt. Include size/ratio/style here, e.g., Landscape 16:9 cinematic, old lighthouse at sunset
예시:
"Landscape 16:9 cinematic, old lighthouse at sunset"
Response format. b64_json returns a base64 string already prefixed with a data URL header (default); url returns an R2 CDN link
사용 가능한 옵션:
b64_json, url 응답
Image successfully generated. Defaults to base64 in data[0].b64_json — url is not returned in the same response.
Image generation response. data[0] returns either url or b64_json, never both (depends on response_format; this endpoint defaults to b64_json).
이 페이지가 도움이 되었나요?
⌘I