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

# Generating Images

> Turn a text prompt into an image using the /v1/images/generations endpoint.

The `/v1/images/generations` endpoint takes a text prompt and returns one or more images. It is compatible with the OpenAI `images.generate()` SDK method — only the base URL and key need to change.

***

## Basic example

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    from openai import OpenAI

    client = OpenAI(
        base_url="https://api.routeway.ai/v1",
        api_key=os.getenv("ROUTEWAY_API_KEY")
    )

    response = client.images.generate(
        model="flux-1-schnell",
        prompt="A serene Japanese garden at dawn, soft mist, cherry blossoms, photorealistic",
        size="1024x1024",
        n=1,
    )

    print(response.data[0].url)
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    import OpenAI from "openai";

    const client = new OpenAI({
      baseURL: "https://api.routeway.ai/v1",
      apiKey: process.env.ROUTEWAY_API_KEY,
    });

    const response = await client.images.generate({
      model: "flux-1-schnell",
      prompt: "A serene Japanese garden at dawn, soft mist, cherry blossoms, photorealistic",
      size: "1024x1024",
      n: 1,
    });

    console.log(response.data[0].url);
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    curl https://api.routeway.ai/v1/images/generations \
      -H "Authorization: Bearer $ROUTEWAY_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{
        "model": "flux-1-schnell",
        "prompt": "A serene Japanese garden at dawn, soft mist, cherry blossoms, photorealistic",
        "size": "1024x1024",
        "n": 1
      }'
    ```
  </Tab>
</Tabs>

***

## Request parameters

| Parameter         | Type    | Default       | Description                                            |
| ----------------- | ------- | ------------- | ------------------------------------------------------ |
| `model`           | string  | required      | Image model ID (e.g. `"flux-1-schnell"`, `"dall-e-3"`) |
| `prompt`          | string  | required      | Text description of the image to generate              |
| `n`               | integer | `1`           | Number of images to generate (1–10)                    |
| `size`            | string  | model default | Output resolution, e.g. `"1024x1024"`, `"1792x1024"`   |
| `quality`         | string  | model default | Provider-specific preset, e.g. `"standard"`, `"hd"`    |
| `response_format` | string  | `"url"`       | `"url"` or `"b64_json"`                                |

***

## Response object

```json theme={null}
{
  "created": 1749052800,
  "data": [
    {
      "url": "https://cdn.routeway.ai/images/abc123.png",
      "revised_prompt": "A serene Japanese garden at dawn..."
    }
  ]
}
```

| Field                   | Description                                                     |
| ----------------------- | --------------------------------------------------------------- |
| `data[].url`            | Temporary URL to the generated image (expires in 1 hour)        |
| `data[].b64_json`       | Base64 PNG data, present when `response_format: "b64_json"`     |
| `data[].revised_prompt` | The prompt as interpreted by the model, if the model revised it |

***

## Saving images locally

URLs expire after 1 hour. Download the image immediately if you need to keep it.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    import requests
    from openai import OpenAI

    client = OpenAI(
        base_url="https://api.routeway.ai/v1",
        api_key=os.getenv("ROUTEWAY_API_KEY")
    )

    response = client.images.generate(
        model="flux-1-schnell",
        prompt="A futuristic cityscape at night, neon lights, rain-slicked streets",
        size="1024x1024",
    )

    image_url = response.data[0].url
    image_bytes = requests.get(image_url).content

    with open("output.png", "wb") as f:
        f.write(image_bytes)

    print("Saved to output.png")
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    import OpenAI from "openai";
    import fs from "fs";

    const client = new OpenAI({
      baseURL: "https://api.routeway.ai/v1",
      apiKey: process.env.ROUTEWAY_API_KEY,
    });

    const response = await client.images.generate({
      model: "flux-1-schnell",
      prompt: "A futuristic cityscape at night, neon lights, rain-slicked streets",
      size: "1024x1024",
    });

    const imageUrl = response.data[0].url;
    const imageResponse = await fetch(imageUrl);
    const buffer = Buffer.from(await imageResponse.arrayBuffer());
    fs.writeFileSync("output.png", buffer);

    console.log("Saved to output.png");
    ```
  </Tab>
