Back to Blog

How to Auto Generate Images: Templates, Jobs and Webhooks

E2X Team··14 min read
automationimage-generationapiwebhooksbatch-processingnano-banana

Most answers to this question are a screenshot of a text box. Type a prompt, press a button, wait, download, repeat. That is not automation. That is you, working by hand, faster.

Automatic means no human in the loop. A row of data arrives, an image comes out, nobody watched it happen. That takes four parts: a prompt template with holes in it, data to fill the holes, a queue that accepts work without blocking, and somewhere durable to put the result. We run the API in the middle of that, so we see the pipelines people build and the ones that quietly break three weeks after launch.

Identical blank panels moving evenly along a stainless steel conveyor line in a clean modern factory

The part nobody tells you first: it is cheap now

Start with the number, because it changes what you are willing to build.

A thousand images through Nano Banana 2 Lite costs $23.80. That is 1,000 × $0.0238, at our price on 26 August 2026. A hundred thousand product shots — a real catalog, every SKU, every colourway — is $2,380.

The same volumes across the tiers you would pick between:

ImagesNano Banana 2 LiteNano Banana 2Nano Banana Pro
100$2.38$4.00$7.50
1,000$23.80$40.00$75.00
10,000$238.00$400.00$750.00
100,000$2,380.00$4,000.00$7,500.00

Prices and product terms can change. Check each provider's current pricing before making a purchasing decision. Google Batch or Flex pricing is not directly equivalent to a standard on-demand API request because scheduling, availability, and processing conditions differ; it is therefore excluded from this comparison. This is a scoped comparison, not a claim that E2X is the world's cheapest option in every configuration.

Most people asking how to automate image generation have quietly priced it at "too expensive to try". It is a $23.80 question. Build the thing.

Step 1: stop writing prompts, start writing a template

A prompt you type once is a sentence. A prompt a machine runs ten thousand times is a template with slots, and that difference is the whole job.

The rule: everything that varies goes in a slot, everything that must stay identical goes in the fixed text. Get that boundary wrong and the set drifts — half the images on white, half on grey, because "background" leaked into the variable part.

TEMPLATE = (
    "Studio product photograph of a {product_name} in {colour}, "
    "centred on a plain warm-grey backdrop, soft directional key light "
    "from the upper left, shallow depth of field, editorial catalog styling, "
    "no text, no logos, no people"
)

Two slots. The lighting, backdrop, framing and exclusions are frozen. That frozen half is what makes 400 images look like one photoshoot instead of 400 accidents.

Keep four things out of the variable half: the medium, the light direction, the background, and the negative instructions. Those are your visual identity. If they move per row, you have none.

A row of interchangeable precision metal stamping dies laid out on a brushed steel workbench, each fitting the same outer frame

Prompt craft itself is a separate post. What matters for automation is the shape: fixed frame, named holes, no surprises.

Step 2: the data is the actual product

The template is trivial. The data is where the work lives, and it is usually something you already have.

  • A product catalog table. One row per SKU, columns for name, colour, material, category.
  • A CMS export of blog posts, where title and topic become the slots for a header image per article.
  • Rows in your application database — user-generated listings, event pages, recipes.
  • A spreadsheet of ad variants: six headlines by four backgrounds is twenty-four images, and nobody is briefing that by hand.

Normalise whatever the source is into a list of dictionaries before it touches the API, and keep a stable ID on every row. You need it to match results back to records, and skipping it hurts at exactly the moment a webhook fires.

Step 3: submit, do not wait

Our API is asynchronous on purpose. You POST a job, you get a job ID back immediately, and generation happens on our side.

curl -X POST https://api.e2x.ai/v1/jobs/submit \
  -H "Authorization: Bearer $E2X_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/nano-banana-2-lite/text-to-image",
    "input": {
      "prompt": "Studio product photograph of a walnut desk lamp in matte black...",
      "aspect_ratio": "1:1"
    },
    "webhookUrl": "https://your-app.example.com/hooks/e2x"
  }'

The walker that turns a table into jobs is about thirty lines. It reads a CSV, formats the template per row, submits, and records the job ID against the row ID so nothing gets orphaned.

import csv
import os
import time
import requests

API = "https://api.e2x.ai/v1"
HEADERS = {
    "Authorization": f"Bearer {os.environ['E2X_API_KEY']}",
    "Content-Type": "application/json",
}

TEMPLATE = (
    "Studio product photograph of a {product_name} in {colour}, "
    "centred on a plain warm-grey backdrop, soft directional key light "
    "from the upper left, shallow depth of field, editorial catalog styling, "
    "no text, no logos, no people"
)

MAX_IMAGES = 500          # hard ceiling, see the cost section
UNIT_COST = 0.0238        # Nano Banana 2 Lite, checked 26 August 2026


