Saltar al contenido principal
POST
/
v1
/
images
/
generations
# El campo model puede ser "gpt-image-2" o el alias compatible "gpt-image-2-ext"
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",
    "prompt": "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
    "n": 1,
    "size": "16:9",
    "resolution": "2k"
  }'
import requests

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

payload = {
    "model": "gpt-image-2",
    "prompt": "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
    "n": 1,
    "size": "16:9",
    "resolution": "2k"
}

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",
  prompt: "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
  n: 1,
  size: "16:9",
  resolution: "2k"
};

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",
        "prompt":     "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
        "n":          1,
        "size":       "16:9",
        "resolution": "2k",
    }

    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",
          "prompt": "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
          "n": 1,
          "size": "16:9",
          "resolution": "2k"
        }
        """;

        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",
    "prompt" => "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
    "n" => 1,
    "size" => "16:9",
    "resolution" => "2k"
];

$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",
  prompt: "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
  n: 1,
  size: "16:9",
  resolution: "2k"
}

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",
    "prompt": "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
    "n": 1,
    "size": "16:9",
    "resolution": "2k"
]

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"",
            ""prompt"": ""A ginger cat sitting on a windowsill watching the sunset, watercolor style"",
            ""n"": 1,
            ""size"": ""16:9"",
            ""resolution"": ""2k""
        }";

        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',
    'prompt': 'A ginger cat sitting on a windowsill watching the sunset, watercolor style',
    'n': 1,
    'size': '16:9',
    'resolution': '2k'
  };

  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",
  prompt = "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
  n = 1,
  size = "16:9",
  resolution = "2k"
)

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_01KPQ7J7DWB7QZ3WCEK3YVPBRA"
    }
  ]
}
{
  "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": 429,
    "message": "Too many requests, please try again later",
    "type": "rate_limit_error"
  }
}
{
  "error": {
    "code": 500,
    "message": "build_request_failed: invalid size: 3:5, allowed: 1:1 / 16:9 / 9:16 / 4:3 / 3:4 / 3:2 / 2:3 / 5:4 / 4:5 / 2:1 / 1:2 / 3:1 / 1:3 / 21:9 / 9:21",
    "type": "server_error"
  }
}
{
  "error": {
    "code": 503,
    "message": "Upstream temporarily unavailable, please try again later",
    "type": "service_unavailable"
  }
}
Aviso de compatibilidad de nombres de modelo: Esta interfaz también admite el alias gpt-image-2-ext, equivalente a gpt-image-2; ambos son intercambiables y producen los mismos resultados.
# El campo model puede ser "gpt-image-2" o el alias compatible "gpt-image-2-ext"
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",
    "prompt": "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
    "n": 1,
    "size": "16:9",
    "resolution": "2k"
  }'
import requests

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

payload = {
    "model": "gpt-image-2",
    "prompt": "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
    "n": 1,
    "size": "16:9",
    "resolution": "2k"
}

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",
  prompt: "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
  n: 1,
  size: "16:9",
  resolution: "2k"
};

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",
        "prompt":     "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
        "n":          1,
        "size":       "16:9",
        "resolution": "2k",
    }

    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",
          "prompt": "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
          "n": 1,
          "size": "16:9",
          "resolution": "2k"
        }
        """;

        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",
    "prompt" => "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
    "n" => 1,
    "size" => "16:9",
    "resolution" => "2k"
];

$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",
  prompt: "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
  n: 1,
  size: "16:9",
  resolution: "2k"
}

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",
    "prompt": "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
    "n": 1,
    "size": "16:9",
    "resolution": "2k"
]

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"",
            ""prompt"": ""A ginger cat sitting on a windowsill watching the sunset, watercolor style"",
            ""n"": 1,
            ""size"": ""16:9"",
            ""resolution"": ""2k""
        }";

        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',
    'prompt': 'A ginger cat sitting on a windowsill watching the sunset, watercolor style',
    'n': 1,
    'size': '16:9',
    'resolution': '2k'
  };

  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",
  prompt = "A ginger cat sitting on a windowsill watching the sunset, watercolor style",
  n = 1,
  size = "16:9",
  resolution = "2k"
)

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_01KPQ7J7DWB7QZ3WCEK3YVPBRA"
    }
  ]
}
{
  "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": 429,
    "message": "Too many requests, please try again later",
    "type": "rate_limit_error"
  }
}
{
  "error": {
    "code": 500,
    "message": "build_request_failed: invalid size: 3:5, allowed: 1:1 / 16:9 / 9:16 / 4:3 / 3:4 / 3:2 / 2:3 / 5:4 / 4:5 / 2:1 / 1:2 / 3:1 / 1:3 / 21:9 / 9:21",
    "type": "server_error"
  }
}
{
  "error": {
    "code": 503,
    "message": "Upstream temporarily unavailable, please try again later",
    "type": "service_unavailable"
  }
}

Autorizaciones

Authorization
string
requerido
Todos los endpoints requieren autenticación con Bearer TokenObtenga su API Key:Visite la página de gestión de API Keys para obtener su API KeyInclúyala en el encabezado de la solicitud:
Authorization: Bearer YOUR_API_KEY

Body

model
string
predeterminado:"gpt-image-2"
requerido
Nombre del modelo de generación de imágenesFijo en gpt-image-2 (alias compatible gpt-image-2-ext)
Para mantener la compatibilidad con llamadas anteriores, el alias gpt-image-2-ext (corresponde a gpt-image-2) sigue estando disponible.
prompt
string
requerido
Descripción textual para la generación de la imagen
  • Admite inglés y chino, se recomiendan descripciones detalladas
  • Moderación de contenido / revisión de seguridad antes del envío — las violaciones se rechazan inmediatamente
