Browse documentation

Image Generations

Generate photorealistic images and custom graphics from descriptive text prompts across multi-cloud vision models with transparent per-image list pricing.

Last updated

The /v1/images/generations endpoint provides unified programmatic image generation across top image synthesis providers, including DALL-E 3, Imagen 3, and partner diffusion models. By funneling vision generation through nRouter, organizations gain automated multi-cloud failover, pre-generation prompt safety inspection, transparent per-image list pricing, and centralized billing.

POST https://api.nrouter.ai/v1/images/generations
Multiple Engines
DALL-E & Imagen

Access OpenAI DALL-E 3, Google Imagen 3, and specialized models behind one key.

Flexible Aspect
Square & Wide

Generate 1024x1024, 1024x1792 portrait, and 1792x1024 landscape visuals on demand.

Security Shield
$0 Refusal Cost

Pre-call moderation halts prompt injections before provider reservation. $0 charged.

Pricing Model
Zero Markup

Billed at raw provider list prices per generated image with no hidden fees.


Architectural Role & Lifecycle

Generating visual assets demands higher compute latency and distinct unit economics compared to standard text completions. nRouter manages this lifecycle through strict preflight controls:

  1. Phase 1: In-Memory Key Auth & Vision Entitlements: Verifies virtual key hash (sk-nrouter-...) and validates tenant authorization for image generation engines.
  2. Phase 2: Concurrency & Rate Limit Validation: Validates image generation RPM and concurrent job limits to prevent upstream provider rate exhaustion.
  3. Phase 3: Content Moderation & Injection Scoring: Evaluates the image description prompt against safety classifiers. If prompt injection or prohibited content is detected, the request halts with HTTP 400 (x-nr-guardrails: blocked).
  4. Phase 4: Per-Image Credit Reservation: Calculates the fixed cost per image based on the model tier, resolution, and quality level, placing an atomic hold on organization credits. Blocked requests incur zero hold and zero spend.
  5. Provider Execution & Asset Return: Dispatches the generation job to the upstream provider. When the asset is synthesized, nRouter commits exact spend and stamps full telemetry headers onto the response payload.

Request Parameters

The request body must be a JSON object:

ParameterTypeRequiredDefaultDescription
promptstringYes—A text description of the desired image(s). Maximum length is 4,000 characters for DALL-E 3 and 1,000 characters for legacy models.
modelstringYes—The model to use for image generation (e.g. dall-e-3, imagen-3, dall-e-2).
nintegerNo1The number of images to generate. Must be 1 for DALL-E 3; between 1 and 4 for DALL-E 2 and Imagen 3.
qualitystringNostandardThe quality of the image that will be generated: standard or hd. hd creates images with finer details and consistency.
response_formatstringNob64_jsonThe format in which the generated images are returned: url or b64_json. Base64 format is recommended for programmatic pipelines.
sizestringNo1024x1024The size of the generated images: 1024x1024, 1024x1792 (portrait), 1792x1024 (landscape), 512x512, or 256x256.
stylestringNovividThe style of the generated images: vivid (hyper-real, dramatic) or natural (more subdued, realistic). Supported on DALL-E 3.
userstringNo—A unique identifier representing your end-user for monitoring and abuse prevention.

Response Payloads

Standard Image Response

{
  "created": 1700000000,
  "data": [
    {
      "b64_json": "iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6...",
      "revised_prompt": "A modern minimalist server room illuminated in soft neon indigo..."
    }
  ]
}

Headers Reference

Inbound Request Headers

HeaderTypeRequiredDescription
AuthorizationstringYesBearer authentication format: Bearer sk-nrouter-....
Content-TypestringYesMust be application/json.
x-nr-tagsstringNoCost attribution metadata (e.g. campaign=q3_launch,asset=hero).

Outbound Response Headers

HeaderTypeDescription
x-nr-request-idstringUnique UUID correlation identifier stamped on every request.
x-nr-latency-msintegerEdge turnaround time in milliseconds.
x-nr-request-costfloatExact USD cost of the image generation calculated from provider rates.
x-nr-cost-statusstringexact when priced or unpriced if rate metadata is pending.
x-nr-modelstringUpstream physical model that synthesized the image.
x-nr-routingstringRouting chain outcome: direct or fallback:<n>.
x-nr-attemptsintegerNumber of upstream provider attempts made.
x-nr-guardrailsstringGuardrail evaluation result: none, monitor, pass, or blocked.

SDK Code Examples

import { nRouter } from "@nrouter_ai/sdk";
import * as fs from "node:fs";

const client = new nRouter({
  apiKey: process.env.NROUTER_API_KEY,
});

const response = await client.images.generate({
  model: "dall-e-3",
  prompt: "A futuristic enterprise datacenter cooling system with bioluminescent cooling fluid.",
  size: "1024x1024",
  quality: "hd",
  response_format: "b64_json",
});

const imageBase64 = response.data[0].b64_json;
if (imageBase64) {
  await fs.promises.writeFile("datacenter.png", Buffer.from(imageBase64, "base64"));
  console.log("Image saved to datacenter.png");
}

Error Handling & Failure Troubleshooting

{
  "error": {
    "type": "gateway_error",
    "message": "Size 2048x2048 is not supported for model dall-e-3.",
    "code": "invalid_request"
  }
}
HTTP StatusError CodeTrigger ConditionMitigation Strategy
400 Bad Requestinvalid_requestUnsupported resolution, parameter incompatibility (e.g. n > 1 on DALL-E 3), or prompt exceeding character ceiling.Validate parameters against model constraints before issuing request.
400 Bad Requestguardrail_blockedPrompt violated safety policies, NSFW restrictions, or prompt injection guardrails.Review prompt against content safety rules; blocked calls incur $0 cost.
401 Unauthorizedinvalid_api_keyVirtual key missing, expired, or invalid.Verify sk-nrouter-... key in organization dashboard.
402 Payment Requiredinsufficient_creditsOrganization prepaid balance is insufficient to reserve per-image hold.Add credit balance via the dashboard billing interface.
404 Not Foundmodel_not_foundRequested image model is unrecognized or unauthorized.Consult the model catalog via GET /v1/models for active vision engines.
429 Too Many Requestsrate_limit_exceededAccount RPM or concurrent generation quota exceeded.Check x-nr-limit-source header and apply exponential backoff.
500 / 503 Provider Errorservice_unavailableUpstream image provider experiencing an outage or timeout.nRouter automatically initiates fallback routing if alternative models are configured.
POST
/v1/images/generations

Authorization

NRouterApiKey
AuthorizationBearer <token>

Your nRouter virtual key (sk-nrouter-…). Sent as Authorization: Bearer sk-nrouter-….

In: header

Header Parameters

x-nr-compress?string

Request prompt compression: on to compress eligible prompts, off to skip

Value in

  • "on"
  • "off"
x-nr-tags?string

Custom spend and attribution tags (comma-separated key=value pairs)

x-nr-mcp-server?string

Target MCP server ID when routing MCP tool calls or prompts through the gateway

Request Body

application/json

TypeScript Definitions

Use the request body type in TypeScript.

Response Body

application/json

application/json

application/json

application/json

application/json

application/json

application/json

application/json

application/json

application/json

curl -X POST "https://example.com/v1/images/generations" \  -H "Content-Type: application/json" \  -d '{    "model": "dall-e-3",    "prompt": "A sleek minimalist server room in deep twilight blue.",    "size": "1024x1024"  }'
{  "created": 1700000000,  "data": [    {      "b64_json": "<base64-png>"    }  ]}
Was this page helpful?