> ## 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.

# Generación de Video MiniMax-H3

>  - Modo de procesamiento asíncrono, devuelve un ID de tarea para consultas posteriores
- Soporta text-to-video, image-to-video (primer / último / primer+último fotograma) y referencia multimodal a video (imágenes de referencia + videos + audio)
- Salida nativa 2K, duración de 4 ~ 15 segundos, con pista de audio
- Comparte las mismas APIs de envío y consulta que MiniMax-Hailuo-02 / MiniMax-Hailuo-2.3 

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.apimart.ai/v1/videos/generations \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --data '{
      "model": "MiniMax-H3",
      "prompt": "A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work",
      "duration": 5,
      "resolution": "2K",
      "aspect_ratio": "16:9"
    }'
  ```

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

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

  payload = {
      "model": "MiniMax-H3",
      "prompt": "A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work",
      "duration": 5,
      "resolution": "2K",
      "aspect_ratio": "16:9"
  }

  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/videos/generations";

  const payload = {
    model: "MiniMax-H3",
    prompt: "A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work",
    duration: 5,
    resolution: "2K",
    aspect_ratio: "16:9"
  };

  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/videos/generations"

      payload := map[string]interface{}{
          "model":        "MiniMax-H3",
          "prompt":       "A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work",
          "duration":     5,
          "resolution":   "2K",
          "aspect_ratio": "16:9",
      }

      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/videos/generations";

          String payload = """
          {
            "model": "MiniMax-H3",
            "prompt": "A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work",
            "duration": 5,
            "resolution": "2K",
            "aspect_ratio": "16:9"
          }
          """;

          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/videos/generations";

  $payload = [
      "model" => "MiniMax-H3",
      "prompt" => "A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work",
      "duration" => 5,
      "resolution" => "2K",
      "aspect_ratio" => "16:9"
  ];

  $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/videos/generations")

  payload = {
    model: "MiniMax-H3",
    prompt: "A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work",
    duration: 5,
    resolution: "2K",
    aspect_ratio: "16:9"
  }

  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/videos/generations")!

  let payload: [String: Any] = [
      "model": "MiniMax-H3",
      "prompt": "A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work",
      "duration": 5,
      "resolution": "2K",
      "aspect_ratio": "16:9"
  ]

  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/videos/generations";

          var payload = @"{
              ""model"": ""MiniMax-H3"",
              ""prompt"": ""A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work"",
              ""duration"": 5,
              ""resolution"": ""2K"",
              ""aspect_ratio"": ""16:9""
          }";

          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);
      }
  }
  ```
</RequestExample>

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

  ```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 account balance, please top up and try again",
      "type": "payment_required"
    }
  }
  ```

  ```json 422 theme={null}
  {
    "error": {
      "code": 422,
      "message": "Content safety review failed",
      "type": "invalid_request_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 retry later",
      "type": "server_error"
    }
  }
  ```
</ResponseExample>

## Autorización

