Passer au contenu principal
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"
  }
}

Autorisations

Authorization
string
requis
Tous les points de terminaison nécessitent une authentification Bearer TokenObtenir votre clé API :Rendez-vous sur la page de gestion des clés API pour obtenir votre clé APIIncluez-la dans l’en-tête de la requête :
Authorization: Bearer YOUR_API_KEY

Body

model
string
défaut:"gpt-image-2-official"
requis
Nom du modèle de génération d’imagesFixé à gpt-image-2-official (modèle officiel OpenAI gpt-image-2)
prompt
string
requis
Description textuelle pour la génération d’images
  • Prend en charge l’anglais et le chinois, des descriptions détaillées sont recommandées
  • Modération de contenu / examen de sécurité avant soumission — les violations sont rejetées immédiatement
size
string
défaut:"1:1"
Ratio d’aspect de l’imageÀ l’extérieur, des valeurs de ratio sont utilisées ; en interne, elles sont automatiquement associées aux pixels réels selon resolution.Ratios pris en charge, plus auto pour laisser le serveur choisir automatiquement un ratio adapté :
  • auto — Automatique (le serveur choisit un ratio selon le prompt / les images de référence)
  • 1:1 — Carré (par défaut, avatars sociaux / logos)
  • 3:2 — Paysage (ratio courant de reflex numérique)
  • 2:3 — Portrait (affiches verticales)
  • 4:3 — Paysage (moniteur classique / diaporama)
  • 3:4 — Portrait
  • 5:4 — Paysage
  • 4:5 — Portrait (publication Instagram verticale)
  • 16:9 — Paysage (miniature vidéo grand écran)
  • 9:16 — Portrait (plein écran téléphone / couverture de vidéo courte)
  • 2:1 — Paysage (bannière Web)
  • 1:2 — Portrait
  • 3:1 — Paysage (bannière ultra-large)
  • 1:3 — Portrait (affiche extra-haute)
  • 21:9 — Paysage (ultra-large cinématographique)
  • 9:21 — Portrait
Les dimensions en pixels peuvent également être transmises directement, par exemple 1881x836 / 887x1774.
Lorsque size est défini sur auto, le ratio par défaut est 1:1.
resolution
string
défaut:"1k"
Niveau de résolution (nouveau champ)Contrôle la netteté réelle de la sortie.
  • 1k — Base 1024, économique pour une utilisation quotidienne (par défaut)
  • 2k — Base 2048, adapté aux affiches / besoins en haute définition
  • 4k — Base 3840, prend en charge les 15 ratios du tableau de correspondance ci-dessous
La 4K prend en charge les 15 ratios du tableau de correspondance ci-dessous ; vous pouvez également transmettre les dimensions en pixels du tableau directement via size.
quality
string
défaut:"auto"
Qualité de l’image
  • auto — Automatique (par défaut, généralement équivalent à low)
  • low — Rapide et économique, suffisant pour des contours grossiers
  • medium — Équilibré
  • high — Précision maximale (4K + high peut prendre plus de 120 s)
background
string
défaut:"auto"
Mode d’arrière-plan
  • auto — Automatique (par défaut)
  • opaque — Opaque
  • transparent — ⚠️ gpt-image-2-official ne prend pas en charge les arrière-plans transparents ; le système rétrograde silencieusement vers auto
moderation
string
défaut:"auto"
Force de modération
  • auto — Force de modération par défaut
  • low — Modération plus permissive
output_format
string
défaut:"png"
Format de sortie
  • png — Par défaut
  • jpeg — Fichiers plus petits
  • webp — Optimal pour les navigateurs modernes
output_compression
integer
Niveau de compression de sortie, plage 0-100
  • N’est effectif que pour jpeg / webp
n
integer
défaut:"1"
Nombre d’images à générerPlage : 1 ~ 4
Doit être un nombre brut (par exemple 1), ne pas mettre entre guillemets
image_urls
array
Tableau d’URL d’images de référence
mask_url
string
URL de l’image de masque, utilisée pour l’inpainting
  • Doit être utilisé conjointement avec image_urls
  1. Assurez-vous que l’image de masque possède un canal Alpha avant de la téléverser.
  2. Les dimensions de l’image de masque doivent correspondre à la première image de référence.

Correspondance Size × Resolution

size × resolution → pixels réels OpenAI (15 ratios × 3 niveaux) :
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
Note : Certaines dimensions sont approximées à des multiples de 16 et à des limites de pixels, comme 3:2 / 2:3 @ 2K qui est 2048×1360 et 21:9 @ 4K qui est 3840×1648. Référez-vous aux pixels réels du tableau comme source de vérité.

Exemples d’utilisation

Texte-vers-image (requête minimale)
{
  "model": "gpt-image-2-official",
  "prompt": "An ancient castle beneath a starry sky"
}
Affiche haute définition 2K
{
  "model": "gpt-image-2-official",
  "prompt": "Cyberpunk night scene",
  "size": "16:9",
  "resolution": "2k",
  "quality": "high",
  "output_format": "jpeg",
  "output_compression": 90
}
Fond d’écran 4K
{
  "model": "gpt-image-2-official",
  "prompt": "Snow mountain sunrise panorama",
  "size": "16:9",
  "resolution": "4k",
  "quality": "high",
  "n": 1
}
Image-vers-image (fusion multi-références)
{
  "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 (masque)
{
  "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"
}
Plusieurs images (n > 1)
{
  "model": "gpt-image-2-official",
  "prompt": "Four minimalist poster variations of a red fox",
  "size": "1:1",
  "quality": "low",
  "n": 4
}
Chaîne de pixels directe (avancée)
{
  "model": "gpt-image-2-official",
  "prompt": "wide cinematic shot",
  "size": "3840x2160",
  "quality": "high"
}

Response

code
integer
Code de statut de la réponse
data
array
Tableau de données de réponse

Interrogation des résultats de tâche

Après une soumission réussie, un task_id est renvoyé. Interrogez l’état de la tâche via GET /v1/tasks/{task_id}, voir API d’interrogation des tâches pour plus de détails.

Exemple de réponse en cas de succès

{
  "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
        }
      ]
    }
  }
}
Flux de statuts de la tâche : submittedin_progresscompleted / failed. Accès à l’image : data.result.images[0].url[0].