> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apimart.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# GPT-Image(1/1.5) Image Generation

>  - Asynchronous processing mode, returns task ID for subsequent queries
- Supports text-to-image, image-to-image, and inpainting generation modes
- Supports transparent backgrounds, multiple output formats, and quality tiers
- Generate up to 4 images per request, with up to 15 reference images 

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.apimart.ai/v1/images/generations \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "gpt-image-1-official",
      "prompt": "An ancient castle under a starry sky",
      "size": "1:1",
      "quality": "auto",
      "n": 1
    }'
  ```

  ```python Python theme={null}
  import requests

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

  payload = {
      "model": "gpt-image-1-official",
      "prompt": "An ancient castle under a starry sky",
      "size": "1:1",
      "quality": "auto",
      "n": 1
  }

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

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

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const url = "https://api.apimart.ai/v1/images/generations";

  const payload = {
    model: "gpt-image-1-official",
    prompt: "An ancient castle under a starry sky",
    size: "1:1",
    quality: "auto",
    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));
  ```

  ```go Go theme={null}
  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-1-official",
          "prompt":  "An ancient castle under a starry sky",
          "size":    "1:1",
          "quality": "auto",
          "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))
  }
  ```

  ```java Java theme={null}
  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-1-official",
            "prompt": "An ancient castle under a starry sky",
            "size": "1:1",
            "quality": "auto",
            "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 PHP theme={null}
  <?php

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

  $payload = [
      "model" => "gpt-image-1-official",
      "prompt" => "An ancient castle under a starry sky",
      "size" => "1:1",
      "quality" => "auto",
      "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;
  ?>
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'
  require 'uri'

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

  payload = {
    model: "gpt-image-1-official",
    prompt: "An ancient castle under a starry sky",
    size: "1:1",
    quality: "auto",
    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
  ```

  ```swift Swift theme={null}
  import Foundation

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

  let payload: [String: Any] = [
      "model": "gpt-image-1-official",
      "prompt": "An ancient castle under a starry sky",
      "size": "1:1",
      "quality": "auto",
      "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()
  ```

  ```csharp C# theme={null}
  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-1-official"",
              ""prompt"": ""An ancient castle under a starry sky"",
              ""size"": ""1:1"",
              ""quality"": ""auto"",
              ""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);
      }
  }
  ```

  ```dart Dart theme={null}
  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-1-official',
      'prompt': 'An ancient castle under a starry sky',
      'size': '1:1',
      'quality': 'auto',
      'n': 1,
    };

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

    print(response.body);
  }
  ```

  ```r R theme={null}
  library(httr)
  library(jsonlite)

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

  payload <- list(
    model = "gpt-image-1-official",
    prompt = "An ancient castle under a starry sky",
    size = "1:1",
    quality = "auto",
    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"))
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "code": 200,
    "data": [
      {
        "status": "submitted",
        "task_id": "task_01KXXXXXXXXXXXXXXX"
      }
    ]
  }
  ```

  ```json 400 theme={null}
  {
    "error": {
      "code": 400,
      "message": "Invalid request parameters",
      "type": "invalid_request_error"
    }
  }
  ```

  ```json 401 theme={null}
  {
    "error": {
      "code": 401,
      "message": "Authentication failed, please check your API key",
      "type": "authentication_error"
    }
  }
  ```

  ```json 402 theme={null}
  {
    "error": {
      "code": 402,
      "message": "Insufficient balance, please top up and try again",
      "type": "payment_required"
    }
  }
  ```

  ```json 403 theme={null}
  {
    "error": {
      "code": 403,
      "message": "Access forbidden, you do not have permission to access this resource",
      "type": "permission_error"
    }
  }
  ```

  ```json 429 theme={null}
  {
    "error": {
      "code": 429,
      "message": "Too many requests, please try again later",
      "type": "rate_limit_error"
    }
  }
  ```

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "Internal server error, please try again later",
      "type": "server_error"
    }
  }
  ```

  ```json 502 theme={null}
  {
    "error": {
      "code": 502,
      "message": "Bad gateway, server temporarily unavailable",
      "type": "bad_gateway"
    }
  }
  ```
</ResponseExample>

## Supported Models

| Model                    | Description                                                  | Modes                          | Image-to-Image | Max Images | Billing        |
| ------------------------ | ------------------------------------------------------------ | ------------------------------ | -------------- | ---------- | -------------- |
| `gpt-image-1-official`   | Stability-first, suitable for general image generation       | Text-to-Image / Image-to-Image | Supported      | 4          | Size x Quality |
| `gpt-image-1.5-official` | New version, suitable for higher quality and complex editing | Text-to-Image / Image-to-Image | Supported      | 4          | Size x Quality |

## Authorizations

