All guides

OpenRouter Image API: generate an image and check delivery

Check model and endpoint capabilities, send a text prompt to /api/v1/images, then verify output, failures and cleanup. No API was run here.

AINav editorsWritten / Updated Sources checked
On this page

At a glance

OpenRouter's documentation describes a dedicated Image API that turns a text prompt, and optionally reference images, into images. It covers model discovery, per-endpoint capabilities and generation. This tutorial follows that order and then adds delivery checks. Checks marked editorial are this site's recommendations, not OpenRouter behavior.

Task workflow

  1. Model-level and endpoint-level capabilities

    The list at /api/v1/images/models gives each model an id, an architecture block, supported_parameters, supports_streaming and an endpoints path. At model level, supported_parameters is the union of capabilities across all endpoints, so a parameter listed there does not prove that every endpoint accepts it. The per-endpoint records are the definitive source: each has its own supported_parameters (a subset of the union), allowed_passthrough_parameters, supports_streaming and pricing. A descriptor is an enum with allowed values, a range with min and max, or a boolean, and an absent key means that endpoint does not support the parameter.

  2. Request fields and their limits

    Only model and prompt are required. n is an upper bound from 1 to 10: providers may return fewer images, and single-image providers reject n above 1. output_format accepts png, jpeg, webp, svg (vectorization models only) or gif (animation-capable models only), and the provider default applies when it is omitted. Providers without a quality control ignore quality. The provider object, with fields such as only, order, ignore, sort, allow_fallbacks, zdr and data_collection, narrows which endpoints may serve the request. Read together, a request has to fit both your routing limits and the capabilities of the endpoints that remain, so check the records of those endpoints as well as the model-level union. With zdr set to true, the request fails if no endpoint qualifies.

  3. Response shape and billing

    By default images come back as base64 bytes in data[].b64_json. media_type is present whenever the format can be identified, including image/png, and omitted only when it cannot. usage reports token counts and cost when available. With response_format set to url, each item carries a url, the response adds expires_at, and the links expire after 24 hours. Billing is all-or-nothing: a completed generation is billed in full, and one that does not complete returns 502 Bad Gateway with no charge. If a client disconnects mid-generation, the upstream provider may still finish rendering and charge OpenRouter, yet the client sees only a fully billed result or an error. In the url case, a completed generation is billed once its output is stored, even if the client never receives the response, and storage does not recover a lost response.

  4. Editorial completion checks

    The source defines no delivery checklist, so everything in this layer is an editorial recommendation. A static check inspects the HTTP status, the presence of data, and a non-empty b64_json or url per item. A semantic check compares the decoded image with the prompt. The Python excerpt prints only the length of each base64 string, which shows that a string arrived and says nothing about what the picture contains. The source defines no cancellation API for this request, so the stopping rules in step six are manual controls chosen by the editor.

Inputs, processing and deliverables from official documentation; the product was not run in this batch.

Task and deliverable

OpenRouter's documentation describes a dedicated Image API that turns a text prompt, and optionally reference images, into images. It covers model discovery, per-endpoint capabilities and generation. This tutorial follows that order and then adds delivery checks. Checks marked editorial are this site's recommendations, not OpenRouter behavior.

Prepare the input and environment

  • An OpenRouter API key placed in the environment variable OPENROUTER_API_KEY. The Python excerpt reads it with os.environ['OPENROUTER_API_KEY'] and sends it as a Bearer token. The source does not describe how to create or fund a key, and this batch did not check login state, account permissions or current pricing.
  • A Python environment with requests for the generation excerpt. The excerpt imports os, requests and json, though json is never used, and the source shows no installation step. The two discovery excerpts are TypeScript using fetch; they need a runtime that provides fetch and an async context that allows await, and they only assign models and endpoints without printing anything.
  • A text prompt and a model slug. The request requires only model and prompt, and the slug should come from model discovery.
  • Network access to openrouter.ai and a budget you are willing to spend on generation. A spending cap is an editorial recommendation, and billing follows the pricing of the endpoint that serves the request.

Mechanism and data flow

Model-level and endpoint-level capabilities: The list at /api/v1/images/models gives each model an id, an architecture block, supported_parameters, supports_streaming and an endpoints path. At model level, supported_parameters is the union of capabilities across all endpoints, so a parameter listed there does not prove that every endpoint accepts it. The per-endpoint records are the definitive source: each has its own supported_parameters (a subset of the union), allowed_passthrough_parameters, supports_streaming and pricing. A descriptor is an enum with allowed values, a range with min and max, or a boolean, and an absent key means that endpoint does not support the parameter.

