Generation APIs/Images

Generate Images

POST

Overview

Submit a unified image generation task through API Mall. This endpoint wraps the supported image providers behind a single contract, so callers only need to choose the model, set the task type, and provide the input fields required by that model.

Authentication

All API requests require a Bearer token in the request header.

Authorization: Bearer YOUR_API_KEY

Create and manage API keys from API Keys or use https://www.apimall.ai/api-keys.

1. Create Generation Task

API Information

  • URL: POST https://gateway.apimall.ai/api/v1/images/generate
  • Content-Type: application/json

Request Parameters

ParameterTypeRequiredDescription
model
string
z-imagezimagenano-banana
Required

Model identifier for this endpoint.

Default: nano-banana

type
string
text-to-imageimage-to-imageupscale
Optional

Task mode for the selected model.

Default: text-to-image

prompt
stringRequired

Prompt or edit instruction for the generation task.

input_image
stringOptional

Single reference image URL. When provided without `type`, the API usually infers `image-to-image`.

image_urls
arrayOptional

Reference image URLs for edit, upscale, or multi-image workflows.

num_images
integerOptional

Number of output images to generate.

Default: 1

Range: 1 - 6

image_size
stringOptional

Requested output size or provider-specific size preset.

image_resolution
stringOptional

Output resolution tier combined with `image_size` to determine final pixel dimensions.

aspect_ratio
stringOptional

Target aspect ratio when supported by the selected model.

resolution
string
1K2K4K
Optional

Nano Banana 2 output resolution tier.

seed
integerOptional

Optional random seed for deterministic providers.

quality
string
lowmediumhigh
Optional

Quality tier used by GPT Image 1.5.

background
string
autotransparentopaque
Optional

Background rendering mode for GPT Image 1.5.

output_format
string
jpegjpgpng
Optional

Requested output image format.

google_search
booleanOptional

Enable Google Search grounding for prompts that depend on current real-world information.

task_id
stringOptional

Source task ID used by task-based image tools such as upscaling.

source_task_id
stringOptional

Alias for source task references on some models.

origin_task_id
stringOptional

Original task ID for provider workflows that need a prior generation reference.

scale
integerOptional

Upscale factor for upscaler models.

Range: 1 - 4

face_enhance
booleanOptional

Enable face enhancement during upscaling when supported.

Request Example

{
  "model": "nano-banana",
  "type": "text-to-image",
  "prompt": "A cinematic portrait of a cyberpunk fox in neon rain.",
  "num_images": 1,
  "aspect_ratio": "1:1",
  "output_format": "png"
}

Response Example

{
  "success": true,
  "data": {
    "task_id": "img_01HQ9M7XJQ7PZ3GQ9F6C5W3N2M",
    "request_id": "provider_req_01HQ9M87A5Y2QZW0S1R3T6YQ2C",
    "credits_used": 8,
    "remaining_credits": 112,
    "model": "nano-banana"
  },
  "request_id": "req_01HQ9M7J7X9P7Y8T6W5V4U3S2R"
}

cURL Example

curl --request POST 'https://gateway.apimall.ai/api/v1/images/generate' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
  "model": "nano-banana",
  "type": "text-to-image",
  "prompt": "A cinematic portrait of a cyberpunk fox in neon rain.",
  "num_images": 1,
  "aspect_ratio": "1:1",
  "output_format": "png"
}'

JavaScript Example

const API_KEY = process.env.APIMALL_API_KEY;
const CREATE_URL = 'https://gateway.apimall.ai/api/v1/images/generate';

const payload = {
  "model": "nano-banana",
  "type": "text-to-image",
  "prompt": "A cinematic portrait of a cyberpunk fox in neon rain.",
  "num_images": 1,
  "aspect_ratio": "1:1",
  "output_format": "png"
};

async function createTask() {
  const response = await fetch(CREATE_URL, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
  });

  if (!response.ok) {
    throw new Error(`Create task failed: ${response.status} ${response.statusText}`);
  }

  const json = await response.json();
  const taskId = json.data?.task_id;

  if (!taskId) {
    throw new Error('Missing task_id in create response');
  }

  return taskId;
}

async function getTask(taskId) {
  const response = await fetch(`https://gateway.apimall.ai/api/v1/images/${encodeURIComponent(String(taskId))}`, {
    headers: {
      Authorization: `Bearer ${API_KEY}`,
    },
  });

  if (!response.ok) {
    throw new Error(`Query task failed: ${response.status} ${response.statusText}`);
  }

  const json = await response.json();
  return {
    ...json,
  };
}

