Перейти к основному содержанию
POST
/
v1
/
images
/
generations
curl --request POST \
  --url https://api.apimart.ai/v1/images/generations \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '{
    "model": "gpt-image-2-official",
    "prompt": "An ancient castle beneath a starry sky",
    "size": "16:9",
    "resolution": "2k",
    "quality": "high",
    "n": 1
  }'
import requests

url = "https://api.apimart.ai/v1/images/generations"

payload = {
    "model": "gpt-image-2-official",
    "prompt": "An ancient castle beneath a starry sky",
    "size": "16:9",
    "resolution": "2k",
    "quality": "high",
    "n": 1
}

headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
const url = "https://api.apimart.ai/v1/images/generations";

const payload = {
  model: "gpt-image-2-official",
  prompt: "An ancient castle beneath a starry sky",
  size: "16:9",
  resolution: "2k",
  quality: "high",
  n: 1,
};

const headers = {
  Authorization: "Bearer <token>",
  "Content-Type": "application/json",
};

fetch(url, {
  method: "POST",
  headers: headers,
  body: JSON.stringify(payload),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    url := "https://api.apimart.ai/v1/images/generations"

    payload := map[string]interface{}{
        "model":      "gpt-image-2-official",
        "prompt":     "An ancient castle beneath a starry sky",
        "size":       "16:9",
        "resolution": "2k",
        "quality":    "high",
        "n":          1,
    }

    jsonData, _ := json.Marshal(payload)

    req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer <token>")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class Main {
    public static void main(String[] args) throws Exception {
        String url = "https://api.apimart.ai/v1/images/generations";

        String payload = """
        {
          "model": "gpt-image-2-official",
          "prompt": "An ancient castle beneath a starry sky",
          "size": "16:9",
          "resolution": "2k",
          "quality": "high",
          "n": 1
        }
        """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Authorization", "Bearer <token>")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();

        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
<?php

$url = "https://api.apimart.ai/v1/images/generations";

$payload = [
    "model" => "gpt-image-2-official",
    "prompt" => "An ancient castle beneath a starry sky",
    "size" => "16:9",
    "resolution" => "2k",
    "quality" => "high",
    "n" => 1
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer <token>",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>
require 'net/http'
require 'json'
require 'uri'

url = URI("https://api.apimart.ai/v1/images/generations")

payload = {
  model: "gpt-image-2-official",
  prompt: "An ancient castle beneath a starry sky",
  size: "16:9",
  resolution: "2k",
  quality: "high",
  n: 1
}

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 = payload.to_json

response = http.request(request)
puts response.body
import Foundation

let url = URL(string: "https://api.apimart.ai/v1/images/generations")!

let payload: [String: Any] = [
    "model": "gpt-image-2-official",
    "prompt": "An ancient castle beneath a starry sky",
    "size": "16:9",
    "resolution": "2k",
    "quality": "high",
    "n": 1
]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer <token>", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: payload)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }

    if let data = data, let responseString = String(data: data, encoding: .utf8) {
        print(responseString)
    }
}

task.resume()
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var url = "https://api.apimart.ai/v1/images/generations";

        var payload = @"{
            ""model"": ""gpt-image-2-official"",
            ""prompt"": ""An ancient castle beneath a starry sky"",
            ""size"": ""16:9"",
            ""resolution"": ""2k"",
            ""quality"": ""high"",
            ""n"": 1
        }";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

        var content = new StringContent(payload, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(url, content);
        var result = await response.Content.ReadAsStringAsync();

        Console.WriteLine(result);
    }
}
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  final url = Uri.parse('https://api.apimart.ai/v1/images/generations');

  final payload = {
    'model': 'gpt-image-2-official',
    'prompt': 'An ancient castle beneath a starry sky',
    'size': '16:9',
    'resolution': '2k',
    'quality': 'high',
    'n': 1,
  };

  final response = await http.post(
    url,
    headers: {
      'Authorization': 'Bearer <token>',
      'Content-Type': 'application/json',
    },
    body: jsonEncode(payload),
  );

  print(response.body);
}
library(httr)
library(jsonlite)

