Image generation

Connect GPT Image, Seedream and configured image models.

POST/v1/images/generations
https://api.hanrouter.ai/v1Manage API keys

URL and authentication

Use https://api.hanrouter.ai/v1 as the OpenAI-compatible Base URL and Authorization: Bearer $HANROUTER_API_KEY. Do not duplicate /v1. All manufacturers use your HanRouter key, not an upstream vendor key.

For the Anthropic SDK and Claude Code, use https://api.hanrouter.ai without /v1; the client appends /v1/messages. Use the OpenAI-compatible interface for Google models.

Before calling: models and permissions

Call GET /v1/models and use an exact image model ID returned for your key. The plaza shows output types and prices; listing a model does not guarantee every endpoint or parameter. Your key group must also enable image generation.

Text to image: minimal request

Set HANROUTER_API_KEY and replace YOUR_IMAGE_MODEL_ID with an available ID. Start with model, prompt and n; add size, quality or response_format only when supported. Running this command creates a real generation and may incur charges.

Request example
curl --max-time 300 "https://api.hanrouter.ai/v1/images/generations" \
  -H "Authorization: Bearer $HANROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_IMAGE_MODEL_ID",
  "prompt": "A golden bull in front of a modern city skyline, cinematic lighting",
  "n": 1
}'

Parameters and model differences

model and prompt are required strings. n is the image count; start with 1 and follow model limits. size commonly uses WIDTHxHEIGHT, such as 1024x1024, but supported sizes differ. quality and response_format are model-specific; do not reuse vendor parameters indiscriminately.

Some Gemini image models or channels use multimodal Chat Completions or a native protocol instead of Images. These examples require an Images-compatible channel. For response_modalities casing or protocol errors, retain the request ID and contact support rather than repeatedly changing model names.

Image to image and editing

Image-to-image protocols vary. A Grok Imagine channel supporting this format can accept image: {"url":"https://..."} on POST /v1/images/generations. This is an object, not a bare URL string. The upstream must be able to access the reference. This field is not universal; confirm channel support.

Request example
curl --max-time 300 "https://api.hanrouter.ai/v1/images/generations" \
  -H "Authorization: Bearer $HANROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "YOUR_GROK_IMAGE_MODEL_ID",
  "prompt": "Turn this reference into a watercolor illustration",
  "image": {
    "url": "https://example.com/reference.png"
  }
}'

Upload a local image: multipart editing

The studio uploads files to POST /v1/images/edits for editing-capable models. Use -F for multipart/form-data; let cURL set Content-Type and boundary rather than application/json. Replace reference.png with your PNG/JPEG/WebP file. Formats, size limits, masks and multiple inputs depend on the model.

Request example
curl --max-time 300 "https://api.hanrouter.ai/v1/images/edits" \
  -H "Authorization: Bearer $HANROUTER_API_KEY" \
  -F "model=$HANROUTER_IMAGE_MODEL" \
  -F 'prompt=Keep the subject and change the background to a city at sunset' \
  -F 'n=1' \
  -F 'image=@reference.png'

Response: URL and Base64

Synchronous results commonly use data[].url or data[].b64_json; both are not guaranteed together. Decode b64_json to image bytes before saving. URLs may expire; download promptly. These are illustrative structures, not actual generated results. Handle optional usage or revised_prompt fields as returned.

Request example
{
  "data": [
    {
      "url": "https://example.com/generated-image.png"
    }
  ]
}

{
  "data": [
    {
      "b64_json": "<BASE64_IMAGE_BYTES>"
    }
  ]
}

Python: generate and save an image

This uses the Python standard library. Set HANROUTER_API_KEY and HANROUTER_IMAGE_MODEL; it handles URL or Base64 output and saves PNG, JPEG or WebP based on file signatures. Keep credentials out of source code.

Request example
import base64, json, os, pathlib, urllib.request

payload = {"model": os.environ["HANROUTER_IMAGE_MODEL"],
           "prompt": "A golden bull in a modern city, cinematic lighting", "n": 1}
request = urllib.request.Request(
    "https://api.hanrouter.ai/v1/images/generations",
    data=json.dumps(payload).encode(),
    headers={"Authorization": "Bearer " + os.environ["HANROUTER_API_KEY"],
             "Content-Type": "application/json"})
with urllib.request.urlopen(request, timeout=300) as response:
    result = json.load(response)
for index, item in enumerate(result["data"], 1):
    if item.get("b64_json"):
        image = base64.b64decode(item["b64_json"])
    else:
        with urllib.request.urlopen(item["url"], timeout=60) as response:
            image = response.read()
    extension = ".png" if image.startswith(b"\x89PNG") else ".jpg" if image.startswith(b"\xff\xd8") else ".webp"
    pathlib.Path(f"image-{index}{extension}").write_bytes(image)

Async images and troubleshooting

Where enabled, submit to POST /v1/images/generations/async or /v1/images/edits/async, retain request_id / task_id / id and poll GET /v1/images/tasks/{id} with the same key. Follow the actual status, result and image data. A disabled async endpoint may return 404; only switch to sync after confirming an endpoint-disabled error, not an unrelated model 404.

403 permission_error / Image generation is not enabled for this group: ask an administrator to enable group permissions. For 400 check model, size, image fields and protocol; 401 check the key; 402/403 check balance, quota and permissions; 429 follow Retry-After. For 5xx/timeouts retain X-Request-Id, time and a redacted response; check tasks and usage before resubmitting. See /docs/generate-video for video submission, polling and starting-frame examples.

Request parameters

model
Required string: exact model ID available to your key.
prompt
String: image or prompt-adapter video description; native content depends on channel requirements.
size
Optional string: an image size supported by the model.
n
Optional integer: generation count within model limits.
quality
Optional string: model-specific quality tier.
image
Optional object: {url: "https://..."} on compatible image-to-image channels; local edits use multipart /images/edits.

Request example

Examples use configured model IDs. Key group permissions determine access; query GET /v1/models first.

cURL
curl -X POST "https://api.hanrouter.ai/v1/images/generations" \
  -H "Authorization: Bearer $HANROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "your-model-id",
  "prompt": "A red bicycle beside a tree"
}'

Response example

JSON · illustrative structure
{
  "data": [
    {
      "url": "https://example.com/generated-image.png"
    }
  ]
}