Blog

Tutorial

How to Use Nano-Banana via the HiAPI API: curl, Python, and a Working Request

Nov 12, 2026 12 min read
Abstract layered translucent glass planes that refract a light gray background into cool blue bands, used as a tutorial cover image
On this page

What Nano-Banana Gives You as an API

Nano-Banana is an image-generation model exposed through the HiAPI API. You send a prompt — and, if you want, one or more reference images — and you get generated images back. That is the whole mental model. There is no local model to host, no GPU to provision, and no separate SDK to learn: the same authentication, request envelope, and async task mechanics you use for other HiAPI models apply here too.

Before writing code, it helps to be clear about what an image-generation endpoint is and isn't. It is a creative endpoint: the same prompt can produce different outputs across runs, and you should design your pipeline to tolerate that. It is not a deterministic transform like resizing or format conversion. If you need pixel-exact reproducibility, cache the outputs you accept rather than assuming regeneration will match.

A typical integration has three phases:

  1. Submit a generation request with your prompt and any optional inputs.
  2. Wait on the resulting task, since image generation takes longer than a simple text completion.
  3. Retrieve the output, store it, and decide whether to accept it or retry with a tweaked prompt.

Two things are worth deciding up front, because they shape everything else: whether your prompts are text-only or use reference images (which changes the payload), and whether you need to preserve a consistent character across many generations (which almost always means reference images). The sections below build from the request shape outward, so you can follow along and adapt the examples as you go.

Anatomy of a Nano-Banana Request

Every call to Nano-Banana through HiAPI has the same skeleton. Only the payload changes.

Endpoint and authentication

Requests go to the HiAPI base URL, with the specific model identified in the payload rather than in a hand-built upstream URL. You authenticate with your API key in an Authorization header. Keep that key in an environment variable — never inline it in source code or commit it.

The model name

The model identifier is a field in your JSON body. Treat it as a string you copy from the model listing rather than something you construct, so a naming change doesn't silently break your code.

The prompt payload

At minimum you send a text prompt describing the image you want. Prompt quality dominates output quality here far more than any other field. Be concrete about subject, composition, lighting, and style. Vague prompts produce vague images, and no parameter setting rescues a prompt that doesn't say what you actually want.

Optional reference images

If you include reference images, they are part of the same request body — typically supplied as image URLs or encoded image data, depending on what the model accepts. Reference images anchor things like a character's face, an outfit, or an overall art style. Omit them for pure text-to-image generation; include them when the output needs to resemble something specific.

Some fields shape the result rather than the content: things like the requested output size or aspect ratio. These are best treated as requested values, not guarantees — the model may return dimensions that differ slightly. Plan your downstream code to read the actual returned dimensions instead of assuming what you asked for is what you got.

Here's the conceptual shape, with placeholder values:

{
  "model": "<nano-banana-model-id>",
  "prompt": "a red fox sitting in tall grass at golden hour, shallow depth of field",
  "reference_images": [],
  "size": "1024x1024"
}

Check the model's parameter documentation for the exact accepted field names and formats — the structure above is the general pattern, not a substitute for the spec.

A Working curl Request

The fastest way to confirm your key works and your payload is valid is a single curl call. Set up your environment first:

export HIAPI_API_KEY="your-api-key-here"

Then submit a generation request:

curl -sS -X POST "https://api.hiapi.ai/v1/images/generations" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<nano-banana-model-id>",
    "prompt": "a red fox sitting in tall grass at golden hour, shallow depth of field",
    "size": "1024x1024"
  }'

Where each piece goes:

  • URL — the HiAPI image-generation path. One base URL serves all models; the model is chosen in the body.
  • Authorization — your key, read from the environment so it never lands in shell history or source control.
  • Content-Type — must be application/json; a common early mistake is leaving this off and getting a parse error.
  • Body — the JSON payload from the previous section, with the prompt you actually want.

Reading the response

The response tells you what happened. Two outcomes matter:

  • Synchronous result — some calls return image data or image URLs directly. If you see URLs, fetch and store them promptly rather than relying on them being available indefinitely.
  • Task handle — if generation is asynchronous, the response includes an identifier you use to poll for status. That's the subject of the async section below.

Add -i to your curl command if you want to see the HTTP status line and headers alongside the body — invaluable when something fails and you need to tell an auth problem from a payload problem.

The Same Call in Python

For anything beyond a one-off, move to Python. The requests library keeps the example dependency-light and makes the HTTP layer explicit.

import os
import requests

API_KEY = os.environ["HIAPI_API_KEY"]
BASE_URL = "https://api.hiapi.ai/v1"

payload = {
    "model": "<nano-banana-model-id>",
    "prompt": "a red fox sitting in tall grass at golden hour, shallow depth of field",
    "size": "1024x1024",
}

response = requests.post(
    f"{BASE_URL}/images/generations",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    },
    json=payload,
    timeout=120,
)
response.raise_for_status()
data = response.json()
print(data)

A few habits to build in from the start:

  • Set a timeout. Image generation is slow; without a timeout your worker can hang indefinitely. A generous timeout is a reasonable starting point for a synchronous call, but tune it to your workload.
  • Use raise_for_status(). It turns 4xx and 5xx responses into exceptions you can catch, instead of silently parsing an error body as if it were a result.
  • Wrap it in a function. The snippet above is a script; in a service you'll want a function that takes a prompt and returns either image data or a task handle, so the rest of your code doesn't care about HTTP details.

If the response contains image URLs, download and store them immediately:

for item in data.get("data", []):
    url = item.get("url")
    if url:
        img = requests.get(url, timeout=60)
        img.raise_for_status()
        with open("output.png", "wb") as f:
            f.write(img.content)

Your own storage should be the source of truth for your application — not a temporary remote URL.

