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

# FLUX Kontext Image Generation and Editing

> Submit asynchronous FLUX Kontext image generation or image editing tasks. The API returns a task ID; poll the task endpoint for the generated image.

<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": "flux-kontext-pro",
      "prompt": "Change the hair color to blue",
      "image_urls": ["https://example.com/portrait.jpg"],
      "size": "1:1",
      "output_format": "png"
    }'
  ```

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

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

  payload = {
      "model": "flux-kontext-pro",
      "prompt": "Change the hair color to blue",
      "image_urls": ["https://example.com/portrait.jpg"],
      "size": "1:1",
      "output_format": "png"
  }

  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: "flux-kontext-pro",
    prompt: "Change the hair color to blue",
    image_urls: ["https://example.com/portrait.jpg"],
    size: "1:1",
    output_format: "png"
  };

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Authorization": "Bearer <token>",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(payload)
  });

  console.log(await response.json());
  ```
</RequestExample>

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

  ```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",
      "type": "payment_required"
    }
  }
  ```
</ResponseExample>

## Supported Models

| Model              | Description                                                               |
| ------------------ | ------------------------------------------------------------------------- |
| `flux-kontext-pro` | Context-aware image generation and editing for general-purpose workflows. |
| `flux-kontext-max` | Higher-quality context-aware image generation and editing.                |

Both models support text-to-image generation without reference images and image editing with reference images.

## Authorizations

