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

# Image generation

> Generate images and validate model-specific parameters and output formats.

Use `POST https://api.apione.ai/v1/images/generations` to create images.

![APIONE web image generation page](https://mintcdn.com/apione/pAFvFGkbmcRZirTZ/images/ui/image-generation.png?fit=max\&auto=format\&n=pAFvFGkbmcRZirTZ\&q=85\&s=30f889fdfea0613466caf9910f0b1090)

APIONE web image generation provides templates, prompts, model, aspect ratio, resolution, and output format options.

![APIONE model marketplace image model list](https://mintcdn.com/apione/Vq80XJbufibzxH8S/images/ui/image-models.png?fit=max\&auto=format\&n=Vq80XJbufibzxH8S\&q=85\&s=eae9bd2f7dca4ec988e562d03c1e78aa)

The image category in the model marketplace lets you compare image models, per-image price, input/output types, and available channels.

## Before running examples

Install Python 3, then install the dependency with the same interpreter that will run the example:

```bash theme={null}
python -m pip install requests
```

If your system uses `python3`, use `python3` for both installation and execution. Windows users can use `py -m pip install requests` and `py example.py`. Activate your virtual environment first, if applicable.

Create a key on the [API Keys page](https://apione.ai/en/app/api-keys), copy a model ID that supports image generation from the [available model list](https://apione.ai/docs/en/models/catalog.md), then set the variables in the terminal where you will run the script. The uppercase values below are placeholders to replace.

> [tab] macOS / Linux
>
> ```bash theme={null}
> export APIONE_API_KEY="YOUR_APIONE_API_KEY"
> export APIONE_IMAGE_MODEL="YOUR_IMAGE_MODEL"
> ```

> [tab] Windows PowerShell
>
> ```powershell theme={null}
> $env:APIONE_API_KEY = "YOUR_APIONE_API_KEY"
> $env:APIONE_IMAGE_MODEL = "YOUR_IMAGE_MODEL"
> ```

Variables only apply to the current terminal and child processes it starts. Run the examples in the same terminal; IDEs, containers, and new terminals need separate configuration. Do not commit real keys to source control.

## Query model and parameters

First query image models available to the current key, then check the target model's parameters:

```bash theme={null}
curl https://api.apione.ai/v1/models/YOUR_IMAGE_MODEL/params \
  -H "Authorization: Bearer YOUR_APIONE_API_KEY"
```

Size, count, quality, return format, and other extension fields are determined by the model; do not copy enum values from another model.

## Minimal request

```bash theme={null}
curl https://api.apione.ai/v1/images/generations \
  -H "Authorization: Bearer YOUR_APIONE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_IMAGE_MODEL",
    "prompt": "A transparent glass vase in a white studio, soft side light"
  }'
```

A successful response contains the generation result or a result reference. Specific fields and return forms such as URL or Base64 depend on the target model and current parameter documentation.

## Common issues

| Issue | Check |
| - | - |
| Model unavailable | Whether the current key's `/v1/models` includes this ID |
| Parameter error | Fields and enums returned by `/v1/models/{model}/params` |
| Content rejected | Prompt, uploaded material, and target model content rules |
| Empty result or timeout | Request ID, console details, and upstream status |

Images are typically charged per image, per request, or by model rules. Final charges are based on console request details.

## How to confirm request fields

`model` and `prompt` are the core fields in a minimal request. Whether size, count, quality, style, background, seed, negative prompt, and return format are available depends on the target model. After calling the parameters interface, check in this order:

1. Whether the field exists.
2. Whether the type is string, number, boolean, or array.
3. Optional enums and defaults.
4. Whether it affects the per-request charge.
5. Whether it is mutually exclusive with other fields.

> [!WARNING]
>
> Do not copy `size`, `quality`, or `n` directly from one model to another. Even if field names match, allowed values may differ.

## Python example

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

payload = {
    "model": os.environ["APIONE_IMAGE_MODEL"],
    "prompt": "A transparent glass vase in a white studio, soft side light",
}

response = requests.post(
    "https://api.apione.ai/v1/images/generations",
    headers={
        "Authorization": f"Bearer {os.environ['APIONE_API_KEY']}",
        "Content-Type": "application/json",
    },
    json=payload,
    timeout=180,
)
print("status:", response.status_code)
print("request-id:", {name: response.headers[name] for name in ("X-Request-ID", "X-Maxx-Trace-Id", "X-Maxx-Request-ID") if name in response.headers})
response.raise_for_status()
print(response.json())
```

## Node.js example

Use Node.js 18 or higher (built-in `fetch`), and run in the same terminal where the environment variables above are set.

Save the JavaScript below as `example.mjs`. Run `node example.mjs` in the same terminal where this page's environment variables are set. Node.js 18 or higher with built-in `fetch` requires no extra dependencies.

```javascript theme={null}
const response = await fetch("https://api.apione.ai/v1/images/generations", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.APIONE_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: process.env.APIONE_IMAGE_MODEL,
    prompt: "A transparent glass vase in a white studio, soft side light",
  }),
});

