# How to Use the Asynchronous Image Task Endpoints in Sub2API: Complete REST API Reference

> Discover Sub2API's asynchronous image task endpoints. Learn how to manage batch image generation and retrieve results using the /v1/images/batches REST API.

- Repository: [Wesley Liddick/sub2api](https://github.com/Wei-Shaw/sub2api)
- Tags: api-reference
- Published: 2026-08-23

---

**Sub2API exposes nine REST endpoints under the `/v1/images/batches` path that enable asynchronous batch image generation, job lifecycle management, and result retrieval, all authenticated via bearer tokens and wrapped by typed client functions in [`frontend/src/api/batchImage.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/batchImage.ts).**

The Wei-Shaw/sub2api repository implements a scalable asynchronous image generation pipeline designed for high-volume processing. All endpoints for asynchronous image tasks in Sub2API route through a central gateway URL—constructed by the `buildGatewayUrl` utility—and operate under the shared `/v1/images/batches` prefix, with the client library handling authentication headers automatically.

## Overview of Asynchronous Image Endpoints

Sub2API treats batch image generation as a first-class async workflow. Each operation corresponds to a specific HTTP method and path relative to the gateway base URL. The TypeScript client implementation in [`frontend/src/api/batchImage.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/batchImage.ts) provides strongly-typed wrappers that inject the required `Authorization: Bearer` headers via the `authHeaders` helper (lines 30‑35) and manage the Axios instance defined in [`frontend/src/api/client.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/client.ts).

The following table maps each async operation to its HTTP signature and client function:

| Operation | Method | Endpoint Path | Client Function (batchImage.ts) |
|-----------|--------|---------------|----------------------------------|
| Submit batch job | `POST` | `/v1/images/batches` | `submitBatchImageJob` (L37) |
| Get job details | `GET` | `/v1/images/batches/{batchId}` | `getBatchImageJob` (L54) |
| List jobs | `GET` | `/v1/images/batches` | `listBatchImageJobs` (L62) |
| List models | `GET` | `/v1/images/batches/models` | `listBatchImageModels` (L82) |
| List job items | `GET` | `/v1/images/batches/{batchId}/items` | `listBatchImageItems` (L90) |
| Cancel job | `POST` | `/v1/images/batches/{batchId}/cancel` | `cancelBatchImageJob` (L102) |
| Download ZIP | `GET` | `/v1/images/batches/{batchId}/download` | `downloadBatchImageZip` (L112) |
| Get item content | `GET` | `/v1/images/batches/{batchId}/items/{customId}/content` | `getBatchImageItemContent` (L121) |
| Delete job | `DELETE` | `/v1/images/batches/{batchId}` | `deleteBatchImageJobRecord` (L130) |

All paths are relative to the gateway URL built by `buildGatewayUrl` in [`frontend/src/api/url.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/url.ts).

## Creating and Managing Batch Jobs

### Submit a New Batch Image Job

To initiate an asynchronous batch, send a `POST` request to `/v1/images/batches`. The `submitBatchImageJob` function at line 37 of [`frontend/src/api/batchImage.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/batchImage.ts) constructs this request, requiring an API key, a payload specifying the model and prompt items, and an idempotency key to prevent duplicate submissions.

```typescript
import { submitBatchImageJob } from '@/api/batchImage';

const job = await submitBatchImageJob(
  process.env.SUB2API_KEY,
  {
    model: 'flash-3b',
    items: [
      { custom_id: 'item-1', prompt: 'a sunset over mountains' },
      { custom_id: 'item-2', prompt: 'futuristic cityscape' }
    ]
  },
  crypto.randomUUID() // idempotency key
);

```

### Retrieve Job Status and Details

Poll for job metadata using `GET /v1/images/batches/{batchId}`. The `getBatchImageJob` wrapper (line 54) returns the current status, progress, and metadata without downloading actual image data.

```typescript
import { getBatchImageJob } from '@/api/batchImage';

const jobDetails = await getBatchImageJob(process.env.SUB2API_KEY, job.id);
console.log(jobDetails.status); // 'pending', 'processing', 'completed', 'failed', or 'cancelled'

```

### List All Batch Jobs

For pagination and filtering, use `GET /v1/images/batches`. The `listBatchImageJobs` function (line 62) supports query parameters for filtering by status, date ranges, or model types, returning a paginated list of job records.

### Cancel a Running Batch Job

To abort an in-progress job, call `POST /v1/images/batches/{batchId}/cancel` via the `cancelBatchImageJob` wrapper at line 102. This triggers a cancellation signal but may not immediately halt processing items already in flight.

### Delete a Job Record

Once results are downloaded and no longer needed, clean up server-side state by calling `DELETE /v1/images/batches/{batchId}` through `deleteBatchImageJobRecord` (line 130). This removes the job metadata and associated temporary storage.

### List Available Image Models

Before submitting, query supported models with `GET /v1/images/batches/models` using `listBatchImageModels` (line 82). This returns model identifiers, capabilities, and versioning information required for the submission payload.

## Retrieving Batch Results and Individual Images

### Download Complete Results as ZIP

When a job reaches `completed` status, retrieve the full result archive via `GET /v1/images/batches/{batchId}/download`. The `downloadBatchImageZip` function (line 112) returns a binary Blob containing all generated images packaged as a ZIP file.

```typescript
import { downloadBatchImageZip } from '@/api/batchImage';

const zipBlob = await downloadBatchImageZip(process.env.SUB2API_KEY, job.id);
// Handle browser download or stream to storage

```

### List Individual Items in a Batch

To inspect per-prompt status without downloading binary data, use `GET /v1/images/batches/{batchId}/items` with optional `?status=` filters. The `listBatchImageItems` wrapper (line 90) returns metadata for each item including `custom_id`, generation status, and error messages if applicable.

### Fetch Single Image Content

For granular access, retrieve specific images via `GET /v1/images/batches/{batchId}/items/{customId}/content?image_index={n}`. The `getBatchImageItemContent` function (line 121) streams the binary content of the nth image generated for a specific custom ID, useful for previewing or caching individual results before downloading the full ZIP.

## Authentication and Client Configuration

All asynchronous image endpoints require a bearer token supplied through the `authHeaders` utility. According to the source code in [`frontend/src/api/batchImage.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/batchImage.ts) lines 30‑35, this helper merges the API key into the `Authorization` header alongside locale and timezone information injected by the central Axios client in [`frontend/src/api/client.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/client.ts).

The base URL for all requests is constructed by `buildGatewayUrl` in [`frontend/src/api/url.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/url.ts), ensuring that staging, production, or custom gateway deployments use the correct endpoint roots without hardcoding URLs in the business logic.

## Complete Workflow Example

The following TypeScript example demonstrates the full lifecycle: submission, polling, and retrieval.

```typescript
import {
  submitBatchImageJob,
  getBatchImageJob,
  listBatchImageJobs,
  cancelBatchImageJob,
  downloadBatchImageZip,
  getBatchImageItemContent,
} from '@/api/batchImage'

// 1️⃣ Submit a new batch job
const job = await submitBatchImageJob(
  process.env.SUB2API_KEY,
  {
    model: 'flash-3b',
    items: [{ custom_id: 'item-1', prompt: 'a sunset over mountains' }],
  },
  crypto.randomUUID()
)

// 2️⃣ Poll for status
let status = job.status
while (!['completed', 'failed', 'cancelled'].includes(status)) {
  await new Promise(r => setTimeout(r, 2000))
  const refreshed = await getBatchImageJob(process.env.SUB2API_KEY, job.id)
  status = refreshed.status
}

// 3️⃣ Download the ZIP once the job is done
if (status === 'completed') {
  const zipBlob = await downloadBatchImageZip(process.env.SUB2API_KEY, job.id)
  // Save the ZIP (browser)
  const url = window.URL.createObjectURL(zipBlob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${job.id}.zip`
  a.click()
}