n
integer
predeterminado:"1"
Número de imágenes a generarRango: 1 - 10
Debe ser un número puro (p. ej., 1), no lo envuelva en comillas
size
string
predeterminado:"1:1"
Proporción de la imagenProporciones admitidas, más auto para dejar que el servidor elija una proporción adecuada automáticamente:
sizeTipo
autoAutomático
1:1Cuadrada
3:2Horizontal
2:3Vertical
4:3Horizontal
3:4Vertical
5:4Horizontal
4:5Vertical
16:9Horizontal
9:16Vertical
2:1Horizontal
1:2Vertical
3:1Horizontal
1:3Vertical
21:9Horizontal
9:21Vertical
También pueden pasarse dimensiones en píxeles directamente, como 1881x836 / 887x1774.
Cuando size se establece en auto, la proporción predeterminada es 1:1.
resolution
string
predeterminado:"1k"
Nivel de resolución de salidaOpciones: 1k / 2k / 4kMapeo size × resolution → píxeles reales:
size1k2k4k
1:11024×1024 / 1254×12542048×20482880×2880
3:21536×10242048×13603520×2336
2:31024×15361360×20482336×3520
4:31024×7682048×15363312×2480
3:4768×10241536×20482480×3312
5:41280×1024 / 1448×10862560×20483216×2576
4:51024×1280 / 1122×14022048×25602576×3216
16:91536×864 / 1672×9412048×11523840×2160
9:16864×1536 / 941×16721152×20482160×3840
2:12048×1024 / 1774×8872688×13443840×1920
1:21024×2048 / 887×17741344×26881920×3840
3:11881×836 / 1536×5123072×10243840×1280
1:3887×1774 / 512×15361024×30721280×3840
21:92016×864 / 1915×8212688×11523840×1648
9:21864×2016 / 821×19151152×26881648×3840
El 4K admite las 15 proporciones listadas arriba; también puede pasar las dimensiones en píxeles de la tabla directamente mediante size.
image_urls
array
Array de imágenes de referencia (campo estándar de OpenAI). Cambia al modo imagen a imagen cuando se proporciona.
Otros campos estándar de OpenAI (response_format, style) no son compatibles y serán ignorados. Los resultados de las tareas solo devuelven url — descargue y convierta a base64 usted mismo si lo necesita.
official_fallback
boolean
predeterminado:"false"
Si recurrir al canal oficial como fallback
  • false: No usar (predeterminado)
  • true: Usar el canal oficial

Ejemplos de uso

Texto a imagen (solicitud mínima)
{
  "model": "gpt-image-2",
  "prompt": "A ginger cat sitting on a windowsill watching the sunset, watercolor style"
}
Texto a imagen (con proporción + 2K)
{
  "model": "gpt-image-2",
  "prompt": "a corgi astronaut on the moon, cinematic, 8k",
  "size": "16:9",
  "resolution": "2k"
}
Texto a imagen (salida en 4K)
{
  "model": "gpt-image-2",
  "prompt": "An ancient castle under a starry sky",
  "size": "16:9",
  "resolution": "4k"
}
Texto a imagen (múltiples)
{
  "model": "gpt-image-2",
  "prompt": "An ancient castle under a starry sky",
  "size": "16:9",
  "resolution": "4k",
  "n": 2
}
Imagen a imagen (referencia = URL)
{
  "model": "gpt-image-2",
  "prompt": "Turn this photo into a watercolor painting",
  "image_urls": [
    "https://example.com/photo.jpg"
  ]
}
Imagen a imagen (referencia = base64)
{
  "model": "gpt-image-2",
  "prompt": "Turn this photo into a watercolor painting",
  "image_urls": [
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
  ]
}
Imagen a imagen (fusión multireferencia, URL + base64 combinados)
{
  "model": "gpt-image-2",
  "prompt": "Fuse these two photos into a single poster",
  "size": "4:3",
  "resolution": "2k",
  "image_urls": [
    "https://example.com/photo-a.jpg",
    "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
  ]
}

Response

code
integer
Código de estado de la respuesta
data
array
Array de datos de la respuesta

Consulta de resultados de la tarea

Tras un envío correcto, se devuelve un task_id. Consulte el estado de la tarea mediante GET /v1/tasks/{task_id}, consulte la API de consulta de tareas para más detalles.

Ejemplo de respuesta exitosa

{
  "code": 200,
  "data": {
    "id": "task_01KPQ7J7DWB7QZ3WCEK3YVPBRA",
    "status": "completed",
    "progress": 100,
    "created": 1776748674,
    "completed": 1776748726,
    "actual_time": 52,
    "cost": 0.05279,
    "credits_cost": 0.5279,
    "estimated_time": 100,
    "result": {
      "images": [
        {
          "url": [
            "https://upload.apimart.ai/f/image/xxxxxxxx-gpt_image_2_task_xxx_0.png"
          ],
          "expires_at": 1776835126
        }
      ]
    }
  }
}
Acceso a la imagen: data.result.images[0].url[0]

Estado de la tarea

EstadoSignificado
submittedEnviada
processingProcesándose en el upstream
completedÉxito, result.images disponible
failedFalló, compruebe error.message