curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "MAI-Image-2.6-Flash",
"prompt": "A traditional teahouse storefront with a wooden sign that reads \"Welcome\", red lanterns, warm dusk light, photorealistic"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "MAI-Image-2.6-Flash",
"prompt": "A traditional teahouse storefront with a wooden sign that reads \"Welcome\", red lanterns, warm dusk light, photorealistic"
}
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: 'MAI-Image-2.6-Flash',
prompt: 'A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic'
})
};
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' => 'MAI-Image-2.6-Flash',
'prompt' => 'A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic'
]),
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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\n}"
response = http.request(request)
puts response.read_body{
"created": 1790999642,
"data": [
{
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"output_tokens": 0
}
}Справочник по Text-to-Image API
Справочник по Text-to-Image API MAI-Image 2.6 с интерактивным Playground — генерация по текстовому prompt, настраиваемая ширина и высота с площадью до 1536×1536, всегда возвращает PNG в base64
curl --request POST \
--url https://api.apiyi.com/v1/images/generations \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "MAI-Image-2.6-Flash",
"prompt": "A traditional teahouse storefront with a wooden sign that reads \"Welcome\", red lanterns, warm dusk light, photorealistic"
}
'import requests
url = "https://api.apiyi.com/v1/images/generations"
payload = {
"model": "MAI-Image-2.6-Flash",
"prompt": "A traditional teahouse storefront with a wooden sign that reads \"Welcome\", red lanterns, warm dusk light, photorealistic"
}
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: 'MAI-Image-2.6-Flash',
prompt: 'A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic'
})
};
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' => 'MAI-Image-2.6-Flash',
'prompt' => 'A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic'
]),
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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\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\": \"MAI-Image-2.6-Flash\",\n \"prompt\": \"A traditional teahouse storefront with a wooden sign that reads \\\"Welcome\\\", red lanterns, warm dusk light, photorealistic\"\n}"
response = http.request(request)
puts response.read_body{
"created": 1790999642,
"data": [
{
"b64_json": "<string>"
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"output_tokens": 0
}
}Bearer sk-xxx), выберите model, укажите prompt, при необходимости настройте width / height и отправьте запрос.response_format, seed или negative_prompt; отправка любого из них возвращает 400 Invalid parameters: xxx. Если вы мигрируете с gpt-image / DALL·E, сначала удалите response_format. Ответ всегда возвращается как data[0].b64_json.size и всегда генерирует 1024×1024. Используйте целочисленные width + height (всегда вместе): каждая сторона ≥ 768, width × height ≤ 2 359 296 (область 1536×1536).Примеры кода
Python (OpenAI SDK)
from openai import OpenAI
import base64
client = OpenAI(
api_key="sk-your-api-key",
base_url="https://api.apiyi.com/v1",
timeout=180.0 # synchronous call, give it enough time
)
resp = client.images.generate(
model="MAI-Image-2.6-Flash",
prompt='A traditional teahouse storefront with a wooden sign that reads "Welcome", red lanterns, warm dusk light, photorealistic',
# width / height are not standard OpenAI SDK fields, so pass them via extra_body
# Do not pass response_format: it returns 400
extra_body={"width": 1024, "height": 1024}
)
with open("out.png", "wb") as f:
f.write(base64.b64decode(resp.data[0].b64_json))
Python (requests)
import base64
import os
import requests
response = requests.post(
"https://api.apiyi.com/v1/images/generations",
headers={"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}"},
json={
"model": "MAI-Image-2.6",
"prompt": "A red fox sitting on a mossy rock in a misty forest, soft morning light, photorealistic",
"width": 1536,
"height": 1024
},
timeout=180
)
response.raise_for_status()
with open("out.png", "wb") as f:
f.write(base64.b64decode(response.json()["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": "MAI-Image-2.6-Flash",
"prompt": "A minimalist coffee shop poster with the headline \"Autumn Special\" at the top, warm brown palette",
"width": 1024,
"height": 1536
}' | python3 -c "import sys,json,base64; open('out.png','wb').write(base64.b64decode(json.load(sys.stdin)['data'][0]['b64_json']))"
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 ${process.env.APIYI_API_KEY}`
},
body: JSON.stringify({
model: 'MAI-Image-2.6-Flash',
prompt: 'A serene Japanese garden with cherry blossoms, koi pond, golden hour',
width: 1792,
height: 1008 // 16:9; width × height must not exceed 2,359,296
}),
signal: AbortSignal.timeout(120000)
});
const data = await resp.json();
fs.writeFileSync('out.png', Buffer.from(data.data[0].b64_json, 'base64'));
Нужно несколько изображений: отправляйте параллельные запросы
Эндпоинт генерации изображений по тексту возвращает 1 изображение за вызов (n не имеет эффекта), поэтому выполняйте запросы параллельно:
import base64, os, requests
from concurrent.futures import ThreadPoolExecutor
def gen(i):
r = requests.post(
"https://api.apiyi.com/v1/images/generations",
headers={"Authorization": f"Bearer {os.environ['APIYI_API_KEY']}"},
json={"model": "MAI-Image-2.6-Flash", "prompt": "a watercolor lighthouse at dusk"},
timeout=120
)
r.raise_for_status()
open(f"out-{i}.png", "wb").write(base64.b64decode(r.json()["data"][0]["b64_json"]))
with ThreadPoolExecutor(max_workers=4) as pool:
list(pool.map(gen, range(4)))
Справочник параметров
| Параметр | Тип | Обязательный | По умолчанию | Описание |
|---|---|---|---|---|
model | string | ✅ | — | MAI-Image-2.6 ($0.12/изображение) или MAI-Image-2.6-Flash ($0.06/изображение), с учётом регистра |
prompt | string | ✅ | — | Prompt на любом языке. Текст, который должен появиться на изображении, заключайте в кавычки |
width | integer | ❌ | 1024 | Ширина вывода. ≥ 768, должна передаваться вместе с height, округляется в меньшую сторону до значения, кратного 16 |
height | integer | ❌ | 1024 | Высота вывода. ≥ 768; ширина × высота ≤ 2,359,296 |
response_format | — | — | — | Возвращает 400; ответ всегда b64_json |
seednegative_prompt | — | — | — | Возвращают 400 |
size | — | — | — | Молча игнорируется на этом эндпоинте |
n | — | — | — | Не влияет на этот эндпоинт; всегда 1 изображение |
quality, output_format, background, style и другие поля в стиле OpenAI молча игнорируются. Результат всегда в формате PNG.Формат ответа
{
"created": 1790999642,
"data": [
{
"b64_json": "iVBORw0KGgoAAAANSUhEUgAABAAAAAQACAIAAADwf7zU..."
}
],
"usage": {
"prompt_tokens": 1000,
"total_tokens": 1000,
"input_tokens": 1000,
"output_tokens": 0
}
}
b64_json— это обычный base64 без префиксаdata:image/png;base64,. Декодируйте его напрямую, чтобы получить PNG.- Поле
urlотсутствует, как иrevised_prompt. - PNG размером 1024×1024 занимает около 1,5–1,7 МБ (2,1–2,3 МБ в виде base64); 1536×1536 — около 4–5 МБ. Проверьте ограничения вашего клиента на размер ответа.
usage: prompt_tokens всегда равен 1000 × количество изображений, а output_tokens всегда равен 0; это плейсхолдеры. Данная серия тарифицируется за изображение, а данные в консоли APIYI являются определяющими.Авторизации
API key from the APIYI console
Тело
Model ID (case-sensitive). 2.6 favors quality, Flash favors speed
MAI-Image-2.6-Flash, MAI-Image-2.6 Prompt in any language. Put text that should appear in the image in quotes
"A traditional teahouse storefront with a wooden sign that reads \"Welcome\", red lanterns, warm dusk light, photorealistic"
Output width in pixels. Each side ≥ 768, width × height ≤ 2,359,296 (a 1536×1536 area);
must be sent together with height; rounded down to a multiple of 16.
x >= 7681024
Output height in pixels, same rules as width
x >= 7681024
Ответ
Image generated
Creation timestamp
1790999642
Image results; always 1 item for text-to-image
Show child attributes
Show child attributes
Placeholder values, not for billing reconciliation. prompt_tokens is always 1000 × images and output_tokens is always 0.
The console bill is authoritative.
Show child attributes
Show child attributes
Была ли эта страница полезной?