console.log("status:", response.status);
console.log("request-id:", Object.fromEntries(["X-Request-ID", "X-Maxx-Trace-Id", "X-Maxx-Request-ID"].map(name => [name, response.headers.get(name)]).filter(([, value]) => value)));
const result = await response.json();
if (!response.ok) throw new Error(JSON.stringify(result));
console.log(result);
```

## Handling generation results

First print a complete response to confirm the structure, then write fixed parsing logic. The return may be a result URL, Base64, or a model-defined object. If you receive a temporary URL, download it to your own storage promptly, and record file type, size, task time, and request ID.

Do not judge image availability by HTTP 200 alone. Also verify:

* Whether the result array is empty.
* Whether the URL is accessible and Base64 is decodable.
* Whether the actual image format matches the extension.
* Whether width, height, transparency channel, and color space meet business requirements.
* Whether content moderation or revision fields need to be shown to the user.

## Pre-production test cases

| Case | Purpose |
| - | - |
| Shortest valid prompt | Verify basic connectivity and default parameters |
| Chinese and English prompts | Verify performance in business languages |
| Minimum/maximum supported sizes | Verify boundaries and cost |
| Unsupported enum values | Confirm error message readability |
| Timeout and disconnect | Verify no infinite repeated generation |
| Content-restricted input | Verify rejection message and user prompt |

## Billing and retries

Media models may charge per image, per request, or by parameter tier. Check model parameters and console prices before batch runs. After a network interruption, retain the request ID; do not infinitely resend the same creation request while the result is unknown.

## End-to-end example: generate and save a PNG

On November 14, 2026, a minimal APIONE request using the available `gpt-image-2` model returned HTTP 200 and `data[0].b64_json`. No size or quality was sent. This response reported `size=1254x1254`, `quality=low`, and `output_format=png`. These are observations from one request, not fixed defaults or guarantees for all groups.

Set `APIONE_API_KEY` and install `requests` as described above. Confirm that your current key still has access to this model. Save as `generate_image.py` and run `python generate_image.py`. The script sends one create request without automatic retries and saves the decoded file in the current directory.

```python theme={null}
import base64
import os
from pathlib import Path
import requests

response = requests.post(
    "https://api.apione.ai/v1/images/generations",
    headers={"Authorization": f"Bearer {os.environ['APIONE_API_KEY']}"},
    json={"model": "gpt-image-2", "prompt":
          "A single blue circle centered on a plain white background, flat icon, no text."},
    timeout=(15, 180),
)
ids = {name: response.headers[name] for name in
       ("X-Request-ID", "X-Maxx-Trace-Id", "X-Maxx-Request-ID")
       if name in response.headers}
print("status:", response.status_code, "request identifiers:", ids)
response.raise_for_status()
result = response.json()
items = result.get("data")
if not isinstance(items, list) or not items:
    raise RuntimeError("No generated image returned")
image = items[0].get("b64_json")
if not image:
    raise RuntimeError("Expected b64_json; inspect this model's actual response")
if result.get("output_format") != "png":
    raise RuntimeError("Output is not PNG; inspect the actual output_format")
content = base64.b64decode(image, validate=True)
if not content.startswith(b"\x89PNG\r\n\x1a\n"):
    raise RuntimeError("Invalid PNG signature")
Path("apione-image.png").write_bytes(content)
print("saved:", Path("apione-image.png").resolve(), "bytes:", len(content))
print("usage:", result.get("usage"))
```

### Actual response with image data omitted

```json theme={null}
{
  "created": 1794638369,
  "background": "opaque",
  "data": [
    {
      "b64_json": "BASE64_IMAGE_DATA_OMITTED",
      "generation_id": "76bcf9e2-ed94-4af7-8a19-8c0ed59ddb18"
    }
  ],
  "output_format": "png",
  "quality": "low",
  "safety_identifier": null,
  "size": "1254x1254",
  "usage": {
    "input_tokens": 23,
    "input_tokens_details": {
      "image_tokens": 0,
      "text_tokens": 23
    },
    "output_tokens": 229,
    "output_tokens_details": {
      "image_tokens": 229,
      "text_tokens": 0
    },
    "total_tokens": 252
  }
}
```

The saved file was decoded as a 1254 by 1254 PNG, 1,043,307 bytes. Usage reported 23 input tokens and 229 output tokens; verify the final charge in the matching APIONE request details. This image response is synchronous and needs no task polling. See [video tasks](https://apione.ai/docs/en/api/videos.md) for asynchronous processing.

## When parameter metadata is empty

HTTP 200 with `params: []`, `request: {}`, or an empty `billingMode` means those details were not declared in this response. It does not prove that a capability is unsupported, permit arbitrary parameters, or indicate a free call. The `usage`, `request`, `second`, and `image` entries in `chargeModes` are listed mode names, not proof that a model bills all four ways.

1. Check the APIONE model details and current key group for protocols and prices.
2. Use confirmed model-specific instructions for size, quality, reference images, masks, and other fields; do not copy enums from another model.
3. Without confirmed parameter instructions, verify the minimal request first and avoid optional fields or batch jobs.
4. Contact support with the model ID, endpoint, time, and actual request identifiers. Do not send the full key.

Next: [Image editing](https://apione.ai/docs/en/api/images-edits.md), [Media parameters](https://apione.ai/docs/en/api/media-parameters.md), [Request reliability](https://apione.ai/docs/en/api/request-reliability.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.