url <- "https://api.apimart.ai/v1/images/generations"

payload <- list(
  model = "gpt-image-2-official",
  prompt = "An ancient castle beneath a starry sky",
  size = "16:9",
  resolution = "2k",
  quality = "high",
  n = 1
)

response <- POST(
  url,
  add_headers(
    Authorization = "Bearer <token>",
    `Content-Type` = "application/json"
  ),
  body = toJSON(payload, auto_unbox = TRUE),
  encode = "raw"
)

cat(content(response, "text"))
{
  "code": 200,
  "data": [
    {
      "status": "submitted",
      "task_id": "task_01KPTXXXXXXXXXXXXXXX"
    }
  ]
}
{
  "error": {
    "code": 400,
    "message": "Invalid parameters: size not allowed / resolution not supported / pixel violation, etc.",
    "type": "invalid_request_error"
  }
}
{
  "error": {
    "code": 401,
    "message": "Authentication failed, please check your API key",
    "type": "authentication_error"
  }
}
{
  "error": {
    "code": 402,
    "message": "Insufficient account balance, please top up and try again",
    "type": "payment_required"
  }
}
{
  "error": {
    "code": 403,
    "message": "Access forbidden, you do not have permission to access this resource",
    "type": "permission_error"
  }
}
{
  "error": {
    "code": 429,
    "message": "Too many requests, please try again later",
    "type": "rate_limit_error"
  }
}
{
  "error": {
    "code": 500,
    "message": "Internal server error, please try again later",
    "type": "server_error"
  }
}
{
  "error": {
    "code": 502,
    "message": "Bad gateway, the server is temporarily unavailable",
    "type": "bad_gateway"
  }
}
curl --request POST \
  --url https://api.apimart.ai/v1/images/generations \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '{
    "model": "gpt-image-2-official",
    "prompt": "An ancient castle beneath a starry sky",
    "size": "16:9",
    "resolution": "2k",
    "quality": "high",
    "n": 1
  }'
import requests

url = "https://api.apimart.ai/v1/images/generations"

payload = {
    "model": "gpt-image-2-official",
    "prompt": "An ancient castle beneath a starry sky",
    "size": "16:9",
    "resolution": "2k",
    "quality": "high",
    "n": 1
}

headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
const url = "https://api.apimart.ai/v1/images/generations";

const payload = {
  model: "gpt-image-2-official",
  prompt: "An ancient castle beneath a starry sky",
  size: "16:9",
  resolution: "2k",
  quality: "high",
  n: 1,
};

const headers = {
  Authorization: "Bearer <token>",
  "Content-Type": "application/json",
};

fetch(url, {
  method: "POST",
  headers: headers,
  body: JSON.stringify(payload),
})
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    url := "https://api.apimart.ai/v1/images/generations"

    payload := map[string]interface{}{
        "model":      "gpt-image-2-official",
        "prompt":     "An ancient castle beneath a starry sky",
        "size":       "16:9",
        "resolution": "2k",
        "quality":    "high",
        "n":          1,
    }

    jsonData, _ := json.Marshal(payload)

    req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer <token>")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class Main {
    public static void main(String[] args) throws Exception {
        String url = "https://api.apimart.ai/v1/images/generations";

        String payload = """
        {
          "model": "gpt-image-2-official",
          "prompt": "An ancient castle beneath a starry sky",
          "size": "16:9",
          "resolution": "2k",
          "quality": "high",
          "n": 1
        }
        """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Authorization", "Bearer <token>")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();

        HttpResponse<String> response = client.send(request,
            HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
<?php

$url = "https://api.apimart.ai/v1/images/generations";

$payload = [
    "model" => "gpt-image-2-official",
    "prompt" => "An ancient castle beneath a starry sky",
    "size" => "16:9",
    "resolution" => "2k",
    "quality" => "high",
    "n" => 1
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer <token>",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>
require 'net/http'
require 'json'
require 'uri'

url = URI("https://api.apimart.ai/v1/images/generations")

payload = {
  model: "gpt-image-2-official",
  prompt: "An ancient castle beneath a starry sky",
  size: "16:9",
  resolution: "2k",
  quality: "high",
  n: 1
}

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 = payload.to_json

response = http.request(request)
puts response.body
import Foundation

let url = URL(string: "https://api.apimart.ai/v1/images/generations")!

let payload: [String: Any] = [
    "model": "gpt-image-2-official",
    "prompt": "An ancient castle beneath a starry sky",
    "size": "16:9",
    "resolution": "2k",
    "quality": "high",
    "n": 1
]

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer <token>", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONSerialization.data(withJSONObject: payload)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Error: \(error)")
        return
    }

    if let data = data, let responseString = String(data: data, encoding: .utf8) {
        print(responseString)
    }
}