Request fields and their limits: Only model and prompt are required. n is an upper bound from 1 to 10: providers may return fewer images, and single-image providers reject n above 1. output_format accepts png, jpeg, webp, svg (vectorization models only) or gif (animation-capable models only), and the provider default applies when it is omitted. Providers without a quality control ignore quality. The provider object, with fields such as only, order, ignore, sort, allow_fallbacks, zdr and data_collection, narrows which endpoints may serve the request. Read together, a request has to fit both your routing limits and the capabilities of the endpoints that remain, so check the records of those endpoints as well as the model-level union. With zdr set to true, the request fails if no endpoint qualifies.

Response shape and billing: By default images come back as base64 bytes in data[].b64_json. media_type is present whenever the format can be identified, including image/png, and omitted only when it cannot. usage reports token counts and cost when available. With response_format set to url, each item carries a url, the response adds expires_at, and the links expire after 24 hours. Billing is all-or-nothing: a completed generation is billed in full, and one that does not complete returns 502 Bad Gateway with no charge. If a client disconnects mid-generation, the upstream provider may still finish rendering and charge OpenRouter, yet the client sees only a fully billed result or an error. In the url case, a completed generation is billed once its output is stored, even if the client never receives the response, and storage does not recover a lost response.

Editorial completion checks: The source defines no delivery checklist, so everything in this layer is an editorial recommendation. A static check inspects the HTTP status, the presence of data, and a non-empty b64_json or url per item. A semantic check compares the decoded image with the prompt. The Python excerpt prints only the length of each base64 string, which shows that a string arrived and says nothing about what the picture contains. The source defines no cancellation API for this request, so the stopping rules in step six are manual controls chosen by the editor.

Workflow map

Workflow stages and responsibilities
StageWhat happens
Model-level and endpoint-level capabilitiesThe list at /api/v1/images/models gives each model an id, an architecture block, supported_parameters, supports_streaming and an endpoints path.
Request fields and their limitsOnly model and prompt are required.
Response shape and billingBy default images come back as base64 bytes in data[].b64_json.
Editorial completion checksThe source defines no delivery checklist, so everything in this layer is an editorial recommendation.

Complete the task

Set up the key and runtime: Set OPENROUTER_API_KEY in the shell that will run the Python excerpt and confirm requests is available there. The excerpt reads that variable with os.environ, so a missing variable raises a KeyError before any request is sent. Before sending anything, decide a spending limit and a stopping point; both are editorial recommendations. The source does not cover key creation, account permissions or current prices, and none of them was checked here.

List image models: Run the first TypeScript excerpt in a runtime that provides fetch and allows await. It requests /api/v1/images/models and stores the parsed JSON in models; it prints nothing and sends no key. Inspect each entry's id, architecture.output_modalities and supported_parameters, and write down the id you plan to use as model. The source also lists /api/v1/models?output_modalities=image and the Models page filter on output modalities as other discovery routes.

Read the endpoint records: The second excerpt fetches the endpoints path for bytedance-seed/seedream-4.5 and stores the result in endpoints. It hard-codes the Seedream path, so another model needs the address from its own endpoints field. For each endpoint, read supported_parameters, allowed_passthrough_parameters, supports_streaming and the pricing lines, where each line has billable, unit, cost_usd and sometimes a variant. Check generation parameters such as n and output_format against the expected endpoint's capabilities. Configure provider separately under Provider Routing, then check the remaining endpoints' generation capabilities. provider need not appear in supported_parameters. The source's sample record shows a cost_usd of 0.05 per output image, which is documentation sample data and not a current price.

Send the generation request: The Python excerpt posts to https://openrouter.ai/api/v1/images with a Bearer header built from the environment variable. Its payload sets model to bytedance-seed/seedream-4.5 and prompt to an English description of a red panda astronaut; the script runs as supplied only when the key, requests and network access are in place. It parses the body into result, loops over result["data"] and prints the length of each b64_json. It does not check the HTTP status, set a timeout, decode or save an image, or use the json import. If the body is an error object without data, the loop fails with a KeyError. Check endpoint generation capabilities before adding n or output_format. Configure the provider routing object under Provider Routing rules.

Read the response and save the image: the JSON excerpt illustrates a response shape, not fields guaranteed in every response. Default data items carry b64_json; usage reports tokens and cost only when available, and media_type appears when the format is identifiable. Missing usage or legitimately omitted media_type is not a failure. The placeholder, numbers and Generated image (1391708 chars) are documentation samples. The following delivery steps are editorial recommendations: decode each actual b64_json to bytes, identify the actual format and choose its file extension, then write the bytes to your chosen delivery directory. If the format is unknown, identify it before choosing an extension. For url, download the image to that directory before expires_at. Open the saved image and compare it with the prompt, then compare the count with n; fewer images do not automatically indicate an error. The original Python excerpt only prints string lengths. Add saving and content checks in your own environment; printing a length does not deliver an image.

