← Articles

AI Image Generation API: Generate an Image in TypeScript

Use the Pipe2.ai TypeScript SDK to call an AI image generation API, poll the asynchronous run, and retrieve the generated image asset.

How-to By Pipe2.ai Updated September 4, 2026

AI Image Generation API: Generate an Image in TypeScript

An AI image generation API turns a prompt into an image through a programmatic run. With Pipe2, start the Image Generator, poll the returned run ID, and read the image URL from the completed run’s assets. The TypeScript example below uses the least expensive valid model and quality combination in the current catalog.

Generate an image with the TypeScript SDK

Install @pipe2-ai/sdk, set PIPE2_TOKEN to a Pipe2 personal access token, and run this module with Node. The prompt describes one subject, one setting, and one lighting direction so the first result is easy to evaluate.

import { createClient } from '@pipe2-ai/sdk';

const input = {
  model: 'gpt-image-2',
  prompt: 'A small red paper boat on a rain-darkened stone step, soft morning light, editorial product photograph, no text.',
  quality: 'fast',
};
const client = createClient(process.env.PIPE2_TOKEN);
const { run_pipeline } = await client.RunPipeline({
  pipeline_slug: 'image-generator',
  input,
});

while (true) {
  const { pipeline_runs_by_pk: run } = await client.GetPipelineRun({
    id: run_pipeline.run_id,
  });
  if (run?.status === 'completed') {
    console.log(run.assets?.[0]?.url);
    break;
  }
  if (run?.status === 'failed') throw new Error(run.error_message ?? 'Image generation failed');
  await new Promise((resolve) => setTimeout(resolve, 3000));
}

The pipeline request inside that program is exactly:

{
  "pipeline_slug": "image-generator",
  "input": {
    "model": "gpt-image-2",
    "prompt": "A small red paper boat on a rain-darkened stone step, soft morning light, editorial product photograph, no text.",
    "quality": "fast"
  }
}

The TypeScript SDK documentation covers installation, authentication, pipeline operations, asset uploads, subscriptions, and credit queries.

Understand the run, poll, and asset flow

RunPipeline accepts a pipeline slug and a JSON input object. It returns identifiers for an asynchronous run rather than holding the connection open until the image is ready. Keep run_pipeline.run_id; GetPipelineRun uses it to retrieve the latest status.

The polling loop handles the two terminal states. A completed run can include generated assets, and the example prints the first asset URL. A failed run can include error_message, which should be logged with the run ID. Production code should also set an overall timeout and treat a missing run as an error instead of polling forever. For live updates in a service, the SDK additionally provides WatchPipelineRun as an async iterable.

Start with the least expensive valid request

The example pins gpt-image-2 with quality: 'fast'. In the current Image Generator catalog, that is the lowest-cost valid combination and maps to the model’s low-quality generation tier. It is appropriate for checking authentication, request shape, polling, and asset handling before spending more on a final image.

Fast is a cost choice, not a promise that the first output is production-ready. Before dispatching a larger workload, use EstimatePipelineCost with the same pipeline_slug and input. Estimate again whenever you change the model, quality, or number of reference images; the active catalog is the source of truth for the charge.

Choose only the controls the image needs

A prompt alone is sufficient. Image Generator can also accept reference images, one supported reference video, an aspect ratio, a quality setting, a model selection, and a prompt-enhancement preference. The supported limits depend on the selected model, so read the pipeline schema instead of assuming that every engine accepts the same media.

For prompt-only work, describe the subject, composition, lighting, and style in a short narrative. Put literal in-image copy in quotation marks and proofread it after generation. For references, say what each image contributes and which details must remain stable. The five shared aspect ratios are 1:1, 16:9, 9:16, 4:3, and 3:4.

Leaving the model on Auto lets Pipe2 choose a compatible engine. Pin a model only when your product requirement depends on its documented capabilities or when you are running a controlled comparison. The AI image generator comparison explains how to keep prompt, references, framing, and attempt count consistent across models.

Handle tokens, failures, and output URLs safely

Create the SDK client with a Pipe2 token supplied through your runtime environment. Do not place a token in source code, commit it, or expose it to browser logs. The request uses Pipe2’s pipeline slug; clients do not send a separate model-provider credential.

Store the run ID before polling so a worker restart can resume the same job. Treat the returned asset URL as application data: persist it if your workflow needs a durable reference, validate that an asset exists before using index zero, and surface the pipeline error without silently retrying forever. If your application accepts user prompts or reference media, apply its normal authorization, moderation, and retention rules before sending them.

Frequently asked questions

Does the AI image generation API return an image immediately?

No. Image Generator starts an asynchronous run and returns a run ID. Poll that run until it is completed or failed, then read the generated image URL from the completed run's assets.

What is the minimum input for Image Generator?

A text prompt is enough. Image Generator also accepts optional reference images, a supported reference video, aspect ratio, quality, model, and prompt-enhancement controls, but a prompt-only request is the smallest useful integration.

Which setting makes the first API test least expensive?

Pin GPT Image 2 and set quality to fast, as in the example. That is the least expensive valid Image Generator combination in the current catalog; estimate the same request before production use because catalog prices can change.

See it in action

1 / 15

Related articles

2