GPT-Image-2 API Guide: Generate & Edit Images in 2026

Aug 8, 2026·6 min read

You've built a feature that generates product mockups on demand. Your users hit "Generate" and expect a result in under ten seconds. The image quality needs to be good enough that the output doesn't embarrass your product. That's exactly the use case GPT-image-2 was designed for — and via GenRelay you can call it with a single API key, no separate OpenAI account provisioning required.

This guide covers everything you need to go from zero to a working integration: authentication, request format, all key parameters, how to handle the response, pricing math, and a few gotchas worth knowing before you ship.


What Is GPT-image-2?

GPT-image-2 is OpenAI's image generation model, positioned as a higher-throughput, more instruction-following upgrade over DALL·E 3. It accepts a natural-language prompt and returns a base64-encoded PNG or a hosted image URL. It supports native image editing (inpainting via a mask) in addition to text-to-image generation, which makes it useful beyond simple generation tasks.

GenRelay exposes GPT-image-2 through a unified endpoint alongside other image and video models. One API key, one base URL, same auth pattern regardless of which model you call.


How Do I Authenticate with the GenRelay API?

Every request uses a Bearer token in the Authorization header. Generate your key in the GenRelay console, then treat it like any secret — environment variable, not hardcoded.

curl https://genrelay.ai/v1/images/generations \
  -H "Authorization: Bearer $GENRELAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "A minimalist product shot of wireless headphones on a white surface, studio lighting",
    "n": 1,
    "size": "1024x1024"
  }'

The endpoint is /v1/images/generations — same path structure as the OpenAI API, so if you already have OpenAI SDK code, you can point it at https://genrelay.ai by changing the base URL only.


What Parameters Does GPT-image-2 Accept?

The table below covers the parameters you'll use most often.

Parameter Type Default Notes
model string "gpt-image-2"
prompt string Required. Up to 4,000 chars.
n integer 1 Number of images. 1–4.
size string "1024x1024" "1024x1024" | "1792x1024" | "1024x1792"
quality string "standard" "standard" | "hd"
response_format string "url" "url" | "b64_json"
style string "vivid" "vivid" (dramatic) | "natural" (realistic)

quality: "hd" runs a second diffusion pass for finer detail. Use it for hero images; skip it for thumbnails or previews.

style is the most overlooked parameter. "vivid" tends toward saturated, cinematic results. "natural" produces more muted, photograph-like output. For product shots, "natural" usually wins.


How Do I Call GPT-image-2 from Python?

Here's a minimal working example using requests. No SDK required.

import os
import requests
import base64
from pathlib import Path

GENRELAY_API_KEY = os.environ["GENRELAY_API_KEY"]

def generate_image(prompt: str, output_path: str = "output.png") -> str:
    resp = requests.post(
        "https://genrelay.ai/v1/images/generations",
        headers={
            "Authorization": f"Bearer {GENRELAY_API_KEY}",
            "Content-Type": "application/json",
        },
        json={
            "model": "gpt-image-2",
            "prompt": prompt,
            "n": 1,
            "size": "1024x1024",
            "quality": "standard",
            "style": "natural",
            "response_format": "b64_json",
        },
        timeout=60,
    )
    resp.raise_for_status()

    data = resp.json()["data"][0]["b64_json"]
    Path(output_path).write_bytes(base64.b64decode(data))
    print(f"Saved to {output_path}")
    return output_path

generate_image("Flat-lay of a leather wallet and keys on dark wood, soft shadow")

Using response_format: "b64_json" means you get the image directly in the response body — no second request to download a URL. For server-side generation where you're writing to S3 or a CDN anyway, this is cleaner.


How Do I Use GPT-image-2 for Image Editing (Inpainting)?

GPT-image-2 supports editing an existing image with a text prompt and an optional mask. The mask is a grayscale PNG where white areas are replaced and black areas are preserved.

import os
import requests

GENRELAY_API_KEY = os.environ["GENRELAY_API_KEY"]

def edit_image(image_path: str, mask_path: str, prompt: str) -> dict:
    with open(image_path, "rb") as img, open(mask_path, "rb") as msk:
        resp = requests.post(
            "https://genrelay.ai/v1/images/edits",
            headers={"Authorization": f"Bearer {GENRELAY_API_KEY}"},
            data={
                "model": "gpt-image-2",
                "prompt": prompt,
                "n": "1",
                "size": "1024x1024",
            },
            files={
                "image": ("image.png", img, "image/png"),
                "mask": ("mask.png", msk, "image/png"),
            },
            timeout=90,
        )
    resp.raise_for_status()
    return resp.json()

result = edit_image(
    image_path="product.png",
    mask_path="background_mask.png",
    prompt="Replace the background with a clean white studio backdrop",
)
print(result["data"][0]["url"])

For editing, use multipart form data (files=), not JSON. The image and mask must both be square PNG files at the same resolution. Common mistake: sending a JPEG image — it will return a 400 error.


What Does GPT-image-2 Cost via GenRelay?

As of August 2026, GPT-image-2 pricing on GenRelay is $0.014 per image at standard 1024×1024 resolution.

To put that in context for a real workload:

Workload Images Cost
100 product images/day 3,000/month $42/month
User-facing generator (500 DAU × 5 images) 75,000/month $1,050/month
Background processing (batch thumbnails) 10,000/month $140/month

For comparison, Nano Banana Pro costs $0.030 per image at 1K resolution — more than twice the price but with higher output resolution and different stylistic defaults. If you need photorealistic product shots, GPT-image-2 at $0.014 is the more cost-efficient choice. If you need illustration-style or higher-fidelity detail at 4K, Nano Banana Pro is worth the premium. See the Nano Banana Pro API guide for a deeper comparison.

GenRelay's free tier includes credits to test both models without entering a card.


FAQ

Does GPT-image-2 support batch generation?
Yes — set n to 2, 3, or 4 in a single request. All images are returned in the same response. For larger batches, send parallel requests; GPT-image-2 has no enforced concurrency limit at the GenRelay tier.

What's the rate limit?
GenRelay's image generation endpoint handles burst traffic well for typical SaaS workloads. If you're running high-volume batch jobs (thousands of images per hour), reach out via the console to discuss higher-throughput configurations.

Can I use GPT-image-2 output commercially?
Yes. GenRelay's terms permit commercial use of generated images. You own the output.

Does it support transparent backgrounds?
GPT-image-2 does not natively output RGBA PNGs with transparency. Post-process with a background removal tool (e.g. rembg) if you need cutouts.

What languages does GPT-image-2 understand in prompts?
The model handles English prompts most reliably. For non-English languages, translation to English before sending the prompt tends to produce better results.

How long does a generation take?
Standard quality at 1024×1024 typically returns in 8–15 seconds. HD quality adds another 5–10 seconds on average. Build your UI around a 20-second p95 latency budget.


Self-Check Before You Ship

Before going live, verify:

  • API key is loaded from an environment variable, never hardcoded in source
  • You handle resp.raise_for_status() and surface meaningful errors to users (content policy refusals return a 400 with a specific error code)
  • For image editing, confirm inputs are square PNGs at matching resolution
  • Timeout set to at least 60 seconds (90 for HD or edits)
  • Cost tracking in place — at $0.014/image, a runaway loop generating thousands of images is a real risk

The GenRelay console shows per-model usage and spend in real time, which helps catch runaway jobs early.

Related posts

Join our DiscordGPT-Image-2 API Guide: Generate & Edit Images in 2026 — GenRelay