def submit(row):
    body = {
        "model": "google/nano-banana-2-lite/text-to-image",
        "input": {
            "prompt": TEMPLATE.format(**row),
            "aspect_ratio": "1:1",
        },
        "webhookUrl": "https://your-app.example.com/hooks/e2x",
    }
    for attempt in range(4):
        r = requests.post(f"{API}/jobs/submit", json=body, headers=HEADERS, timeout=30)
        if r.status_code < 300:
            return r.json()["data"]["jobId"]
        if r.status_code == 429 or r.status_code >= 500:
            time.sleep(2 ** attempt)
            continue
        raise RuntimeError(f"row {row['id']} rejected: {r.status_code} {r.text}")
    raise RuntimeError(f"row {row['id']} still failing after 4 attempts")


with open("catalog.csv") as fh:
    rows = list(csv.DictReader(fh))[:MAX_IMAGES]

print(f"submitting {len(rows)} jobs, budget ${len(rows) * UNIT_COST:.2f}")

submitted = {}
for row in rows:
    try:
        submitted[row["id"]] = submit(row)
    except RuntimeError as err:
        print(f"skipped: {err}")

print(f"{len(submitted)}/{len(rows)} accepted")

Note what that loop does not do: stop when a row fails. A batch of 500 where row 212 has a null colour should give you 499 images and one logged skip, not a stack trace at 3am and zero images.

The slug matters more than it looks. google/nano-banana-2-lite/text-to-image carries the capability suffix; the Nano Banana 2 text slug is bare google/nano-banana-2 with none. Guessing costs you a 404 on a pipeline that otherwise looks finished. Each model publishes its parameter list in a machine-readable spec file.

Step 4: webhook over polling, and here is the reason

You can poll. GET /v1/jobs/{JOB_ID} returns pending, processing, completed, failed or cancelled, and for a one-off script that is fine.

For a pipeline it is the wrong choice, and the reason is not elegance. Polling couples your process lifetime to the slowest job in the batch. A Lite generation runs around 60 seconds on our side. Submit 500 and the poller must stay alive, holding state, for as long as the tail takes — through a deploy, a container restart, the 15-minute timeout on whatever serverless platform you are on. When it dies, it dies holding the only record of which jobs were in flight.

A webhook inverts that. You submit and exit. Later, a POST arrives with a completed job and you handle exactly that one job, statelessly.

// Express handler. Idempotent: the same jobId can arrive twice.
app.post("/hooks/e2x", express.json(), async (req, res) => {
  res.status(200).end(); // acknowledge first, work after

  const job = req.body.data;
  if (job.status !== "completed") {
    await markFailed(job.jobId, job.error?.message ?? "unknown");
    return;
  }

  const already = await findAsset(job.jobId);
  if (already) return;

  await storeImage(job.jobId, job.outputs[0].url);
});

Poll when you are running a script by hand and watching it. Take the webhook when nobody is watching, which is the definition of automation.

Step 5: the output URL is temporary, and this is how pipelines break

This is the one. If you skim everything else, read this section twice.

data.outputs[0].url is a delivery URL, not storage. It works now. It will not work forever. Anything that treats it as permanent — a product_image_url column, a CMS field, a link emailed to a client — renders fine in staging and shows broken image icons a fortnight later.

The failure is nasty because it is delayed. Nothing errors at write time. Tests pass. The batch reports 500 successes. Then images start disappearing from the oldest records first, and by the time anyone notices you cannot regenerate them without re-running the whole job, because the prompts were never saved either.

Download the bytes. Put them in your own bucket. Store your URL.

Identical crates on roller tracks at a loading dock at dusk, several already moved onto solid steel warehouse shelving behind them

import requests
import boto3

s3 = boto3.client("s3")


def store_image(job_id, row_id, source_url):
    img = requests.get(source_url, timeout=60)
    img.raise_for_status()

    key = f"products/{row_id}.jpg"
    s3.put_object(
        Bucket="my-assets",
        Key=key,
        Body=img.content,
        ContentType=img.headers.get("content-type", "image/jpeg"),
    )
    return f"https://cdn.example.com/{key}"

While you are in there, save the prompt alongside the image. One text column, and it is the difference between "regenerate that variant" and "start over".

Two more habits worth having from day one. Check the download returned image bytes rather than an error page, since a 200 with HTML in it will happily write to your bucket. And key storage on your row ID, not our job ID, so a regeneration overwrites the right object instead of orphaning it.

Step 6: what actually goes wrong at volume

Small batches hide everything. Here is what shows up once you are past a few hundred.

Partial batches are normal. Some fraction of any large run fails — a prompt that trips a content filter, a malformed row, a transient upstream error. Treat 497 of 500 as the success case, and give yourself a one-command retry over just those three rows.

Retries need a spending ceiling. A retry loop with no cap is a bug that bills. $0.0238 a shot sounds harmless until a stuck loop runs it forty thousand times. Put a hard count in the code — the MAX_IMAGES line above is the cheapest insurance here.

