To generate an image from code, you can call OpenAI directly or connect an MCP client to Oakgen’s developer interface. The OpenAI examples below use its Images API. With Oakgen, check that GPT Image 2 is available to your account and quote the exact settings against your shared credit balance.
Option 1 — OpenAI Images API direct
Requires an OpenAI API key with billing enabled. The call is synchronous — you wait for the HTTP response and get a URL or base64 payload back. Approximate OpenAI pay-per-image cost for gpt-image-2 runs $0.02–$0.19 depending on quality and size tier.
Node (fetch)
// pseudocode — confirm final field names against OpenAI's reference
const res = await fetch("https://api.openai.com/v1/images/generations", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-image-2",
prompt: "A brass astrolabe on a walnut desk, soft window light",
size: "1024x1024",
quality: "high",
n: 1,
}),
});
if (!res.ok) {
const err = await res.text();
throw new Error(`OpenAI ${res.status}: ${err}`);
}
const { data } = await res.json();
const url = data[0].url; // or data[0].b64_json
Python (openai SDK)
from openai import OpenAI
client = OpenAI()
result = client.images.generate(
model="gpt-image-2",
prompt="A brass astrolabe on a walnut desk, soft window light",
size="1024x1024",
quality="high",
n=1,
)
url = result.data[0].url
Launch week (April 21–28, 2026) has seen frequent 429s on OpenAI direct — especially for Tier 1 and Tier 2 accounts. Build retry-with-backoff from day one, or front the call with a provider that already does it.
Pros: one less layer, direct billing relationship, latest features first. Cons: no failover, no built-in storage, synchronous (your request holds the connection), per-account tier limits.
Option 2 — Quote and generate with Oakgen MCP
Connect your MCP client to https://oakgen.ai/api/mcp with a Personal API key from the MCP console or a supported OAuth connection. MCP uses the same account and credit balance as the studio. The regional pricing page lists the available plans and their monthly credit grants.
- Call
search_modelsto find GPT Image 2. Read its current inputs withget_model_schema. - Call
get_pricingwith the image settings you intend to send. Check the quoted credits against your budget. - Call
start_generationwith the approved settings, amaxCreditsceiling and anidempotencyKey. Reuse that key only when retrying the same request. - Poll
get_generation_statuswith the returned generation ID to retrieve the result and its assets.
The developer guide lists authentication scopes, request limits and cancellation behavior.
When to pick each
| Situation | Pick |
|---|---|
| Building one tool, GPT Image 2 only, occasional use | OpenAI direct |
| Multi-model studio or pipeline | Oakgen |
| Want predictable usage-based credits | Oakgen |
| Need images stored and served without setup | Oakgen |
| Already on a high OpenAI tier with retry infra | OpenAI direct |
If you're evaluating models alongside the API choice, our GPT Image 2 vs Nano Banana Pro breakdown covers the quality and latency tradeoffs.
Sample Next.js route for OpenAI direct
// app/api/image/route.ts
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const { prompt } = await req.json();
const openaiRes = await fetch("https://api.openai.com/v1/images/generations", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-image-2",
prompt,
size: "1024x1024",
quality: "high",
n: 1,
}),
});
if (!openaiRes.ok) {
return NextResponse.json(
{ error: await openaiRes.text() },
{ status: openaiRes.status },
);
}
const { data } = await openaiRes.json();
return NextResponse.json({ url: data[0].url });
}
Caller blocks on the response. On a cold Tier 1 key during launch week, expect 15–40s P95 and occasional 429s.
Error handling patterns
Rate-limit retry with exponential backoff
async function withRetry<T>(fn: () => Promise<Response>, max = 5): Promise<T> {
let attempt = 0;
while (true) {
const res = await fn();
if (res.ok) return res.json();
if (res.status !== 429 && res.status < 500) {
throw new Error(`${res.status}: ${await res.text()}`);
}
if (attempt >= max) throw new Error(`max retries: ${res.status}`);
const retryAfter = Number(res.headers.get("retry-after"));
const delay = retryAfter ? retryAfter * 1000 : 2 ** attempt * 500;
await new Promise((r) => setTimeout(r, delay));
attempt++;
}
}
Use this around OpenAI direct calls. For Oakgen, keep the generation ID returned by MCP so you can check an existing job after a connection failure.
Timeout handling
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 60_000);
try {
const res = await fetch(url, { signal: controller.signal, ... });
// ...
} finally {
clearTimeout(timeout);
}
An HTTP timeout can end the client’s wait before a generation is finished. Check an existing Oakgen generation by ID before submitting again.
Rate limits and quotas
OpenAI direct uses a tier system (Tier 1 → Tier 5) scaling with cumulative spend. Image generation limits are separate from chat and apply per-minute and per-day. Launch week has seen Tier 1 accounts hit ceilings inside 10 minutes of heavy usage.
Oakgen meters generations in credits and enforces request limits. Check model access on the regional pricing page and get a quote for your exact settings before starting a job.
Both providers return 429 Too Many Requests with a Retry-After header when you hit a limit. Respect it.
Authentication
OpenAI
- Create a key at
platform.openai.com/api-keys. - Add billing.
- Set
OPENAI_API_KEYin your env. Never ship it to the browser.
Oakgen
- Check your model access and monthly credits on the pricing page.
- Create a Personal API key in the MCP console.
- Connect your client to the MCP endpoint using the key as a bearer token. The developer guide lists the available tools for quoting, starting and monitoring a generation.
Both keys are Bearer tokens. Both should be server-side only.
Migrating from DALL·E 3 or GPT Image 1
It's mostly a drop-in swap on OpenAI direct — change model: "dall-e-3" (or "gpt-image-1") to model: "gpt-image-2".
Notable differences:
- Quality parameter: GPT Image 2 exposes more quality tiers than DALL·E 3. Old
"standard"/"hd"still accepted; new high tiers cost more. - Size: square and wide-aspect ratios largely match. Confirm the exact enum against the current reference.
- Response shape: unchanged —
data[].urlordata[].b64_json. Existing clients that parse DALL·E 3 responses generally keep working. - Moderation: tightened in a few categories. If you relied on edge-case outputs from GPT Image 1, test them before shipping.
When changing models on Oakgen, inspect the new model’s schema and request a fresh credit quote before you generate.
FAQ
Is GPT Image 2 available via API?
Yes. OpenAI exposes it on the Images API (model: "gpt-image-2"). For Oakgen, check the model list returned by your MCP connection. Use its model ID and schema to quote and start the job.
What's the rate limit? OpenAI: tier-based, scales with spend, separate ceilings per-minute and per-day. Oakgen enforces request limits and meters generations in credits.
Can I batch generate?
OpenAI supports n up to a provider-capped value per request — check the current ref. Each Oakgen MCP generation has its own handle. Check its status using the tools listed in the developer guide.
Does Oakgen support streaming? An MCP generation returns a handle. Check its status and retrieve the image once it completes.
Are images stored? On Oakgen, the completed generation’s status includes its output assets. On OpenAI direct, the returned URL is ephemeral (minutes, not days) — you must download and re-host.
Do failed generations cost credits? If an Oakgen generation fails, the job’s deducted credits are refunded. Check its status before retrying.
Running a dev shop or agency? The referral program explains which subscription payments earn a commission and how to get a referral link.
Plan your first image API request
Identify the input, output format and status checks for a small test before scaling up.