Choose an exit and clean up (editorial recommendation): success requires a 2xx status, non-empty data, valid required output fields, a saved image and passed content acceptance. Stop on a non-2xx status, an error body or a 502, retaining diagnostic information without automatic retries. Missing or empty data or blank output fields mean undelivered output. Record decoding, saving, downloading or content-check failures too; valid JSON alone is not completion. If you interrupt the client, an incomplete generation is not billed, though an upstream provider may continue rendering and charge OpenRouter. A completed stored result in url mode is still billed. On every exit, keep accepted delivery files and remove only temporary files and sensitive logs created for this attempt as needed. Clear the temporary shell variable OPENROUTER_API_KEY, and rotate a key that was printed or shared. Cleanup should preserve the deliverable.

Worked example

The source's showcase request used openai/gpt-image-2 with quality high, aspect_ratio 16:9 and n 1. Its prompt asks for an editorial photograph of a neighborhood storefront at blue hour, with a warm-white neon sign in hand-bent cursive that reads exactly "OpenRouter" as the only text in the scene, a quiet street with no people, and a straight-on composition. The source reports a 1536×864 PNG, 94 seconds and $0.13 for that run. Those are the documentation's figures, not results from this site, and they predict nothing for your account. The Python excerpt in step four uses a different model and a red panda prompt, so the storefront run is a separate documented case. Applying this article's checks to a similar request: confirm the status; expect at most one item in data because n is 1; treat media_type as image/png only if the response says so; then look at the decoded image for a single sign reading OpenRouter, no other text and no people. Those visual checks are editorial and manual.

Official documentation excerpt: read under the stated prerequisites; not run in this batch
typescript
const response = await fetch('https://openrouter.ai/api/v1/images/models');
const models = await response.json();
Official documentation excerpt: read under the stated prerequisites; not run in this batch
typescript
const response = await fetch('https://openrouter.ai/api/v1/images/models/bytedance-seed/seedream-4.5/endpoints');
const endpoints = await response.json();
Official documentation excerpt: read under the stated prerequisites; not run in this batch
python
import os
import requests
import json

url = "https://openrouter.ai/api/v1/images"
headers = {
    "Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}",
    "Content-Type": "application/json"
}

payload = {
    "model": "bytedance-seed/seedream-4.5",
    "prompt": "a red panda astronaut floating in space, studio lighting"
}

response = requests.post(url, headers=headers, json=payload)
result = response.json()

for image in result["data"]:
    # image["b64_json"] contains the base64-encoded image
    print(f"Generated image ({len(image['b64_json'])} chars)")

Official documentation excerpt: read under the stated prerequisites; not run in this batch
json
{
  "created": 1748372400,
  "data": [
    {
      "b64_json": "<base64-encoded-image>",
      "media_type": "image/png"
    }
  ],
  "usage": {
    "prompt_tokens": 0,
    "completion_tokens": 4175,
    "total_tokens": 4175,
    "cost": 0.04
  }
}

Check the result and failure paths

  • Success (editorial rule): the status is 2xx, data is non-empty, each item has b64_json (or url when response_format is url), and a manual look at the decoded image matches the prompt. Valid JSON alone does not show that generation succeeded.
  • Failure: a non-2xx status, an error body or 502 Bad Gateway. The source also names a 400 when an explicit pixel size is sent with a mismatched resolution or aspect_ratio to a provider that accepts pixel sizes, and a failed request when zdr is true and no endpoint qualifies. Per the source, a generation that does not complete is not billed. Stop and keep the response body for diagnosis.
  • Empty or short output: no data, an empty array, a blank b64_json, or fewer items than n. Per the source, n is an upper bound and providers may return fewer, so a short count is not automatically an error and the decision to accept it is yours; the other cases count as undelivered.
  • User stopping: this is a manual control and not an official cancellation API. After you interrupt the client process, the source describes only the billing outcome: an incomplete generation is not billed, though the upstream may still finish rendering and charge OpenRouter, and in the url case a stored result is still billed after a disconnect.
  • With url: download before expires_at, since links expire after 24 hours, and do not expect storage to recover a lost response.

Scope and limits

  • This tutorial covers non-streaming text-to-image only. The source also describes streaming, reference images, gif animation and markup editing, which are not expanded here. stream applies only to models whose supports_streaming is true, and the Seedream endpoint in the source sample lists false.
  • The costs, durations and sample outputs in the source are documentation data and should not be read as your expectation. Models, prices and parameters follow the official page and your own endpoint records, and they may change.
  • One successful request says nothing about later ones, and the documentation does not promise that an image matches its prompt, so you have to check content yourself.

No OpenRouter API, model or code excerpt was run, installed or called in this batch, and no account, login state, key or billing was checked. Everything here comes from the s1 documentation page, the sample outputs are the page's own, and the completion checks and manual stopping steps are editorial recommendations, not official behavior.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. OpenRouter · Official sources
    View details