Idempotency is not optional. Webhooks can be delivered more than once. A handler that is not safe to run twice on one job ID gives you duplicate assets and duplicate rows, and you find out in the busiest week.

Costs need a live counter, not a monthly invoice. Monetary values in our API come back in micro-cents — 1,000,000 equals $1. Sum them per batch and log the total when it closes. A pipeline reporting "412 images, $9.81" every night is one nobody has to audit.

Aspect ratio defaults will surprise you. Lite defaults to 1:1, while Nano Banana 2 and Pro default to 9:16. Pin it in the template or half your catalog quietly becomes portrait.

The watermark travels with the file. Google stamps SynthID into everything its image models produce. It is invisible, it is not a flag, and it survives whatever your pipeline does to the bytes afterwards. Whoever owns brand or legal at your end should sign off on AI-generated assets before the pipeline exists, not after it has written 20,000 objects into a bucket.

Pneumatic diverter arms pushing a few panels off a moving belt into a side reject chute while the rest continue along the line

Which model to point the pipeline at

Default to Nano Banana 2 Lite and only move off it when something specific forces you to.

That is arithmetic, not a hedge. At $0.0238 it is the cheapest thing we sell that makes an image, a full generation newer than the original Nano Banana it replaced, and at pipeline volumes the price gap compounds into the only number finance looks at. It also carries four aspect ratios nothing else has — 1:4, 4:1, 1:8 and 8:1 — exactly what you want if the output is banners and vertical rails. One quirk: no resolution parameter at all, and sending one is an error rather than a silent no-op.

Route away from it in these four cases, and not otherwise:

  • Output above 1K. Lite is 1K only. Nano Banana 2 reaches 4K at $0.04 base, with 2K at ×1.5 and 4K at ×2.
  • Legible text in the image. Product cards with prices, localised infographics. That lives on Nano Banana Pro at $0.075, where 1K and 2K cost the same — take the 2K, it is free.
  • Transparent backgrounds. Cut-outs and sticker sheets need background: transparent, and GPT Image 2 is the only model we carry that does it in one call. Budget $0.0525 at 1K, not the raw catalog number — quality multiplies by 7 at every tier.
  • The same face or the same bottle across many frames. A reference-image problem, not a volume problem, with its own post on consistency.

For mixed workloads, run the bulk on Lite and branch the 2% needing text or fidelity to Pro on a column in your data. One pipeline, two models, Pro pricing only where it earns something.

For the parameter-by-parameter walkthrough of the submit and poll contract, see the Nano Banana Pro API tutorial, and for the tier-by-tier breakdown, the model comparison. Both of those assume you have already chosen a model. If you have not, the text-to-image models are listed with their prices attached, and the catalog adds the video side.

The whole thing, in order

Template with slots. Data with stable IDs. Submit as jobs under a hard ceiling. Take a webhook. Download the bytes into your own storage. Log the failures and the spend. Six steps, none of them hard, and the one that gets skipped is always step five.

Frequently asked questions

How do you auto generate an image?

Write your prompt as a template with named slots, fill those slots from a data source such as a product catalog or CSV, and submit each filled prompt as an asynchronous job to an image API. Take the result on a webhook rather than polling, then download the image bytes into your own storage. Nothing in that loop needs a human, which is what makes it automatic rather than fast manual work.

How much does it cost to generate 1,000 images automatically?

At E2X prices on 26 August 2026, 1,000 images through Nano Banana 2 Lite is $23.80, since each request is $0.0238. The same volume is $40.00 on Nano Banana 2 and $75.00 on Nano Banana Pro. Higher resolutions multiply on top, but for standard 1K output the per-image number is the whole calculation.

Should I use a webhook or poll for image generation jobs?

Use a webhook for anything running unattended. Polling ties your process lifetime to the slowest job in the batch, so a deploy or a serverless timeout kills the poller while it holds the only record of which jobs are still running. A webhook lets you submit and exit, then handle each completed job statelessly. Polling is fine for a script you are watching run.

Why do my generated images stop loading after a while?

Because you stored the API's output URL instead of the image. That URL is temporary delivery, not storage, so a column holding it renders correctly at first and breaks later. Download the bytes as soon as the job completes, write them to your own bucket, store your own URL. It is the most common way an image pipeline ships broken.

Which model should an automated image pipeline default to?

Nano Banana 2 Lite, at $0.0238 per image. It is the cheapest image model in our catalog and a generation newer than the original Nano Banana, and at batch volumes price dominates every other consideration. Move to Nano Banana 2 only for output above 1K, to Nano Banana Pro only for legible in-image text, and to GPT Image 2 only for transparent backgrounds.

What happens when some images in a batch fail?

Some always will, and the pipeline should treat that as normal rather than fatal. Keep submitting after a rejected row, log failed IDs with their errors, and build a retry path that runs only the failures. Cap retry attempts, since each one is a real charge.