Blog

Tutorial

How to Use nano-banana-2 via the HiAPI API: Working curl and Python Requests

A developer walkthrough for wiring nano-banana-2 into your image generation pipeline

Nov 12, 2026 12 min read
Minimalist cover image: on a warm sand background, terracotta and tan horizontal stepped bands are arranged in a staggered downward sequence like a mercury column chart.
On this page

What nano-banana-2 Gives You and When to Reach for It

nano-banana-2 is an image generation model you call as an HTTP API. You send a prompt, optionally alongside a source image, and you get a generated image back. That is the whole mental model you need before writing code.

Reach for nano-banana-2 when you need to generate images programmatically inside an existing product or pipeline rather than through a chat window: marketing asset generation, thumbnail and cover creation, iterative edits on a base image, or batch jobs where the number of images is driven by your own data. Because the interface is a plain request/response API, you can slot it behind a queue worker, a backend endpoint, or a CLI tool without adopting a new SDK per language.

Two modes cover most use cases:

  • Text-to-image — you describe what you want in a prompt and get an image.
  • Image-to-image — you supply a source image plus a prompt describing the transformation, and get a modified image back.

The two modes share the same shape of request, which is why a single client wrapper (built later in this post) can handle both. If your pipeline only ever renders from text, you can ignore the image field entirely. If your pipeline is about editing existing assets, image-to-image is your entry point.

What nano-banana-2 does not do for you: it does not manage your retries, your timeouts, your storage, or your idempotency. Those are the parts you build around the call — and that is where most of the rest of this tutorial spends its time, because a naive requests.post in a loop is the most common reason a demo works and production does not.

Before You Send Your First Request

You need three things in place before the first call.

1. Platform credentials

You need API access from the HiAPI platform and the credential issued to your account. Treat it as a secret: load it from an environment variable or your secret manager, never commit it to a repository, and never paste it into a client-side bundle. Every request below reads the key from the environment so nothing sensitive appears in source code.

export HIAPI_API_KEY="your-key-here"

2. A client environment

For curl, all you need is a shell with curl available — the examples use flags that ship with standard builds. For Python, you need Python 3 and the requests library:

python3 -m venv .venv
source .venv/bin/activate
pip install requests

3. A place to put the output

Image generation returns image data — either inline in the response or as a reference you fetch afterward, depending on the response shape your account returns. Decide up front whether you are saving bytes to disk, uploading to object storage, or returning a URL to a caller. Doing this thinking now prevents the classic “it worked in the shell but I have nowhere to put the file” moment.

You do not need to estimate limits or pricing to start. The general rule for a first integration is: send the smallest valid request, confirm you get a valid response, and only then add parameters. The next section does exactly that.

A Minimal Working curl Request

Here is one complete text-to-image call. The endpoint, header, and body are the only moving parts: the endpoint identifies the model and operation on the HiAPI platform, the header carries your credential, and the JSON body carries the payload.

curl -sS -X POST "$HIAPI_BASE_URL/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nano-banana-2",
    "prompt": "a minimalist isometric workspace, soft daylight, muted palette",
    "n": 1
  }'

Set HIAPI_BASE_URL to the API base shown in your HiAPI account dashboard, so you are not hardcoding hosts into scripts. The body has three fields and all three matter:

  • model tells the platform which model to run. Keep it explicit even if you use a default elsewhere; it makes logs self-describing.
  • prompt is natural language. Be concrete about subject, composition, and style; vague prompts produce vague images.
  • n is how many images to request for this prompt. Start with 1 while you are validating that the plumbing works.

A successful response returns image data in the response body. Inspect it before writing any parser: pipe the output through jq or redirect it to a file and look at the top-level keys. You are confirming two things — that the request was accepted, and where the image payload actually lives in the response.

Resist the urge to add parameters on the first call. A working baseline you understand beats a large body you copied. Once this call returns an image, every later section is a variation on it.

The Same Request in Python

Port the curl call to Python without changing the payload. Keeping one source of truth (a dict) means the body you validated in the shell is the body you ship.

import os
import requests

BASE_URL = os.environ["HIAPI_BASE_URL"]
API_KEY = os.environ["HIAPI_API_KEY"]


def generate_image(prompt: str, model: str = "nano-banana-2", n: int = 1,
                   timeout: float = 60.0) -> dict:
    """Send one text-to-image request and return the parsed JSON response."""
    payload = {"model": model, "prompt": prompt, "n": n}
    response = requests.post(
        f"{BASE_URL}/v1/images/generations",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        },
        json=payload,
        timeout=timeout,
    )
    response.raise_for_status()
    return response.json()


if __name__ == "__main__":
    result = generate_image(
        "a minimalist isometric workspace, soft daylight, muted palette"
    )
    print(result.keys())

Three details are worth calling out, because they are the ones people drop when they copy snippets.

Always set timeout. Without it, a stalled connection blocks your worker indefinitely. The value above is a starting point, not a law — tune it against your own observed latencies.

Use json= not data=. Passing a dict to json sets the content type and serializes correctly; passing a raw string to data is how you get malformed-body errors that look like model failures.

Call raise_for_status() before parsing. A 4xx response that you try to .json()-parse into an image field produces a confusing downstream error. Surface the HTTP status first.

This function is the reusable wrapper mentioned earlier. The next section extends its payload rather than replacing it.

Text-to-Image vs Image-to-Image Payloads

The two modes differ in one way: whether the request body includes a source image. Everything else — endpoint, auth header, model name — stays the same.

Text-to-image

{
  "model": "nano-banana-2",
  "prompt": "a minimalist isometric workspace, soft daylight",
  "n": 1
}

Image-to-image

{
  "model": "nano-banana-2",
  "prompt": "same scene, but converted to a warm evening palette",
  "image": "<base64-encoded source image>",
  "n": 1
}