<ParamField header="Authorization" type="string" required>
  Todos los endpoints de la API requieren autenticación mediante Bearer Token

  Obtenga su API Key:

  Visite la [página de gestión de API Keys](https://apimart.ai/keys) para obtener su API Key

  Añádala al encabezado de la solicitud:

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

## Modos de generación

MiniMax-H3 enruta automáticamente al modo correspondiente según los campos de la solicitud. **No necesita el campo `mode`**:

| Modo                            | Activador                                                                                       | Capacidad                                                              |
| ------------------------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| **Text-to-Video (T2V)**         | Solo `prompt` y campos generales                                                                | Generación impulsada únicamente por texto                              |
| **Image-to-Video (I2V)**        | `first_frame_image` / `last_frame_image` (o `first_frame` / `last_frame` en `image_with_roles`) | Control de primer fotograma, último fotograma, primer+último fotograma |
| **Referencia multimodal (R2V)** | `image_urls` / `video_urls` / `audio_urls`, o `reference_image` en `image_with_roles`           | Imágenes de referencia + videos + audio                                |

<Warning>
  **Exclusión mutua estricta**: los campos de image-to-video (`first_frame_image` / `last_frame_image`, y `first_frame` / `last_frame` en `image_with_roles`) no pueden combinarse con los campos de referencia multimodal (`image_urls`, `video_urls`, `audio_urls`, y `reference_image` en `image_with_roles`). Mezclarlos devuelve **400**.
</Warning>

<Warning>
  **El audio por sí solo no está permitido.** Si envía `audio_urls`, también debe proporcionar al menos una imagen de referencia o un video de referencia.
</Warning>

## Parámetros de la solicitud

### Campos generales

<ParamField body="model" type="string" required>
  Valor fijo: `MiniMax-H3`

  <Warning>
    **`model` es obligatorio y debe enviarse de forma explícita.** Los clientes ya integrados con Hailuo pueden cambiar configurando `model` a `MiniMax-H3`.
  </Warning>
</ParamField>

<ParamField body="prompt" type="string" required>
  Descripción del contenido del video. **Obligatorio y no vacío en todos los escenarios**, máximo **7000** caracteres por solicitud.

  Describa la escena, el sujeto, el movimiento y el estilo con detalle para obtener mejores resultados.

  Ejemplo: `"A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work"`
</ParamField>

<ParamField body="duration" type="integer" default="5">
  Duración de salida (segundos)

  * Rango: entero de `4` a `15`
  * Por defecto: `5`
</ParamField>

<ParamField body="resolution" type="string" default="2K">
  Resolución del video

  * Valor soportado: solo `2K` (por defecto)
</ParamField>

<ParamField body="aspect_ratio" type="string">
  Proporción de aspecto. También puede enviar `size` o `ratio` con el mismo efecto.

  Proporciones permitidas: `21:9`, `16:9`, `4:3`, `1:1`, `3:4`, `9:16`

  El comportamiento por escenario se describe en “Reglas de proporción de aspecto” más abajo.
</ParamField>

<ParamField body="watermark" type="boolean" default="false">
  Si se debe añadir una marca de agua AIGC

  Por defecto: `false`

  Alias compatible: `aigc_watermark`
</ParamField>

<ParamField body="webhook" type="string">
  URL que recibe un push cuando la tarea alcanza un estado terminal (éxito / fallo)

  <Note>
    Use `webhook`. No envíe el `callback_url` oficial. `callback_url` está reservado para uso interno y no se acepta de los usuarios.
  </Note>
</ParamField>

### Campos de image-to-video

Para image-to-video de **primer / último fotograma**, especifique los roles de forma explícita. No infiera a partir del recuento de `image_urls`.

<ParamField body="first_frame_image" type="string">
  URL de la imagen del primer fotograma

  Cuando se proporciona, esta imagen se utiliza como el **fotograma inicial** del video.
</ParamField>

<ParamField body="last_frame_image" type="string">
  URL de la imagen del último fotograma

  Cuando se proporciona, esta imagen se utiliza como el **fotograma final**. Combínela con `first_frame_image` para el control de primer+último fotograma.
</ParamField>

### Campos de referencia multimodal

<ParamField body="image_urls" type="string[]">
  Array de URLs de imágenes de referencia

  <Warning>
    **Cada imagen en `image_urls` se trata como una imagen de referencia (`reference_image`)**, independientemente del recuento. Nunca se mapean automáticamente a primer / primer+último fotograma según la longitud.
  </Warning>

  * Cantidad: ≤ **9**
</ParamField>

<ParamField body="video_urls" type="string[]">
  Array de URLs de videos de referencia

  * Cantidad: ≤ **3**
  * Formato y límites: consulte “Límites de medios de entrada” más abajo
</ParamField>

<ParamField body="audio_urls" type="string[]">
  Array de URLs de audio de referencia

  * Cantidad: ≤ **3**
  * No puede usarse solo; debe emparejarse con una imagen de referencia o un video de referencia
</ParamField>

### Array de imágenes compartido (formulario opcional)

<ParamField body="image_with_roles" type="object[]">
  Array de imágenes con rol etiquetado. Puede reemplazar `first_frame_image` / `last_frame_image` / `image_urls`. Cada elemento:

  <Expandable title="elemento image_with_roles">
    <ResponseField name="url" type="string" required>
      URL de la imagen
    </ResponseField>

    <ResponseField name="role" type="string" required>
      Rol de la imagen. Valores permitidos:

      * `first_frame` (también acepta `first`) — primer fotograma (I2V)
      * `last_frame` (también acepta `last`) — último fotograma (I2V)
      * `reference_image` (también acepta `reference`) — imagen de referencia (R2V)
    </ResponseField>
  </Expandable>

  Ejemplo (primer + último fotograma):

  ```json theme={null}
  {
    "image_with_roles": [
      {"url": "https://example.com/start.png", "role": "first_frame"},
      {"url": "https://example.com/end.png", "role": "last_frame"}
    ]
  }
  ```

  Ejemplo (imagen de referencia):

  ```json theme={null}
  {
    "image_with_roles": [
      {"url": "https://example.com/char.png", "role": "reference_image"}
    ]
  }
  ```
</ParamField>

## Reglas de proporción de aspecto

| Escenario                                      | Comportamiento de `aspect_ratio`                                                     |
| ---------------------------------------------- | ------------------------------------------------------------------------------------ |
| **Text-to-video** (solo prompt)                | Debe ser una proporción concreta; omitir o `adaptive` **usa `16:9` por defecto**     |
| **Image-to-video** (primer / último fotograma) | Determinado por la imagen de entrada; cualquier valor se ignora (siempre `adaptive`) |
| **Referencia multimodal**                      | Opcional, por defecto `adaptive`; también puede establecer una proporción explícita  |

Proporciones concretas permitidas: `21:9`, `16:9`, `4:3`, `1:1`, `3:4`, `9:16`.

## Límites de medios de entrada

Tamaño total del cuerpo de la solicitud ≤ **64 MB**. Use URLs públicas para archivos grandes; **no use Base64**.

### Imágenes

| Elemento                    | Límite                                                                 |
| --------------------------- | ---------------------------------------------------------------------- |
| Formato                     | JPG / JPEG / PNG / WEBP / HEIC / HEIF                                  |
| Por archivo                 | ≤ 30 MB                                                                |
| Ancho / alto                | 256 \~ 5760 px                                                         |
| Proporción de aspecto (a/h) | 0.4 \~ 2.5                                                             |
| Cantidad                    | Primer fotograma ≤ 1, último fotograma ≤ 1, imágenes de referencia ≤ 9 |

### Video (solo referencia multimodal)

| Elemento                  | Límite                                        |
| ------------------------- | --------------------------------------------- |
| Formato                   | MP4 (`.mp4`), MOV (`.mov`)                    |
| Códec                     | Video H.264/AVC, H.265/HEVC; audio AAC, MP3   |
| Por archivo               | ≤ 50 MB                                       |
| Cantidad                  | ≤ 3                                           |
| Duración                  | Por clip 2 \~ 15 s; **duración total ≤ 15 s** |
| Tamaño / proporción / FPS | 256 \~ 5760 px / 0.4 \~ 2.5 / 23.976 \~ 60    |

### Audio (solo referencia multimodal)

| Elemento    | Límite                                    |
| ----------- | ----------------------------------------- |
| Formato     | WAV, MP3                                  |
| Por archivo | ≤ 15 MB                                   |
| Cantidad    | ≤ 3                                       |
| Duración    | Por clip 2 \~ 15 s; duración total ≤ 15 s |

## Restricciones de parámetros

Las infracciones se rechazan con **400** (el contenido sensible puede devolver **422**) y **no se facturan**:

| Parámetro                                        | Restricción                                                                             |
| ------------------------------------------------ | --------------------------------------------------------------------------------------- |
| `prompt`                                         | Obligatorio y no vacío en todos los escenarios, ≤ 7000 caracteres                       |
| `duration`                                       | Solo enteros de `4` a `15`                                                              |
| `resolution`                                     | Solo `2K`                                                                               |
| `aspect_ratio`                                   | Consulte “Reglas de proporción de aspecto”; T2V usa `16:9` por defecto si se omite      |
| Primer/último fotograma vs activos de referencia | **Mutuamente excluyentes**, no se pueden mezclar                                        |
| `audio_urls`                                     | No puede usarse solo; debe emparejarse con imagen o video de referencia                 |
| Imágenes de referencia                           | ≤ 9                                                                                     |
| Videos de referencia                             | ≤ 3                                                                                     |
| Audio de referencia                              | ≤ 3                                                                                     |
| Fallo de probe del video de referencia           | Devuelve `input_video_probe_failed` (URL inaccesible o archivo corrupto), **sin cargo** |

## Respuesta

<ResponseField name="code" type="integer">
  Código de estado de la respuesta, 200 en caso de éxito
</ResponseField>

<ResponseField name="data" type="array">
  Array de datos de la respuesta

  <Expandable title="Elementos del array">
    <ResponseField name="status" type="string">
      Estado de la tarea; `submitted` al enviarse inicialmente
    </ResponseField>

    <ResponseField name="task_id" type="string">
      ID único de la tarea para consultar el estado y los resultados
    </ResponseField>
  </Expandable>
</ResponseField>

## Ejemplos de solicitud

### Caso 1: Text-to-Video

```json theme={null}
{
  "model": "MiniMax-H3",
  "prompt": "A boy playing basketball by the sea at dusk, waves crashing, cinematic camera work",
  "duration": 6,
  "resolution": "2K",
  "aspect_ratio": "16:9"
}
```

### Caso 2: Image-to-Video — Primer fotograma

```json theme={null}
{
  "model": "MiniMax-H3",
  "prompt": "Pull focus to the people in the background and add more steam to the ramen bowl.",
  "first_frame_image": "https://cdn.example.com/ramen.png",
  "duration": 5,
  "resolution": "2K"
}
```

### Caso 3: Image-to-Video — Primer + último fotograma

```json theme={null}
{
  "model": "MiniMax-H3",
  "prompt": "Camera slowly transitions from morning light to sunset",
  "first_frame_image": "https://cdn.example.com/morning.png",
  "last_frame_image": "https://cdn.example.com/sunset.png",
  "duration": 8
}
```

### Caso 4: Referencia multimodal a video

```json theme={null}
{
  "model": "MiniMax-H3",
  "prompt": "Character speaks: Follow the wind, live free. Leave worries behind, enjoy the moment. Voice references audio 1",
  "image_with_roles": [
    {"url": "https://cdn.example.com/char.png", "role": "reference_image"}
  ],
  "video_urls": ["https://cdn.example.com/ref_motion.mp4"],
  "audio_urls": ["https://cdn.example.com/ref_voice.mp3"],
  "duration": 5,
  "resolution": "2K"
}
```

### Caso 5: Primer + último fotograma mediante image\_with\_roles

```json theme={null}
{
  "model": "MiniMax-H3",
  "prompt": "Camera slowly transitions from morning light to sunset",
  "image_with_roles": [
    {"url": "https://cdn.example.com/morning.png", "role": "first_frame"},
    {"url": "https://cdn.example.com/sunset.png", "role": "last_frame"}
  ],
  "duration": 8
}
```

<Note>
  **Consultar resultados de la tarea**

  La generación de video es asíncrona y devuelve un `task_id` al enviarse. Use el endpoint [Obtener estado de la tarea](/es/api-reference/tasks/status) para consultar el progreso y los resultados.

  Intervalo de sondeo recomendado: cada **5 \~ 10 segundos**. Tiempo de espera del cliente: **15 minutos**. En caso de éxito, `result.videos[0].url` es la URL mp4. Las URLs de video caducan en aproximadamente **24 horas** — guárdelas a tiempo. Las tareas fallidas se reembolsan automáticamente.
</Note>
