Skip to content
Guides

Image Generation API in Python: Prompt to File

An image generation API Python tutorial: a first request, reference pictures and edits, batches of four billed per image, saving files, safe retries.

Updated 5 min read

To generate images from Python, you send a prompt to an image generation API with requests, wait a few seconds for the job, then save each file. On Frameport one key reaches all 10 image models, from $0.025 per image, and an image that fails costs nothing.

This guide goes from a first request to a script you can run in production: reference pictures and edits, batches of four, saving the files, and retries that never pay twice. The examples use GPT Image 2.5 Sunburst, Nano Banana Pro and Frameport Image 1; every image model takes the same request.

What you need

  • Python 3.8 or later and requests (pip install requests).
  • An API key: create an account, add funds under Billing (from $10), then create a key under API keys. It starts with fp_live_ and is shown once.
  • The key in an environment variable, so it never lands in your code.
export FRAMEPORT_API_KEY="fp_live_..."
pip install requests

All the code below shares these lines:

import os
import requests

API = "https://frameport.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['FRAMEPORT_API_KEY']}"}

Your first image from the Python API

POST /v1/images/generations takes a model, a prompt, and optionally aspect_ratio (1:1 by default, or 3:4, 4:3, 9:16, 16:9) and n, the number of images. It holds the price on your balance and answers at once with 202 Accepted and a generation id. The images take a few seconds; read the generation until it settles.

Submit and wait
import time
import uuid


def error_of(res: requests.Response) -> str:
    try:
        error = res.json()["error"]
        return f"{error['code']}: {error['message']}"
    except (ValueError, KeyError, TypeError):
        return f"HTTP {res.status_code}"


def submit(body: dict, key: str = "") -> dict:
    res = requests.post(
        f"{API}/images/generations",
        headers={**HEADERS, "Idempotency-Key": key or str(uuid.uuid4())},
        json=body,
    )
    if not res.ok:
        raise RuntimeError(error_of(res))
    return res.json()


def wait(gen: dict, timeout: float = 300) -> dict:
    deadline = time.monotonic() + timeout
    while gen["status"] in ("queued", "running"):
        if time.monotonic() > deadline:
            raise TimeoutError(f"{gen['id']} is still {gen['status']}")
        time.sleep(2)
        res = requests.get(f"{API}/generations/{gen['id']}", headers=HEADERS)
        if not res.ok:
            raise RuntimeError(error_of(res))
        gen = res.json()
    return gen


gen = wait(submit({
    "model": "gpt-image-2-5-sunburst",
    "prompt": 'A minimal poster of a mountain lake at dawn with the title "Quiet Water" in a clean serif',
    "aspect_ratio": "3:4",
}))
print(gen["status"], "charged", gen["cost_usd"], gen["outputs"][0].get("url"))
The generation, once it has succeeded (abridged)
{
  "id": "gen_4kQ8vT2nLm9Xr7Wd1sYcPa",
  "object": "generation",
  "type": "image",
  "model": "gpt-image-2-5-sunburst",
  "status": "succeeded",
  "reserved_usd": 0.085,
  "cost_usd": 0.085,
  "outputs": [{
    "id": "file_8Hc2RkQw5ZpT1mVb7nXe3L",
    "status": "succeeded",
    "url": "https://frameport.ai/v1/files/file_8Hc2RkQw5ZpT1mVb7nXe3L?expires=...&signature=...",
    "url_expires_at": "2026-11-28T11:10:00.000Z",
    "cost_usd": 0.085,
    "content_type": "image/png"
  }],
  "error": null
}

Text that must appear in the picture goes in quotes, as above, so the model draws it as lettering. Each model takes the same body; the differences are in what it does with it:

ModelmodelPer imageReference picturesMakes
GPT Image 2.5 Sunburstgpt-image-2-5-sunburst$0.085Text onlyText to image
Nano Banana Pronano-banana-pro$0.16Up to 6Text to image and Image to image
Frameport Image 1fp-image-1$0.025Up to 10Text to image and Image to image

Reference pictures and edits

reference_images sends pictures with the prompt: a face, a product or a place to keep, or a picture to change. Nano Banana Pro takes up to 6 and Frameport Image 1 up to 10. Each item can be a public https URL, a data:image/...;base64, URI, an upload id (upl_…) or one of your earlier outputs by its file id (file_…).

That last form makes edits a two-step script: generate, then send the output back with the change written as an instruction. Write the change, not the whole scene again.

Edit an earlier output
edit = wait(submit({
    "model": "fp-image-1",
    "prompt": "Change the background to a beach at sunset, keep the poster's layout and title",
    "reference_images": [gen["outputs"][0]["id"]],
    "aspect_ratio": "3:4",
}))

For a picture on disk, send it to POST /v1/uploads as the raw body (PNG, JPEG or WebP, up to 10 MB). The id it returns works in any request of the workspace for 24 hours:

Upload a local picture
def upload(path: str, content_type: str = "image/jpeg") -> str:
    with open(path, "rb") as file:
        res = requests.post(
            f"{API}/uploads",
            headers={**HEADERS, "Content-Type": content_type},
            params={"filename": os.path.basename(path)},
            data=file,
        )
    res.raise_for_status()
    return res.json()["id"]  # upl_...


mug = upload("mug.jpg")
shot = wait(submit({
    "model": "nano-banana-pro",
    "prompt": "The ceramic mug from the picture on a walnut desk beside a window, morning light, product photo",
    "reference_images": [mug],
}))