task.resume()
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var url = "https://api.apimart.ai/v1/images/generations";

        var payload = @"{
            ""model"": ""gpt-image-2-official"",
            ""prompt"": ""An ancient castle beneath a starry sky"",
            ""size"": ""16:9"",
            ""resolution"": ""2k"",
            ""quality"": ""high"",
            ""n"": 1
        }";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

        var content = new StringContent(payload, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(url, content);
        var result = await response.Content.ReadAsStringAsync();

        Console.WriteLine(result);
    }
}
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  final url = Uri.parse('https://api.apimart.ai/v1/images/generations');

  final payload = {
    'model': 'gpt-image-2-official',
    'prompt': 'An ancient castle beneath a starry sky',
    'size': '16:9',
    'resolution': '2k',
    'quality': 'high',
    'n': 1,
  };

  final response = await http.post(
    url,
    headers: {
      'Authorization': 'Bearer <token>',
      'Content-Type': 'application/json',
    },
    body: jsonEncode(payload),
  );

  print(response.body);
}
library(httr)
library(jsonlite)

url <- "https://api.apimart.ai/v1/images/generations"

payload <- list(
  model = "gpt-image-2-official",
  prompt = "An ancient castle beneath a starry sky",
  size = "16:9",
  resolution = "2k",
  quality = "high",
  n = 1
)

response <- POST(
  url,
  add_headers(
    Authorization = "Bearer <token>",
    `Content-Type` = "application/json"
  ),
  body = toJSON(payload, auto_unbox = TRUE),
  encode = "raw"
)

cat(content(response, "text"))
{
  "code": 200,
  "data": [
    {
      "status": "submitted",
      "task_id": "task_01KPTXXXXXXXXXXXXXXX"
    }
  ]
}
{
  "error": {
    "code": 400,
    "message": "Invalid parameters: size not allowed / resolution not supported / pixel violation, etc.",
    "type": "invalid_request_error"
  }
}
{
  "error": {
    "code": 401,
    "message": "Authentication failed, please check your API key",
    "type": "authentication_error"
  }
}
{
  "error": {
    "code": 402,
    "message": "Insufficient account balance, please top up and try again",
    "type": "payment_required"
  }
}
{
  "error": {
    "code": 403,
    "message": "Access forbidden, you do not have permission to access this resource",
    "type": "permission_error"
  }
}
{
  "error": {
    "code": 429,
    "message": "Too many requests, please try again later",
    "type": "rate_limit_error"
  }
}
{
  "error": {
    "code": 500,
    "message": "Internal server error, please try again later",
    "type": "server_error"
  }
}
{
  "error": {
    "code": 502,
    "message": "Bad gateway, the server is temporarily unavailable",
    "type": "bad_gateway"
  }
}

Авторизация

