Image generation
This guide covers the image generation workflow and common tasks. For every parameter value, limit and error code, see the API reference.
1. Prepare your key
Create an API key in the console, confirm it can call the model, and keep it on your server. The examples read the URL and key from environment variables.
export IMAGE_API_BASE="https://ling-light.com"
export IMAGE_API_KEY="sk-your-api-key"2. Choose a model and endpoint
Image models come in two series, GPT Image and Seedream, which take reference images differently. Find the endpoint for your task:
| Task | GPT Image | Seedream |
|---|---|---|
| Text to image | POST /v1/images/generations | POST /v1/images/generations |
| Use reference images | POST /v1/images/edits with images | POST /v1/images/generations with image |
| Long runs or safe retries | POST /v1/images/tasks | POST /v1/images/tasks |
3. Generate an image
Synchronous endpoints generate and return the image in one HTTP request, with no polling. Generation can take from tens of seconds to minutes, so the examples use a 240-second client timeout. Do not resend automatically after a timeout, or you may be charged twice.
GPT Image text to image
curl --fail-with-body --max-time 240 \
--request POST "$IMAGE_API_BASE/v1/images/generations" \
--header "Authorization: Bearer $IMAGE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "gpt-image-2.6",
"n": 1,
"prompt": "Create a landscape watercolor illustration of a seated orange cat in soft light, with no text.",
"size": "1536x1024"
}' \
--output image-response.jsonimport { writeFile } from 'node:fs/promises'
const baseUrl = process.env.IMAGE_API_BASE
const apiKey = process.env.IMAGE_API_KEY
if (!baseUrl || !apiKey) throw new Error('Set IMAGE_API_BASE and IMAGE_API_KEY first')
const response = await fetch(new URL('/v1/images/generations', baseUrl), {
method: 'POST',
redirect: 'error',
signal: AbortSignal.timeout(240_000),
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"model": "gpt-image-2.6",
"n": 1,
"prompt": "Create a landscape watercolor illustration of a seated orange cat in soft light, with no text.",
"size": "1536x1024"
}),
})
const result = await response.json().catch(() => null)
const rayId = response.headers.get('cf-ray')
const status = 'HTTP ' + response.status + (rayId ? ' · CF-Ray ' + rayId : '')
if (!response.ok || result?.error) {
const fallback = response.status === 524
? 'Cloudflare timed out waiting for the origin. Check usage logs before retrying.'
: "Image generation failed"
throw new Error(status + ' · ' + (result?.error?.message || result?.message || fallback))
}
if (!result) throw new Error(status + ' · Expected a JSON response')
const image = result.data?.[0]
if (!image?.url && !image?.b64_json) throw new Error('No image data returned; inspect the response')
await writeFile('image-response.json', JSON.stringify(result, null, 2))
console.log(image.url || 'Saved base64 image data in image-response.json')Seedream with a reference image
Replace the image URL with a public HTTPS image or asset://<asset ID> from your asset library.
curl --fail-with-body --max-time 240 \
--request POST "$IMAGE_API_BASE/v1/images/generations" \
--header "Authorization: Bearer $IMAGE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "seedream-5.5",
"prompt": "Keep the vase and flowers from the reference and create a 9:16 portrait watercolor with an opaque light beige background.",
"image": [
"https://media.example.com/images/reference.png"
],
"size": "2K",
"n": 1,
"background": "opaque",
"output_format": "png",
"watermark": true
}' \
--output image-response.jsonimport { writeFile } from 'node:fs/promises'
const baseUrl = process.env.IMAGE_API_BASE
const apiKey = process.env.IMAGE_API_KEY
if (!baseUrl || !apiKey) throw new Error('Set IMAGE_API_BASE and IMAGE_API_KEY first')
const response = await fetch(new URL('/v1/images/generations', baseUrl), {
method: 'POST',
redirect: 'error',
signal: AbortSignal.timeout(240_000),
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"model": "seedream-5.5",
"prompt": "Keep the vase and flowers from the reference and create a 9:16 portrait watercolor with an opaque light beige background.",
"image": [
"https://media.example.com/images/reference.png"
],
"size": "2K",
"n": 1,
"background": "opaque",
"output_format": "png",
"watermark": true
}),
})
const result = await response.json().catch(() => null)
const rayId = response.headers.get('cf-ray')
const status = 'HTTP ' + response.status + (rayId ? ' · CF-Ray ' + rayId : '')
if (!response.ok || result?.error) {
const fallback = response.status === 524
? 'Cloudflare timed out waiting for the origin. Check usage logs before retrying.'
: "Image generation failed"
throw new Error(status + ' · ' + (result?.error?.message || result?.message || fallback))
}
if (!result) throw new Error(status + ' · Expected a JSON response')
const image = result.data?.[0]
if (!image?.url && !image?.b64_json) throw new Error('No image data returned; inspect the response')
await writeFile('image-response.json', JSON.stringify(result, null, 2))
console.log(image.url || 'Saved base64 image data in image-response.json'){
"created": 1795446925,
"data": [
{
"url": "https://media.example.com/images/example.png",
"width": 1024,
"height": 1024
}
]
}4. Edit with GPT Image
GPT Image takes reference images on POST /v1/images/edits in the images array; describe what to change and keep in prompt. Seedream does not use this endpoint.
curl --fail-with-body --max-time 300 \
--request POST "$IMAGE_API_BASE/v1/images/edits" \
--header "Authorization: Bearer $IMAGE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "gpt-image-2.6",
"prompt": "Preserve the subject and composition of the reference image and repaint it as a watercolor.",
"images": [
{
"image_url": "https://media.example.com/images/reference.png"
}
],
"n": 1,
"size": "1024x1024"
}' \
--output image-edit-result.jsonimport { writeFile } from 'node:fs/promises'
const baseUrl = process.env.IMAGE_API_BASE
const apiKey = process.env.IMAGE_API_KEY
if (!baseUrl || !apiKey) throw new Error('Set IMAGE_API_BASE and IMAGE_API_KEY first')
const response = await fetch(new URL('/v1/images/edits', baseUrl), {
method: 'POST',
redirect: 'error',
signal: AbortSignal.timeout(300_000),
headers: {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"model": "gpt-image-2.6",
"prompt": "Preserve the subject and composition of the reference image and repaint it as a watercolor.",
"images": [
{
"image_url": "https://media.example.com/images/reference.png"
}
],
"n": 1,
"size": "1024x1024"
}),
})
const result = await response.json().catch(() => null)
const rayId = response.headers.get('cf-ray')
const status = 'HTTP ' + response.status + (rayId ? ' · CF-Ray ' + rayId : '')
if (!response.ok || result?.error) {
const fallback = response.status === 524
? 'Cloudflare timed out waiting for the origin. Check usage logs before retrying.'
: "Image editing failed"
throw new Error(status + ' · ' + (result?.error?.message || result?.message || fallback))
}
if (!result) throw new Error(status + ' · Expected a JSON response')
await writeFile('image-edit-result.json', JSON.stringify(result, null, 2))
console.log(result.data?.[0]?.url || 'Saved the response in image-edit-result.json')5. Save the image
Each data entry is one image: download url (without your API key), or decode b64_json. Links may expire, so save images to your own storage promptly.
# Replace this with data[0].url from image-response.json.
export IMAGE_URL="https://media.example.com/images/example.png"
curl --fail --location --proto '=https' --proto-redir '=https' \
--max-time 60 "$IMAGE_URL" --output image.pngimport { readFile, writeFile } from 'node:fs/promises'
const result = JSON.parse(await readFile('image-response.json', 'utf8'))
const item = result.data?.[0]
if (item?.b64_json) {
await writeFile('image.png', Buffer.from(item.b64_json, 'base64'))
} else {
if (!item?.url) throw new Error('No image in the saved response')
const response = await fetch(item.url, { signal: AbortSignal.timeout(60_000) })
if (!response.ok) throw new Error(`Image download failed: HTTP ${response.status}`)
await writeFile('image.png', Buffer.from(await response.arrayBuffer()))
}
console.log('Saved image.png')6. Asynchronous image tasks
For long runs, unreliable networks or safe retries, use POST /v1/images/tasks. The body matches the synchronous endpoints plus an Idempotency-Key header: retrying with the same key and body returns the original task instead of generating again. Poll GET /v1/tasks/{id}; once SUCCESS, get image URLs from GET /v1/tasks/{id}/artifacts (valid for 15 minutes; fetch again for fresh links).
# Replace image-order-001 with your request ID and reuse it on retry.
curl --fail-with-body -X POST "$IMAGE_API_BASE/v1/images/tasks" \
-H "Authorization: Bearer $IMAGE_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: image-order-001" \
-d '{"model":"gpt-image-2.6","prompt":"A cat in a garden","size":"1024x1024"}'
# Set TASK_ID to the task_id from the response.
curl --fail-with-body "$IMAGE_API_BASE/v1/tasks/$TASK_ID" \
-H "Authorization: Bearer $IMAGE_API_KEY"
# Read artifacts when status is SUCCESS.
curl --fail-with-body "$IMAGE_API_BASE/v1/tasks/$TASK_ID/artifacts" \
-H "Authorization: Bearer $IMAGE_API_KEY"const base = process.env.IMAGE_API_BASE
const apiKey = process.env.IMAGE_API_KEY
const key = process.env.IMAGE_REQUEST_ID
if (!base || !apiKey || !key) throw new Error('Set IMAGE_API_BASE, IMAGE_API_KEY and IMAGE_REQUEST_ID')
const headers = { Authorization: `Bearer ${apiKey}` }
const submission = await fetch(new URL('/v1/images/tasks', base), {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json', 'Idempotency-Key': key },
body: JSON.stringify({ model: 'gpt-image-2.6', prompt: 'A cat in a garden', size: '1024x1024' }),
})
if (!submission.ok) throw new Error(await submission.text())
const { task_id } = await submission.json()
let task
do {
await new Promise((resolve) => setTimeout(resolve, 4000))
const status = await fetch(new URL(`/v1/tasks/${task_id}`, base), { headers })
if (!status.ok) throw new Error(await status.text())
task = await status.json()
} while (task.status !== 'SUCCESS' && task.status !== 'FAILURE')
if (task.status === 'FAILURE') throw new Error(task.fail_reason || 'Image task failed')
const artifacts = await fetch(new URL(`/v1/tasks/${task_id}/artifacts`, base), { headers })
console.log(await artifacts.json())Errors and retries
- On failure, read error.message and fix the parameters, model access or quota; error codes are listed in the API reference.
- After a synchronous timeout, disconnect or 5xx (including a Cloudflare 524 page), the image may already be generated and billed. Check usage logs before retrying.
- Use asynchronous image tasks with an Idempotency-Key when you need automatic retries.