async function waitForTask(taskId) {
  while (true) {
    const task = await getTask(taskId);
    const state = task.data?.status;

    if (state === 'completed') {
      return task;
    }

    if (state === 'failed') {
      throw new Error(task.data?.failMsg || 'Task failed');
    }

    await new Promise((resolve) => setTimeout(resolve, 3000));
  }
}

(async () => {
  const taskId = await createTask();
  const result = await waitForTask(taskId);
  console.log(result);
})().catch(console.error);

Response Parameters

ParameterTypeDescription
success
boolean

Whether the request completed successfully.

data.task_id
string

Task ID used to query task status and results.

data.request_id
string

Provider-side request identifier for tracing.

data.credits_used
integer

Credits consumed by this request.

data.remaining_credits
integer

Credits remaining after the request.

data.model
string

Model name used for the task.

request_id
string

Request identifier for debugging and support.

Error Response Example

{
  "success": false,
  "error": {
    "code": "insufficient_credits",
    "message": "Insufficient credits"
  },
  "request_id": "req_01HQ9M7J7X9P7Y8T6W5V4U3S2R"
}

2. Query Task Status

API Information

  • URL: GET https://gateway.apimall.ai/api/v1/images/{task_id}

Path Parameters

ParameterTypeRequiredDescription
task_id
stringRequired

Image task identifier returned by `POST /api/v1/images/generate`.

Request Example

GET https://gateway.apimall.ai/api/v1/images/img_01HQ9M7XJQ7PZ3GQ9F6C5W3N2M

cURL Example

curl --request GET 'https://gateway.apimall.ai/api/v1/images/img_01HQ9M7XJQ7PZ3GQ9F6C5W3N2M' \
  --header 'Authorization: Bearer YOUR_API_KEY'

Response Example

{
  "success": true,
  "data": {
    "task_id": "img_01HQ9M7XJQ7PZ3GQ9F6C5W3N2M",
    "model": "nano-banana",
    "status": "completed",
    "output": {
      "resultUrls": [
        "https://cdn.apimall.ai/generated/image-01.webp"
      ]
    },
    "primary_url": "https://cdn.apimall.ai/generated/result.webp",
    "image_url": "https://cdn.apimall.ai/generated/cover.webp",
    "error_message": null,
    "credits_used": 8,
    "credits_refunded": 0,
    "created_at": "2026-03-12T09:30:00.000Z",
    "updated_at": "2026-03-12T09:31:06.000Z",
    "completed_at": "2026-03-12T09:31:06.000Z"
  },
  "request_id": "req_01HQ9M7J7X9P7Y8T6W5V4U3S2R"
}

Response Parameters

ParameterTypeDescription
success
boolean

Whether the request completed successfully.

data.task_id
string

Task ID used to query task status and results.

data.model
string

Model name used for the task.

data.status
string

Current status value returned by the API. Generation task endpoints use normalized values such as `pending`, `processing`, `completed`, `failed`, or `unknown`; management endpoints may return resource states such as `created`, `revoked`, or `active`.

data.output.resultUrls
array

Generated result URLs returned by the upstream provider payload.

data.primary_url
string

Primary hosted image URL for image tasks.

data.image_url
string

Hosted image result URL.

data.error_message
string

Failure reason returned when the music task does not complete successfully.

data.credits_used
integer

Credits consumed by this request.

data.credits_refunded
integer

Credits refunded after failure or partial refund handling.

data.created_at
string

Creation timestamp for the returned resource or task record.

data.updated_at
string

Last update timestamp for the returned resource or task record.

data.completed_at
string

Completion timestamp for the task when available.

request_id
string

Request identifier for debugging and support.

Usage Flow

  1. Create a generation task by calling `POST https://gateway.apimall.ai/api/v1/images/generate`.
  2. Persist `data.task_id` from the create response so you can resume polling later.
  3. Poll `GET https://gateway.apimall.ai/api/v1/images/{task_id}` until `data.status` reaches `completed` or `failed`.
  4. Read the generated image URLs from the final task payload.

Integration Notes

  • Store your API key on the server side only.
  • Persist the returned `data.task_id` immediately so you can resume polling after restarts.
  • Use an `Idempotency-Key` header when retrying create requests from your backend.
  • Poll the task endpoint every few seconds with backoff until `data.status` reaches `completed` or `failed`.
  • Use `data.primary_url` or `data.image_url` as the final hosted asset URL.

Error Codes

Common Error Codes

Status CodeDescription
200Request successful
400Invalid request parameters
401API key required or invalid API key
402Insufficient credits
403API access not approved or request made on a non-gateway host
409Idempotency-Key conflict
429Rate limit exceeded or too many concurrent jobs
503Upstream provider is busy or temporarily unavailable
451Prompt blocked by content moderation
500Internal server error
Generate Images - API Reference | API Mall | API Mall