How to Generate Images with API — Step-by-Step Guide (2026)

Aug 19, 2026·7 min read

You've built a product that needs AI-generated images on demand—product shots, thumbnail variants, marketing visuals. The three models you want each have different authentication schemes, parameter shapes, and response formats if you call them directly. GenRelay normalizes Nano Banana Pro, Nano Banana 2, and GPT-image-2 behind a single OpenAI-compatible endpoint, so you can swap models with one parameter change and keep the rest of your code identical.

This guide walks the full integration path: credentials, your first working request, every parameter that matters, error handling, and cost math.


What do I need before I start?

Three things:

  1. A GenRelay account — the free tier includes starter credits with no credit card required
  2. An API key from the GenRelay dashboard under API Keys
  3. Python 3.8+ (or curl for quick tests)

No upstream API keys are needed. GenRelay handles authentication with each model provider.


How do I authenticate with the GenRelay image API?

Authentication uses a standard Bearer token in the Authorization header. Every request targets the same base URL: https://genrelay.ai/v1.

import os
import requests

API_KEY = os.environ["GENRELAY_API_KEY"]

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
}

Keep the key in an environment variable or secrets manager. A leaked key means unexpected charges billed to your account.

curl equivalent:

curl -H "Authorization: Bearer $GENRELAY_API_KEY" \
     -H "Content-Type: application/json" \
     https://genrelay.ai/v1/images/generations \
     -d '{"model":"nano-banana-pro","prompt":"product shot","size":"1024x1024"}'

How do I make my first image generation request?

The endpoint is POST /v1/images/generations. Minimum required fields: model and prompt.

response = requests.post(
    "https://genrelay.ai/v1/images/generations",
    headers=headers,
    json={
        "model": "nano-banana-pro",
        "prompt": "Studio-lit photograph of a glass perfume bottle on white marble, soft shadows, product photography",
        "size": "1024x1024",
        "n": 1,
    },
)
response.raise_for_status()
result = response.json()
image_url = result["data"][0]["url"]
print(f"Image ready: {image_url}")

Image generation is synchronous — the URL is returned directly in the response body. No polling loop is required, unlike video generation. URLs expire after 24 hours; download to your own storage if you need them longer.


Which model should I use for my use case?

As of August 2026, GenRelay supports three image models:

Model Best for 1K price 4K price
nano-banana-pro Photorealistic product shots, portraits, high-detail renders $0.030 $0.042
nano-banana-2 High-volume generation, illustrations, speed-sensitive pipelines $0.020 $0.036
gpt-image-2 Inpainting, edits, branded content with text $0.014 flat

GPT-image-2 is billed per image regardless of output dimensions — useful when you're generating multiple aspect ratios and don't want per-size pricing to complicate your cost model.

See the AI image API pricing breakdown for a detailed per-request cost comparison across all three models.


What parameters control image output?

size — resolution

Supported sizes vary by model:

  • nano-banana-pro: "1024x1024" (1K), "2048x2048" (2K), "4096x4096" (4K)
  • nano-banana-2: "1024x1024" (1K), "4096x4096" (4K)
  • gpt-image-2: "1024x1024", "1024x1536", "1536x1024" (portrait and landscape)

n — batch count

Generate 1–4 images per request. Each image is billed individually at the per-image rate.

# Generate 4 variants in one request for A/B testing
response = requests.post(
    "https://genrelay.ai/v1/images/generations",
    headers=headers,
    json={
        "model": "nano-banana-2",
        "prompt": "Minimalist app icon, abstract geometric shape, gradient blue to purple, white background",
        "size": "1024x1024",
        "n": 4,
    },
)
images = [item["url"] for item in response.json()["data"]]
print(f"Generated {len(images)} variants")

quality — detail level (Nano Banana Pro only)

  • "standard" — default, faster, suitable for most use cases
  • "hd" — sharper fine detail, ~30–40% higher latency, useful for technical illustrations or images that will be zoomed

response_format

  • "url" — hosted link (default); easiest for most integrations
  • "b64_json" — inline base64 PNG; useful when your environment can't reach external URLs, or you want to avoid a second download step