Authorization
string
обязательно
Все конечные точки требуют аутентификации Bearer TokenПолучение API-ключа:Перейдите на страницу управления API-ключами, чтобы получить ваш API-ключВключите его в заголовок запроса:
Authorization: Bearer YOUR_API_KEY

Body

model
string
по умолчанию:"gpt-image-2-official"
обязательно
Название модели генерации изображенийФиксируется как gpt-image-2-official (официальная модель OpenAI gpt-image-2)
prompt
string
обязательно
Текстовое описание для генерации изображения
  • Поддерживается английский и китайский, рекомендуются подробные описания
  • Перед отправкой контент проходит модерацию / проверку безопасности — нарушения отклоняются немедленно
size
string
по умолчанию:"1:1"
Соотношение сторон изображенияВнешне используются значения соотношений; внутри они автоматически сопоставляются с реальными пикселями согласно resolution.Поддерживаемые соотношения плюс auto, чтобы сервер автоматически выбрал подходящее соотношение:
  • auto — Автоматически (сервер выбирает соотношение по prompt / эталонным изображениям)
  • 1:1 — Квадрат (по умолчанию, аватары соцсетей / логотипы)
  • 3:2 — Горизонтальное (распространённое соотношение DSLR)
  • 2:3 — Вертикальное (вертикальные постеры)
  • 4:3 — Горизонтальное (классические мониторы / слайд-шоу)
  • 3:4 — Вертикальное
  • 5:4 — Горизонтальное
  • 4:5 — Вертикальное (вертикальная публикация Instagram)
  • 16:9 — Горизонтальное (превью широкоформатных видео)
  • 9:16 — Вертикальное (полный экран телефона / обложка короткого видео)
  • 2:1 — Горизонтальное (веб-баннер)
  • 1:2 — Вертикальное
  • 3:1 — Горизонтальное (сверхширокий баннер)
  • 1:3 — Вертикальное (очень высокий постер)
  • 21:9 — Горизонтальное (кинематографический сверхширокий)
  • 9:21 — Вертикальное
Размеры в пикселях также можно передавать напрямую, например 1881x836 / 887x1774.
Когда size установлено в auto, соотношение по умолчанию — 1:1.
resolution
string
по умолчанию:"1k"
Уровень разрешения (новое поле)Управляет фактической чёткостью вывода.
  • 1k — База 1024, экономичный вариант для повседневного использования (по умолчанию)
  • 2k — База 2048, подходит для постеров / нужд высокой чёткости
  • 4k — База 3840, поддерживает 15 соотношений из таблицы сопоставления ниже
4K поддерживает 15 соотношений из таблицы сопоставления ниже; вы также можете передавать размеры в пикселях из таблицы напрямую через size.
quality
string
по умолчанию:"auto"
Качество изображения
  • auto — Автоматически (по умолчанию, обычно эквивалентно low)
  • low — Быстро и экономично, достаточно для черновых набросков
  • medium — Сбалансированно
  • high — Максимальная точность (4K + high может занимать более 120 с)
background
string
по умолчанию:"auto"
Режим фона
  • auto — Автоматически (по умолчанию)
  • opaque — Непрозрачный
  • transparent — ⚠️ gpt-image-2-official не поддерживает прозрачные фоны; система молча понижает до auto
moderation
string
по умолчанию:"auto"
Строгость модерации
  • auto — Стандартная строгость модерации
  • low — Более мягкая модерация
output_format
string
по умолчанию:"png"
Выходной формат
  • png — По умолчанию
  • jpeg — Меньшие файлы
  • webp — Оптимально для современных браузеров
output_compression
integer
Уровень сжатия вывода, диапазон 0–100
  • Действует только для jpeg / webp
n
integer
по умолчанию:"1"
Количество генерируемых изображенийДиапазон: 1 ~ 4
Должно быть обычным числом (например, 1), не заключайте в кавычки
image_urls
array
Массив URL эталонных изображений
mask_url
string
URL маски, используется для inpainting
  • Должен использоваться вместе с image_urls
  1. Перед загрузкой убедитесь, что у маски есть альфа-канал.
  2. Размер маски должен совпадать с первым эталонным изображением.