Handling Async Tasks

Image generation routinely takes longer than a single HTTP round trip should be held open for. HiAPI models that work this way return a task identifier when you submit, and you poll a task-status endpoint until the job finishes. The pattern is the same for every async model on the platform, so learn it once.

Submit, then poll

Your initial POST returns something like a task ID. You then poll a status endpoint with that ID. The logic you want:

import time

def poll_task(task_id, api_key, interval=2, max_wait=300):
    headers = {"Authorization": f"Bearer {api_key}"}
    deadline = time.time() + max_wait
    while time.time() < deadline:
        r = requests.get(
            f"https://api.hiapi.ai/v1/tasks/{task_id}",
            headers=headers,
            timeout=30,
        )
        r.raise_for_status()
        body = r.json()
        status = body.get("status")
        if status in ("succeeded", "completed", "failed", "error"):
            return body
        time.sleep(interval)
    raise TimeoutError(f"task {task_id} did not finish in {max_wait}s")

Three rules that save you pain

  1. Always cap total wait time. A job that never completes must not wedge your worker. The max_wait above is your exit hatch.
  2. Back off. A fixed short interval is fine for interactive use; for batch jobs, increase the interval as the wait grows so you don't hammer the status endpoint.
  3. Validate the terminal state. succeeded means you can read the output; failed means you should read the error payload, not retry blindly. Retrying a malformed payload just burns time.

Persist the task ID alongside your own job record. If your process restarts mid-poll, you can resume polling instead of resubmitting and paying for duplicate generations.

Reference Images and Character Consistency

Text-only prompts are fine for one-off images, but they fall apart the moment you need the same character in ten different scenes. Describing a face in words and hoping the model reproduces it consistently rarely works — small wording changes produce different people.

Reference images solve this. You include one or more images in the request alongside your text prompt, and the model uses them as visual anchors. Character consistency is the headline use case:

  • Character sheets — one clean reference image, many scene prompts, consistent face and outfit.
  • Style anchoring — a reference image sets the visual language while the prompt directs the content.
  • Product shots — a reference of the object keeps its design stable across backgrounds.

In the request, this means populating the reference-image field rather than sending it empty. Supply images as URLs or encoded data, whichever the model's parameter spec supports, and keep reference images clean: one clear subject beats a cluttered scene, because the model latches onto everything in the frame, not just the part you care about.

A practical pattern for a pipeline:

  1. Generate a character once, from a detailed text prompt.
  2. Review it and accept or regenerate until you're happy.
  3. Use that accepted image as the reference for every subsequent scene.

That's a nano banana API python workflow in miniature: lock the character once, then vary only the scene portion of the prompt. Expect to iterate — reference images improve consistency but don't make it perfect, so build a review step rather than assuming every output is usable.

Output Resolution and Practical Limits

Resolution is where assumptions cause the most trouble, so be deliberate about it.

Requested vs. actual size

You can request an output size, but treat it as a hint. The model may return dimensions that differ from what you asked for — particularly for unusual aspect ratios. The robust approach is to read the dimensions of the image you actually received and handle them generically: your storage, your thumbnails, and your layout should all derive from the real file, not from the requested value.

What drives quality

Output quality is dominated by the prompt and, when used, the reference images. A well-composed prompt with clear subject and lighting produces a better image than a vague prompt with a larger requested size. Don't reach for resolution as a fix for an underspecified prompt.

Planning around limits

  • Don't hardcode dimensions in your downstream code. Read them from the returned image.
  • Validate before you store. If your application requires a minimum size, check the actual dimensions after generation and regenerate if they fall short — don't assume the request enforced it.
  • Mind file size. Higher-resolution outputs mean larger payloads; stream or buffer downloads rather than loading everything into memory in a loop.
  • Batch carefully. Concurrency limits apply per account; if you're generating many images, add a small worker pool and retry with backoff rather than firing requests in an unbounded loop.

For the authoritative capabilities and accepted values for Nano-Banana specifically, the model's documentation is the reference — not the illustrative payloads in this post. Billing follows the platform's normal usage-based accounting, and current rates live on the pricing panel rather than in this tutorial.

Troubleshooting Common Errors

Most first-integration failures fall into a handful of buckets. Here's what to check for each.

401 / 403 — authentication

Your key is missing, malformed, or not being sent. Confirm the Authorization header is present, prefixed with Bearer , and that the environment variable is actually exported in the shell or process running the code. A trailing newline in a copied key causes this more often than you'd expect.

400 — malformed payload

Usually one of: invalid JSON (a stray quote or trailing comma), wrong Content-Type, a missing required field like prompt or model, or a reference-image field sent in a format the model doesn't accept. Print the exact body you're sending and compare it field-by-field against the parameter spec.

404 — wrong path or model

The endpoint path is wrong, or the model identifier doesn't match any model on the platform. Copy the model name verbatim from the listing instead of typing it from memory.

Timeouts and stalled polling

For synchronous calls, a too-short timeout aborts a job that would have succeeded. For async jobs, a stalled poll usually means your polling logic exited early or the terminal-state check doesn't match the status strings the API actually returns — log the raw status values and verify them. Always keep a maximum wait time so a stuck job fails loudly instead of hanging.

Empty results

A 200 response with no images is almost always a content concern rather than a bug: the prompt may be too vague, or it may have been filtered. Check the response body for an error or reason field before assuming the API is broken, then tighten and clarify the prompt.

Failures on retry

If the same payload sometimes works and sometimes fails, you're probably hitting rate limits or transient server errors. Add exponential backoff around submission and polling, and don't retry a 400 — fix the payload instead.

When in doubt, the fastest diagnostic is a minimal curl call with a trivial prompt. If that works, the problem is in your payload or code, not your credentials.

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