style (Nano Banana Pro only)

  • "vivid" — higher contrast, more saturated; good for marketing visuals
  • "natural" — closer to photographic realism; better for product photography

How do I handle errors and retries correctly?

Image APIs return standard HTTP status codes. Build retry logic only for transient errors — not for bad requests:

Status Meaning Action
200 Success Parse data[].url or data[].b64_json
400 Invalid parameter Fix the request, do not retry
429 Rate limited Retry with exponential backoff
500 / 503 Upstream model error Retry up to 3× with increasing delay
import time

def generate_image(
    prompt: str,
    model: str = "nano-banana-pro",
    size: str = "1024x1024",
    retries: int = 3,
) -> str:
    for attempt in range(retries):
        resp = requests.post(
            "https://genrelay.ai/v1/images/generations",
            headers=headers,
            json={"model": model, "prompt": prompt, "size": size, "n": 1},
        )
        if resp.status_code == 200:
            return resp.json()["data"][0]["url"]
        if resp.status_code == 400:
            raise ValueError(f"Bad request: {resp.json().get('error', {}).get('message')}")
        if resp.status_code in (429, 500, 503):
            wait = 2 ** attempt  # 1s, 2s, 4s
            print(f"Attempt {attempt + 1} failed ({resp.status_code}), retrying in {wait}s")
            time.sleep(wait)
    raise RuntimeError(f"Image generation failed after {retries} attempts")

How much does image generation cost via the API?

Cost depends on model and resolution. Here are two common workloads:

500 product shots per day at 1K resolution:

Model Per image Daily cost Monthly cost
gpt-image-2 $0.014 $7.00 ~$210
nano-banana-2 $0.020 $10.00 ~$300
nano-banana-pro $0.030 $15.00 ~$450

100 high-resolution catalog images per day at 4K:

Model Per image Daily cost
nano-banana-pro $0.042 $4.20
nano-banana-2 $0.036 $3.60
gpt-image-2 $0.014 $1.40

For 4K output at volume, GPT-image-2's flat pricing becomes the clear cost leader. For photorealistic quality at 1K or 2K, Nano Banana Pro produces the strongest results for product photography use cases.

All pricing is in USD. Usage is billed per image generated, not per API call, so a request with n: 4 costs 4× the per-image rate.


FAQ

Can I generate images without hardcoding the API key?
Yes — load it from os.environ["GENRELAY_API_KEY"] or a secrets manager like AWS Secrets Manager or HashiCorp Vault. Never commit API keys to version control.

What's the rate limit for image generation requests?
Rate limits depend on your plan tier. On the $14/mo plan, concurrent requests are supported. If you hit a 429 response, implement exponential backoff starting at 1–2 seconds and increase on each retry.

How long do generated image URLs stay valid?
Generated image URLs are valid for 24 hours. For long-term storage, download the image immediately after generation and upload it to your own storage (S3, Cloudflare R2, or similar).

Does GPT-image-2 support inpainting and image editing?
Yes. GPT-image-2 supports edit operations via POST /v1/images/edits. You pass the source image and a mask; the model fills the masked region based on your prompt. The request uses multipart form data rather than JSON — see the GPT-image-2 model page for the full request format.

Can I generate images in the same request as text (multimodal)?
Not through the image generation endpoint. Image and text generation use separate endpoints. Use POST /v1/images/generations for images and POST /v1/chat/completions for text.

Is Nano Banana 2 meaningfully slower than Nano Banana Pro?
In practice, Nano Banana 2 has similar latency to Nano Banana Pro at 1K resolution. The hd quality option on Nano Banana Pro adds roughly 30–40% to generation time compared to standard.


The integration path is straightforward: one endpoint, three models, one auth header. Once you have the basic request working, the main decisions are model selection and resolution — which the cost table above should make clear for your workload. For high-volume pipelines, read the batch image generation guide for concurrency patterns and retry logic at scale.

Related posts

Join our DiscordHow to Generate Images with API — Step-by-Step Guide (2026) — GenRelay