Сопоставление Size × Resolution

size × resolution → реальные пиксели OpenAI (15 соотношений × 3 уровня):
size1k2k4k
1:11024×10242048×20482880×2880
3:21536×10242048×13603520×2336
2:31024×15361360×20482336×3520
4:31024×7682048×15363312×2480
3:4768×10241536×20482480×3312
5:41280×10242560×20483216×2576
4:51024×12802048×25602576×3216
16:91536×8642048×11523840×2160
9:16864×15361152×20482160×3840
2:12048×10242688×13443840×1920
1:21024×20481344×26881920×3840
3:11881×836 / 1536×5123072×10243840×1280
1:3887×1774 / 512×15361024×30721280×3840
21:92016×8642688×11523840×1648
9:21864×20161152×26881648×3840
Примечание: Некоторые размеры приближены к кратным 16 и ограничениям по пикселям, например 3:2 / 2:3 @ 2K — это 2048×1360, а 21:9 @ 4K — 3840×1648. В качестве источника истины используйте фактические пиксели из таблицы.

Примеры использования

Text-to-image (минимальный запрос)
{
  "model": "gpt-image-2-official",
  "prompt": "An ancient castle beneath a starry sky"
}
Постер высокой чёткости 2K
{
  "model": "gpt-image-2-official",
  "prompt": "Cyberpunk night scene",
  "size": "16:9",
  "resolution": "2k",
  "quality": "high",
  "output_format": "jpeg",
  "output_compression": 90
}
Обои 4K
{
  "model": "gpt-image-2-official",
  "prompt": "Snow mountain sunrise panorama",
  "size": "16:9",
  "resolution": "4k",
  "quality": "high",
  "n": 1
}
Image-to-image (объединение нескольких эталонов)
{
  "model": "gpt-image-2-official",
  "prompt": "Fuse the two reference images into a single illustration poster, preserving the main silhouettes",
  "size": "1:1",
  "quality": "high",
  "image_urls": [
    "https://your-cdn.com/input-a.png",
    "https://your-cdn.com/input-b.png"
  ]
}
Inpainting (mask)
{
  "model": "gpt-image-2-official",
  "prompt": "Replace the background with a desert sunset",
  "size": "1:1",
  "quality": "medium",
  "image_urls": ["https://your-cdn.com/photo.png"],
  "mask_url": "https://your-cdn.com/mask.png"
}
Несколько изображений (n > 1)
{
  "model": "gpt-image-2-official",
  "prompt": "Four minimalist poster variations of a red fox",
  "size": "1:1",
  "quality": "low",
  "n": 4
}
Прямая строка пикселей (для опытных пользователей)
{
  "model": "gpt-image-2-official",
  "prompt": "wide cinematic shot",
  "size": "3840x2160",
  "quality": "high"
}

Response

code
integer
Код состояния ответа
data
array
Массив данных ответа

Запрос результатов задачи

После успешной отправки возвращается task_id. Опрашивайте статус задачи через GET /v1/tasks/{task_id}, подробнее см. в API запроса задач.

Пример успешного ответа

{
  "code": 200,
  "data": {
    "id": "task_01KPTXXXXXXXXXXXXXXX",
    "status": "completed",
    "progress": 100,
    "actual_time": 46,
    "cost": 0.05279,
    "credits_cost": 0.5279,
    "result": {
      "images": [
        {
          "url": [
            "https://upload.apimart.ai/f/image/xxxxxxxx-gpt_image_2_official_task_xxx_0.png"
          ],
          "expires_at": 1776928569
        }
      ]
    }
  }
}
Поток статусов задачи: submittedin_progresscompleted / failed. Доступ к изображению: data.result.images[0].url[0].