```

## Summary

- **Sub2API provides nine distinct REST endpoints** for asynchronous batch image operations, all prefixed with `/v1/images/batches` and routed through the gateway URL built by `buildGatewayUrl`.
- **The [`frontend/src/api/batchImage.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/batchImage.ts) client library** exports typed wrappers—`submitBatchImageJob`, `getBatchImageJob`, `downloadBatchImageZip`, and others—that handle authentication via `authHeaders` and manage HTTP semantics.
- **Job lifecycle management** includes creating, polling, canceling, and deleting batch records, while result retrieval supports both bulk ZIP downloads and granular single-image access.
- **Authentication is mandatory** via bearer tokens injected by the shared Axios client configuration in [`frontend/src/api/client.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/client.ts).

## Frequently Asked Questions

### What is the base URL for Sub2API asynchronous image endpoints?

All async image endpoints are relative to the gateway URL constructed by `buildGatewayUrl` in [`frontend/src/api/url.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/url.ts). The client library automatically prepends this base URL to the `/v1/images/batches` paths, so you only need to provide the API key and payload when calling wrapper functions like `submitBatchImageJob`.

### How do I authenticate requests to the batch image endpoints?

Authentication uses bearer tokens supplied via the `authHeaders` helper defined at lines 30‑35 of [`frontend/src/api/batchImage.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/batchImage.ts). Pass your Sub2API key as the first argument to any client wrapper function; the library injects the `Authorization: Bearer <token>` header automatically through the central Axios client in [`frontend/src/api/client.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/client.ts).

### What is the difference between the batch endpoints and the synchronous image generation endpoint?

Sub2API maintains a separate synchronous endpoint at `POST /v1/images/generations` for single-image requests that return results immediately. The asynchronous batch endpoints (`/v1/images/batches/*`) are designed for high-volume workflows, returning a job ID immediately while processing occurs server-side, and requiring subsequent polling or webhook handling to retrieve results.

### How do I handle pagination when listing batch jobs?

The `listBatchImageJobs` function (line 62 in [`frontend/src/api/batchImage.ts`](https://github.com/Wei-Shaw/sub2api/blob/main/frontend/src/api/batchImage.ts)) supports standard REST pagination parameters such as `limit`, `offset`, or cursor-based tokens passed as query string arguments. The response typically includes a `total` count and `next_page` token to facilitate iterative fetching of large job histories.