<ParamField header="Authorization" type="string" required>
  All endpoints require Bearer Token authentication.

  Get an API key from [API Key Management](https://apimart.ai/keys), then add it to the request header:

  ```text theme={null}
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## Body

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

  * `flux-kontext-pro`
  * `flux-kontext-max`
</ParamField>

<ParamField body="prompt" type="string" required>
  Text description of the image to generate or the edit to apply to the reference images.
</ParamField>

<ParamField body="image_urls" type="array">
  Reference images for image editing. Publicly accessible image URLs and Base64 input are supported.

  * Maximum: 4 images
  * The output plus all reference images must not exceed 9 MP in total

  If a reference URL cannot be accessed publicly, the task may return only `temporarily unavailable dependency`. When this happens, first check hotlink protection, access permissions, and expired signatures.
</ParamField>

<ParamField body="size" type="string" default="1:1">
  Output aspect ratio. A pixel string such as `1024x1536` is also accepted, but Kontext maps it to the closest supported ratio rather than producing those exact pixel dimensions. Supported ratios:

  * `1:1` (default)
  * `4:3`
  * `3:4`
  * `16:9`
  * `9:16`
  * `3:2`
  * `2:3`
  * `21:9`
  * `9:21`
</ParamField>

Kontext does not support `width` or `height`; supplying either field causes the task to fail. Use `size` to control the aspect ratio. `resolution` has no effect for Kontext, whose output remains approximately 1 MP.

<ParamField body="output_format" type="string" default="png">
  Output image encoding. Supported values: `png`, `jpeg`, and `webp`.
</ParamField>

<ParamField body="response_format" type="string">
  OpenAI-compatible response-shape field. It accepts only `url` or `b64_json` and does not change the image encoding. When both fields are supplied, `output_format` takes priority.
</ParamField>

<ParamField body="n" type="integer" default="1">
  Number of images generated per task. The only supported value is `1`; submit multiple tasks concurrently if you need multiple images.
</ParamField>

<ParamField body="seed" type="integer">
  Random seed. Reuse the same seed and parameters for reproducible output; omit it to use a random seed.
</ParamField>

<ParamField body="prompt_upsampling" type="boolean" default="false">
  Whether to enhance and rewrite the prompt before generation.

  Set this parameter explicitly to `false` to disable prompt rewriting.
</ParamField>

<ParamField body="safety_tolerance" type="integer" default="2">
  Safety tolerance from `0` to `6`. Higher values are more permissive.
</ParamField>

## Supported Aspect Ratios

| Aspect ratio | Orientation          |
| ------------ | -------------------- |
| `1:1`        | Square (default)     |
| `4:3`        | Landscape            |
| `3:4`        | Portrait             |
| `16:9`       | Widescreen landscape |
| `9:16`       | Vertical portrait    |
| `3:2`        | Classic landscape    |
| `2:3`        | Classic portrait     |
| `21:9`       | Ultra-wide landscape |
| `9:21`       | Ultra-tall portrait  |

### Actual Output Dimensions

| Ratio  | Actual output dimensions |
| ------ | ------------------------ |
| `1:1`  | 1024×1024                |
| `4:3`  | 1184×880                 |
| `3:4`  | 880×1184                 |
| `16:9` | 1392×752                 |
| `9:16` | 752×1392                 |
| `3:2`  | 1248×832                 |
| `2:3`  | 832×1248                 |
| `21:9` | 1568×672                 |
| `9:21` | 672×1568                 |

## Usage Examples

### Text-to-image generation

```json theme={null}
{
  "model": "flux-kontext-pro",
  "prompt": "A cozy reading nook with warm lamplight",
  "size": "4:3"
}
```

### Image editing

```json theme={null}
{
  "model": "flux-kontext-max",
  "prompt": "Replace the background with a beach while preserving the person",
  "image_urls": ["https://example.com/portrait.jpg"],
  "size": "16:9",
  "output_format": "webp"
}
```

### Multiple reference images

```json theme={null}
{
  "model": "flux-kontext-pro",
  "prompt": "Place the product from the first image into the room from the second image",
  "image_urls": [
    "https://example.com/product.jpg",
    "https://example.com/room.jpg"
  ],
  "size": "4:3"
}
```

## Response

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

<ResponseField name="data" type="array">
  Submission result array.

  <Expandable title="Properties">
    <ResponseField name="status" type="string">
      Submission status. A successfully accepted task returns `submitted`.
    </ResponseField>

    <ResponseField name="task_id" type="string">
      Unique task identifier. Use it to poll the task endpoint.
    </ResponseField>
  </Expandable>
</ResponseField>

## Retrieve the Result

Poll `GET /v1/tasks/{task_id}` until the task reaches `completed` or `failed`. See the [Task Status API](/en/api-reference/tasks/status) for the complete response schema.

Task statuses:

| Status                  | Meaning                                                                   |
| ----------------------- | ------------------------------------------------------------------------- |
| `submitted` / `pending` | Accepted or queued; continue polling.                                     |
| `processing`            | Image generation is in progress; continue polling.                        |
| `completed`             | Generation succeeded; the image is available in `result.images`.          |
| `failed`                | Generation failed; read `data.error.message`. The task is fully refunded. |

A completed task includes one generated image:

```json theme={null}
{
  "code": 200,
  "data": {
    "id": "task_01KFG5BBFNK1YQDTJDZY0P0QT2",
    "status": "completed",
    "progress": 100,
    "result": {
      "images": [
        {
          "url": ["https://upload.apimart.ai/f/image/xxxxxxxx-flux-kontext.png"],
          "expires_at": 1785220083
        }
      ]
    }
  }
}
```

The image URL is `data.result.images[0].url[0]`. Its expiration is defined by the Unix timestamp in `data.result.images[0].expires_at`; download the image before that time.

### Invalid parameters and failed tasks

Invalid model parameters do not produce a synchronous 4xx response. The submission still returns HTTP 200 with a `task_id`; keep polling until the task becomes `failed`, then read the specific reason from `data.error.message`. Failed tasks are fully refunded.

```json theme={null}
{
  "code": 200,
  "data": {
    "status": "failed",
    "error": {
      "type": "task_failed",
      "code": "task_failed",
      "message": "width/height are not supported by flux-kontext-pro"
    }
  }
}
```

`error.code` is always `task_failed`; the specific reason is in `error.message`.

## Notes

1. Tasks are processed asynchronously. The submission response returns a `task_id` for polling.
2. `n` defaults to `1`, which is the only supported value.
3. Reference images may use publicly accessible image URLs or Base64 input.
4. Up to 4 reference images are supported, subject to the 9 MP combined input-and-output limit.
5. Set `prompt_upsampling: false` explicitly to disable prompt rewriting.
6. Result URL expiration is determined by the `expires_at` value returned in the task response.
7. `width` and `height` cause the task to fail; `resolution` does not change the approximately 1 MP output; a pixel-string `size` maps to the closest supported ratio.
8. Invalid model parameters are returned asynchronously: poll until `failed` and read `data.error.message`.