<ParamField header="Authorization" type="string" required>
  All API requests require Bearer Token authentication

  Get your API Key:

  Visit the [API Key management page](https://apimart.ai/keys) to obtain your API Key

  Add the following to your request headers:

  ```
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## Body

<ParamField body="model" type="string" required>
  Model name

  * `gpt-image-1-official` - Stability-first, suitable for general image generation
  * `gpt-image-1.5-official` - New version, suitable for higher quality and complex editing
</ParamField>

<ParamField body="prompt" type="string" required>
  Text description for image generation, supports both Chinese and English
</ParamField>

<ParamField body="size" type="string" default="1:1">
  Aspect ratio

  Supported ratios:

  * `1:1` - Square (default)
  * `3:2` - Landscape
  * `2:3` - Portrait
</ParamField>

<ParamField body="n" type="integer" default="1">
  Number of images to generate

  Range: 1-4

  * Values ≤ 0 will be treated as `1`
  * Values > 4 will be treated as `4`

  **Warning:** Must be a plain number (e.g. `1`), do not add quotes, otherwise it will cause an error
</ParamField>

<ParamField body="quality" type="string" default="auto">
  Image quality

  * `auto` - Auto quality selection (default)
  * `low` - Faster, more economical
  * `medium` - Balance between quality and cost
  * `high` - Higher quality, higher cost
</ParamField>

<ParamField body="background" type="string" default="auto">
  Background mode

  * `auto` - Auto background (default)
  * `opaque` - Opaque background
  * `transparent` - Transparent background, recommended with `png` output format

  <Warning>
    `background: transparent` cannot be used with `output_format: jpeg` simultaneously
  </Warning>
</ParamField>

<ParamField body="moderation" type="string" default="auto">
  Moderation level

  * `auto` - Default moderation level
  * `low` - More lenient moderation
</ParamField>

<ParamField body="output_format" type="string" default="png">
  Output format

  * `png` - Default format, suitable for transparent backgrounds
  * `jpeg` - Smaller file size, suitable for general image output

  <Warning>
    `background: transparent` cannot be used with `output_format: jpeg` simultaneously
  </Warning>
</ParamField>

<ParamField body="output_compression" type="integer">
  Output compression level, range 0-100

  * Recommended only for `jpeg`
  * Not recommended for `png`
</ParamField>

<ParamField body="image_urls" type="array">
  Array of reference image URLs, enables image-to-image mode when provided

  <Expandable title="Details">
    * 1 image for single reference editing
    * 2-15 images for multi-reference fusion editing
    * More than 15 images will be rejected
    * Must be publicly accessible, stable image URLs
  </Expandable>

  **Limit:** Up to 15 reference images
</ParamField>

<ParamField body="mask_url" type="string">
  Mask image URL for inpainting

  * Must be used together with `image_urls`
  * Will be submitted via the official editing API

  <Warning>
    1. Before uploading the mask image, please confirm that the image Alpha channel is "Yes".

    2. The mask image size must match the first reference image.
  </Warning>
</ParamField>

## Size Reference

Aspect ratios are used externally; the system automatically maps them to official dimensions internally.

| Ratio | Actual Size | Description |
| ----- | ----------- | ----------- |
| `1:1` | 1024x1024   | Square      |
| `2:3` | 1024x1536   | Portrait    |
| `3:2` | 1536x1024   | Landscape   |

## Usage Examples

**Text-to-Image (minimal)**

```json theme={null}
{
  "model": "gpt-image-1-official",
  "prompt": "An ancient castle under a starry sky"
}
```

**Text-to-Image (full parameters)**

```json theme={null}
{
  "model": "gpt-image-1-official",
  "prompt": "A flat icon of a glass bottle with no background",
  "size": "2:3",
  "quality": "high",
  "background": "transparent",
  "moderation": "low",
  "output_format": "png",
  "n": 1
}
```

**Image-to-Image (single reference)**

```json theme={null}
{
  "model": "gpt-image-1.5-official",
  "prompt": "Convert the reference image to illustration style, preserving the main outline",
  "size": "1:1",
  "quality": "auto",
  "image_urls": [
    "https://your-cdn.com/input.png"
  ],
  "n": 1
}
```

**Image-to-Image (multi-reference fusion)**

```json theme={null}
{
  "model": "gpt-image-1.5-official",
  "prompt": "Merge two reference images into an illustration poster, preserving the main outlines",
  "size": "1:1",
  "quality": "auto",
  "background": "transparent",
  "image_urls": [
    "https://your-cdn.com/input-a.png",
    "https://your-cdn.com/input-b.png"
  ],
  "moderation": "low",
  "output_format": "png",
  "n": 1
}
```

**Multiple images (n > 1)**

```json theme={null}
{
  "model": "gpt-image-1-official",
  "prompt": "Four minimalist poster variations of a red fox",
  "size": "1:1",
  "quality": "low",
  "output_format": "png",
  "n": 4
}
```

## Response

<ResponseField name="code" type="integer">
  Response status code
</ResponseField>

<ResponseField name="data" type="array">
  Response data array

  <Expandable title="Properties">
    <ResponseField name="status" type="string">
      Task status

      * `submitted` - Submitted
    </ResponseField>

    <ResponseField name="task_id" type="string">
      Unique task identifier
    </ResponseField>
  </Expandable>
</ResponseField>

## Notes

1. **Asynchronous processing**: After submission, a `task_id` is returned. Poll `/v1/tasks/{task_id}` to get results
2. **Model selection**: Use `gpt-image-1-official` for general image generation; use `gpt-image-1.5-official` for high-quality editing and complex image-to-image tasks
3. **Image URL requirements**: For image-to-image, use publicly accessible and stable image URLs
4. **Billing**: Charged per successfully generated image; no charge for failures