The concept to internalize: in image-to-image mode, the prompt describes the transformation, not the finished scene from scratch. “Convert to a warm evening palette” is a better prompt than re-describing the whole picture, because the source image already supplies the content.

Two practical notes on the image field:

  • Encode the source image according to the format the API documents for that field, and keep the encoded payload well within your request size budget. Oversized inputs are a leading cause of rejected requests.
  • If you plan to accept user uploads, validate size and format before encoding. Failing fast on your side is far cheaper than a round trip that ends in a 4xx.

Extend the Python wrapper with an optional image argument, and one function serves both modes:

def generate_image(prompt: str, image: str | None = None, **kwargs) -> dict:
    payload = {"model": "nano-banana-2", "prompt": prompt, **kwargs}
    if image is not None:
        payload["image"] = image
    # ... same request call as before

Because the branch is a single if, your calling code decides the mode and your transport layer stays unchanged. That is the payoff of keeping one wrapper.

Handling Async Jobs and Retries

Image generation can take longer than a typical JSON API call. Some responses return immediately with the finished image; others return a job you must poll before the result is available. Design for the polling case even if your first successful call came back instantly — otherwise your pipeline will break the first time a generation runs long.

A robust pattern has three pieces: a poll loop with backoff, a hard deadline, and a retry policy that distinguishes “not ready yet” from “failed.”

import time
import requests


def poll_job(job_id: str, base_url: str, api_key: str,
             initial_wait: float = 2.0, max_wait: float = 30.0,
             deadline: float = 300.0) -> dict:
    start = time.monotonic()
    wait = initial_wait
    while True:
        if time.monotonic() - start > deadline:
            raise TimeoutError(f"job {job_id} exceeded deadline")

        response = requests.get(
            f"{base_url}/v1/jobs/{job_id}",
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=30.0,
        )
        response.raise_for_status()
        body = response.json()

        status = body.get("status")
        if status == "succeeded":
            return body
        if status == "failed":
            raise RuntimeError(f"job {job_id} failed: {body}")

        time.sleep(wait)
        wait = min(wait * 2, max_wait)

The job path and status vocabulary should match what your HiAPI account’s API reference specifies — adjust the keys above to that shape, but keep the structure.

Rules that keep this healthy in production:

  • Back off exponentially with a cap. Polling every 200 ms wastes quota and hammers the endpoint; doubling the wait with a ceiling settles around the real completion time.
  • Bound total attempts and total time. A deadline is non-negotiable. An unbounded loop is an outage waiting for a slow day.
  • Retry only what is retryable. Transient network errors and 5xx responses deserve another attempt with jitter; 4xx responses do not — resending a malformed payload just burns time. Use a small bounded retry count (two or three attempts) and log each one.
  • Make retries safe. If your job creation endpoint accepts an idempotency key, send a stable one per logical request so a retried submission does not produce duplicate generations.

With a deadline, a backoff, and a bounded retry count, a slow generation becomes a logged, handled event rather than a hung worker.

Debugging the Errors You Will Actually Hit

When a call fails, read the raw status code and the full response body before touching a single model parameter. The body usually names the problem. Guessing is slower than logging.

Authentication failures

A 401 or 403 almost always means one of: the key is missing from the environment, the header is malformed, or the credential is not active for this environment. Check the literal header value you are sending — a missing Bearer prefix or a stray newline from a copied secret is a common culprit.

Payload errors

A 400 with a message about the body means the JSON itself is wrong: a missing prompt, a trailing comma, data= instead of json= in Python, or an image field that is not correctly encoded. Print the exact bytes you are sending once, check it, then remove the print.

Rejected inputs

Image-to-image requests that fail validation are usually about the input image: too large, wrong format, or not decodable. Validate size and encoding on your side before sending, and surface a clear error to whoever supplied the image rather than retrying.

Timeouts and 5xx

These are the retryable class. Distinguish connection timeouts from server errors in your logs, and confirm your retry has a bound — otherwise a persistent 5xx turns into an infinite loop.

A triage order that works

  1. Log the HTTP status and the raw response text for every failure.
  2. Verify the credential path first, before anything else.
  3. Replay the failing payload in curl to remove your client code from the equation.
  4. Only then adjust prompt, image, or other model parameters.

If a failure survives all four steps, capture the request ID (or equivalent correlation field) from the response and include it when you contact support — it turns a vague report into something traceable.

Making It Production-Ready

Before you ship, run through this checklist.

  • Secrets: the API key loads from the environment or a secret manager, and appears in no logs, no error messages, and no client bundles.
  • Timeouts: every HTTP call — creation, polling, and any fetch of the resulting image — has an explicit timeout.
  • Bounds: polling has a deadline, retries have a maximum attempt count, and retryable vs non-retryable failures are distinguished in code.
  • Observability: you log the request shape (prompt omitted or hashed if it can contain user data), the status code, the latency, and the correlation ID for every call.
  • Cost awareness: billing follows the dimensions your HiAPI account defines, so track how many generations and how much output each request produces, and instrument your own usage counters so a runaway loop is visible before the invoice is.
  • Storage: generated images are written somewhere durable — object storage or a database — rather than left in a temporary directory that vanishes with the container.

None of these items is nano-banana-2-specific. That is the point: the model call is the easy part, and everything around it is ordinary distributed-systems hygiene. Build the wrapper once, keep the payload in one dict, and both text-to-image and image-to-image come along for free.

Start with the curl call, port it to the Python wrapper, add the polling loop, and then run the checklist. For model details and the current API reference, see the nano-banana-2 documentation on the HiAPI platform.

Related articles

View all articles →

Start building with persistent AI artifacts

Get your API key and call image, video and audio models through one task-based API.

Read the API docs