Frameport Image 1 adds a small charge for each reference picture after the first; the quote below shows it before you spend. See uploads for the limits.

For edits on the highest-fidelity model, the Nano Banana Pro API guide has more examples.

Batches: four images, billed per success

n asks for 1 to 4 images in one request. The hold is the price of all of them, but each image is its own job and is charged only if it succeeds. The generation counts as succeeded when at least one image did; an image that failed shows status: "failed" with its reason, and its share of the hold goes back to your balance.

Model1 image2 images4 images
GPT Image 2.5 Sunburst$0.085$0.17$0.34
Nano Banana Pro$0.16$0.32$0.64
Frameport Image 1$0.025$0.05$0.10

To check a batch before it runs, send the same body without the prompt to POST /v1/generations/quote. Nothing is held, and the answer says whether your balance covers it:

Quote four images
q = requests.post(f"{API}/generations/quote", headers=HEADERS, json={"model": "nano-banana-pro", "n": 4}).json()
print(q["breakdown"], "covered:", q["enough_balance"])
200 OK
{
  "object": "quote",
  "model": "nano-banana-pro",
  "type": "image",
  "mode": "generate",
  "price_usd": 0.64,
  "reserved_usd": 0.64,
  "breakdown": "4 images × $0.16",
  "enough_balance": true
}

Model-by-model prices are in AI image generation API cost.

Saving the files

Each output that succeeded has a url, a signed link that opens without a key for about an hour, and a content_type. Stream each one to disk, and skip the ones that failed:

Save every image of a generation
EXTENSIONS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}


def save(gen: dict, stem: str) -> list:
    paths = []
    for index, output in enumerate(gen["outputs"]):
        if output["status"] != "succeeded" or not output.get("url"):
            continue
        path = f"{stem}-{index}{EXTENSIONS.get(output.get('content_type'), '.img')}"
        with requests.get(output["url"], stream=True) as res:
            res.raise_for_status()
            with open(path, "wb") as file:
                for chunk in res.iter_content(chunk_size=1 << 16):
                    file.write(chunk)
        paths.append(path)
    return paths


print(save(shot, "mug"))

If a link has expired, read the generation again for a fresh one, or fetch GET /v1/generations/{id}/content/{index} with your key (the index starts at 0). Files are not stored forever, so copy the ones you keep to your own storage (files).

Retries and idempotency

A timeout does not tell you whether the request arrived. Send an Idempotency-Key with each submit and reuse it on the retry: the same key with the same body returns the first generation for 24 hours, with an Idempotent-Replayed: true header, instead of making and charging the images twice. Build the key from your own record, such as an order or a row id:

Retry safely
def submit_with_retry(body: dict, key: str, attempts: int = 5) -> dict:
    for attempt in range(1, attempts + 1):
        try:
            res = requests.post(
                f"{API}/images/generations",
                headers={**HEADERS, "Idempotency-Key": key},
                json=body,
                timeout=60,
            )
        except requests.RequestException:
            if attempt == attempts:
                raise
            time.sleep(2 ** attempt)
            continue
        if res.ok:
            return res.json()  # 202 the first time, 200 on a replay
        reason = error_of(res)
        retry = res.status_code == 429 or res.status_code >= 500 or reason.startswith("request_in_progress")
        if not retry or attempt == attempts:
            raise RuntimeError(reason)
        time.sleep(float(res.headers.get("Retry-After", 2 ** attempt)))


gen = submit_with_retry({"model": "nano-banana-pro", "prompt": "A lighthouse on a cliff at dawn, soft fog", "n": 4}, key="row-1842")

The same key with a different body is refused with 409 idempotency_conflict, and a 400 is never worth retrying: its message names the field to fix. The idempotency reference covers each case, and the images reference lists every field.

Frameport's own engines, such as Frameport Image 1, render without a content filter once a workspace owner or admin aged 18 or older turns it off in Settings. Third-party models keep their makers' policies and may refuse a prompt; a refused job costs nothing. The uncensored image generation API guide has the details. For video, the video generation API in Python uses the same steps. The same calls in JavaScript and TypeScript are in the image generation API in JavaScript guide. To serve the images in a chat, see the Discord bot image generation guide. Your own pictures as references are sent as shown in upload image to API.

FAQ

Is there a free image generation API for Python?

Frameport is prepaid: you add funds from $10 and pay per image that succeeds, from $0.025. Listing the models and quoting a request are free, and a failed image costs nothing.

Can I use GPT Image from Python with this API?

Yes. gpt-image-2-5-sunburst and gpt-image-2-5-flare, made by OpenAI, take the same request as every other model here, with your Frameport key. They work from text alone; for edits from pictures, use Nano Banana Pro or Frameport Image 1.

How do I send a local image to an image generation API in Python?

Either upload it with POST /v1/uploads and pass the upl_… id, or encode it as a data:image/png;base64,… URI in reference_images. The upload keeps large files out of your request bodies.

Am I charged for the images that fail in a batch?

No. Each image of a batch is charged only if it succeeds. The generation's cost_usd is the sum of the images that did, and the rest of the hold goes back to your balance.

How many images can I generate at once?

Up to 4 per request with n, and up to 20 generations running at once in a workspace, with 60 new requests a minute. Queue the rest and submit as they finish.

Start building.

Your API key is free. Top up from $10 when you are ready.