</Tabs>

Alternatively, request `response_format: "b64_json"` to receive the image bytes directly in the API response — no second HTTP request needed.

```python theme={null}
import base64

response = client.images.generate(
    model="flux-1-schnell",
    prompt="Abstract watercolour landscape",
    response_format="b64_json",
)

image_bytes = base64.b64decode(response.data[0].b64_json)

with open("output.png", "wb") as f:
    f.write(image_bytes)
```

***

## Generating multiple images

Set `n` to receive several variations in a single call. Each item in `data` is an independent generation.

```python theme={null}
response = client.images.generate(
    model="flux-1-schnell",
    prompt="A cosy mountain cabin in winter, warm light from the windows",
    size="1024x1024",
    n=4,
)

for i, image in enumerate(response.data):
    print(f"Image {i + 1}: {image.url}")
```

***

## Choosing size and quality

Available sizes and quality presets vary by model. As a general guide:

| Size        | Aspect ratio | Typical use                       |
| ----------- | ------------ | --------------------------------- |
| `1024x1024` | Square       | Social media, avatars, thumbnails |
| `1792x1024` | Landscape    | Banners, hero images              |
| `1024x1792` | Portrait     | Mobile wallpapers, posters        |

| Quality    | Trade-off                                |
| ---------- | ---------------------------------------- |
| `standard` | Faster, lower cost, slightly less detail |
| `hd`       | Slower, higher cost, finer details       |

<Tip>
  Use `flux-1-schnell` for iteration and prototyping — it generates in seconds. Switch to `flux-1-dev` or `dall-e-3` when quality matters for production output.
</Tip>

***

## Writing effective prompts

Image models are sensitive to how prompts are written. A few techniques that consistently improve results:

<AccordionGroup>
  <Accordion title="Be specific about style and medium" icon="palette">
    Vague prompts produce generic results. Name a style, medium, or artist reference to anchor the output.

    ```
    # Vague
    "A forest"

    # Specific
    "A dense pine forest at dusk, oil painting, dramatic lighting, muted earth tones"
    ```
  </Accordion>

  <Accordion title="Describe composition and perspective" icon="frame">
    Tell the model where to place things and from what angle.

    ```
    "Close-up portrait of an elderly sailor, weathered face, looking off-camera,
    shallow depth of field, golden hour light"
    ```
  </Accordion>

  <Accordion title="Add technical photography terms" icon="camera">
    Terms like `shallow depth of field`, `35mm lens`, `shot on film`, `bokeh`, and `golden hour` reliably improve photorealistic outputs.
  </Accordion>

  <Accordion title="Use negative prompts where supported" icon="ban">
    Some models (like FLUX) accept a `negative_prompt` parameter to exclude unwanted elements.

    ```json theme={null}
    {
      "prompt": "A clean minimal product photo of a white ceramic mug",
      "negative_prompt": "blurry, watermark, text, cluttered background, low quality"
    }
    ```
  </Accordion>
</AccordionGroup>

***

## Error handling

```python theme={null}
from openai import BadRequestError

try:
    response = client.images.generate(
        model="flux-1-schnell",
        prompt="...",
    )
    print(response.data[0].url)
except BadRequestError as e:
    # Prompt was rejected (content policy, invalid parameters, etc.)
    print(f"Request error: {e.message}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

Common errors:

| Status | Cause                                                   |
| ------ | ------------------------------------------------------- |
| `400`  | Invalid parameters or prompt rejected by content policy |
| `401`  | Missing or invalid API key                              |
| `429`  | Rate limit or insufficient balance                      |
| `500`  | Upstream model error — retry with exponential backoff   |
