Blog

Tutorial

Nano-Banana-2 API Tutorial: Working curl and Python Requests via hiapi

Nov 10, 2026 13 min read
Flat-lay cover art: offset bone-white paper sheets in charcoal-edged layers with one rust-red sheet, 16:9.
On this page

What you need before your first call

Before you send anything to Nano-Banana-2, get four pieces in place. None of them takes long, and having all four ready makes the first request a copy-paste exercise rather than a scavenger hunt.

1. A hiapi account and API key

Every request is authenticated with an API key tied to your hiapi account. Create the key in your account dashboard and store it somewhere safe — a password manager, or an environment variable on your machine. Treat it like a password: never commit it to a repository or paste it into a shared document.

On your machine, export it once per shell session so the examples below can read it without hardcoding anything:

export HIAPI_API_KEY="your_api_key_here"

2. The API base URL

The base URL is the root that all requests are built on. You append the model route to it when you construct the endpoint. Keep the base URL in a config variable in your code rather than scattering it across files — that way, if it ever changes, you update one line.

3. A client for sending requests

You need exactly one of these to start:

  • curl — almost certainly already installed. Use it to confirm your key and payload are correct before writing any application code.
  • Python 3 with the requests library (pip install requests). This is what most readers will use to build the real integration.

Having both is useful: curl isolates the request from your code, so if something breaks you know whether the problem is the API call or your application.

4. A clear idea of what you're generating

Nano-Banana-2 handles both text-to-image and image-to-image work. Decide up front which mode you need, because the payload shape differs (covered in detail later). For your very first call, start with text-to-image — it has the fewest moving parts.

With the key exported, a client installed, and a prompt in mind, you're ready to look at the request itself.

Anatomy of a Nano-Banana-2 request

A Nano-Banana-2 call is a POST request with a JSON body. Every field has one job, and understanding them separately means you can change one thing at a time when something goes wrong.

The endpoint

Requests go to the hiapi API base URL with the Nano-Banana-2 model route appended. The method is always POST, because you're sending a payload to be processed, not fetching a resource.

The headers

Two headers matter:

  • Content-Type: application/json — tells the API how to parse your body.
  • Authorization — carries your API key. The examples below read it from the environment variable you exported earlier.

If either header is missing or malformed, the request fails before the model ever sees it. This is the single most common source of confusing errors.

The body fields

A text-to-image request carries these fields:

  • model — identifies Nano-Banana-2 as the model to run. Keep it explicit even if a default exists; it makes your code self-documenting and protects you if defaults change.
  • prompt — the natural-language description of the image you want. This is where most of your iteration will happen. Be concrete: subject, composition, style, lighting. Vague prompts produce vague results.
  • Image inputs — for text-to-image, this is absent or empty. For image-to-image, it carries your reference image (more on this in the image-to-image section).
  • Output and sizing parameters — model-specific fields that influence the shape or scale of what comes back. Only set what the model documents as supported; unknown fields in a strict API often mean a rejected request rather than a silently ignored one.

What comes back

The response is JSON. Depending on how the call is structured, you'll receive either the generated image data directly or a reference to it. Your client code should check the HTTP status first, then inspect the returned body — don't assume a 200-shaped response contains an image without verifying.

That's the whole structure: an authenticated POST with a small, explicit JSON body. Everything else in this tutorial is just variations on that shape.

A working curl request

This is the smallest complete call you can make. Run it from a terminal with your API key already exported, and you'll know within seconds whether your account, key, and network path are all working.

curl -X POST "$HIAPI_BASE_URL/nano-banana-2" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -d '{
    "model": "nano-banana-2",
    "prompt": "A weathered cabin on a rocky coastline at dawn, low fog, soft warm light, wide composition"
  }'

Set the base URL once in your shell alongside the key:

export HIAPI_BASE_URL="https://api.hiapi.ai"

(Use the base URL shown in your hiapi dashboard — that's the authoritative value for your account.)

Reading the output

curl prints the raw response to stdout. If the call succeeded, you'll see JSON containing your generated image. Pipe it through python -m json.tool to pretty-print it and confirm the structure:

curl -s -X POST "$HIAPI_BASE_URL/nano-banana-2" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $HIAPI_API_KEY" \
  -d '{"model":"nano-banana-2","prompt":"a red fox in fresh snow, side profile, crisp detail"}' \
  | python -m json.tool

Interpreting what you see

  • A successful response confirms your key is valid, the endpoint is right, and your payload parses. Save this working command — it's your baseline.
  • An error response means something in the three-line header set or the body is off. Copy the error text; the debugging section maps the common ones to fixes.

The value of starting in curl is isolation. Your key, headers, and JSON are all visible in one place, so a failure points at the request rather than at your application code. Once this command works, porting it to Python is mechanical.

The same request in Python

Here is the identical call in Python using requests. The payload is the same dict you saw in the curl body — nothing about the API changes, only how you send it.

import os
import requests

API_KEY = os.environ["HIAPI_API_KEY"]
BASE_URL = os.environ.get("HIAPI_BASE_URL", "https://api.hiapi.ai")

payload = {
    "model": "nano-banana-2",
    "prompt": "A weathered cabin on a rocky coastline at dawn, low fog, soft warm light, wide composition",
}

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {API_KEY}",
}

response = requests.post(
    f"{BASE_URL}/nano-banana-2",
    json=payload,
    headers=headers,
    timeout=120,
)

response.raise_for_status()
data = response.json()
print(data)

Why it's written this way

  • json=payload lets requests serialize the dict and set Content-Type for you. You can still pass the header explicitly; it does no harm and makes the request self-describing.
  • timeout=120 — image generation isn't instant. A generous timeout prevents your client from giving up while the model is still working. Tune the value to your use case.
  • raise_for_status() turns non-2xx responses into exceptions, so failures surface immediately instead of quietly flowing into your result-handling code.
  • Environment variables keep the key out of source. In production, inject it from your platform's secret store rather than a .env file that could be committed.

Extracting the image

The response body is JSON. Inspect it once interactively to learn the exact shape, then pull the image field out explicitly:

image_url = data["image_url"]  # confirm the key name against a real response

If your response carries base64 data instead of a URL, decode and write it:

import base64

with open("output.png", "wb") as f:
    f.write(base64.b64decode(data["image_base64"]))

Don't guess field names — print the raw response on your first successful call and key off what's actually there. That one habit prevents most integration bugs.

Text-to-image vs image-to-image with reference images

Everything so far has been text-to-image: a prompt in, an image out. Nano-Banana-2 also supports image-to-image, where you supply a reference image that the model uses as guidance. Knowing when to switch, and how the payload changes, is the difference between a call that works and one that gets rejected.

When to use each mode

  • Text-to-image — you have an idea in words and no starting image. Best for exploration, illustration, and anything generated from scratch.
  • Image-to-image — you have an existing image and want a variation, restyle, or edit that preserves its structure or subject. This is the mode for iterating on a design, matching a visual style, or transforming a photo.

If your prompt says "make this look like…" or "keep the layout but…", you want image-to-image.

How reference images change the request

The endpoint and headers stay the same. What changes is the body: you add a reference image field alongside your prompt. Depending on how the image is supplied, that field carries either a URL or encoded image data. Keep these rules in mind:

  • Use a direct, publicly reachable URL if you pass a link. Pages that require login or redirect through authentication will fail — the API needs to fetch the bytes directly.
  • Match the expected format. Common formats like PNG and JPEG are safe; exotic or corrupt files are a frequent cause of rejected requests.
  • Check size limits before uploading. Large images are often the reason for a payload error.
  • Keep the prompt focused. With a reference image, describe the transformation you want rather than re-describing the reference.

A sketched image-to-image payload looks like this:

payload = {
    "model": "nano-banana-2",
    "prompt": "Same subject, restyled as a graphite sketch with light crosshatching",
    "image_url": "https://example.com/your-reference.jpg",
}

Confirm the exact field name against your first successful response, as always. The principle is simple: text-to-image is prompt-only, image-to-image adds a validated reference image to the same request shape. Start with text-to-image to prove the pipeline, then layer reference images on top.

Handling errors and debugging failed requests

Failures on Nano-Banana-2 calls cluster into three groups. Learn to recognize each and you'll fix most problems in under a minute.

Authentication errors

If you see an auth error, the key isn't reaching the API correctly. Check, in order:

  • Is HIAPI_API_KEY actually exported in the shell or environment running the request? Run echo $HIAPI_API_KEY to confirm.
  • Is the Authorization header present and correctly formatted? The scheme and the key both matter.
  • Has the key been revoked or rotated in your dashboard?
  • Are you hitting the correct base URL for your account?

A 401 or 403 almost always means one of these four. The key itself is rarely the problem — the plumbing around it usually is.

Malformed payloads

A 400-class error usually means the API couldn't parse or validate your body:

  • Invalid JSON — a stray comma, single quotes instead of double, or an unescaped character. Piping curl output through python -m json.tool and building bodies in code rather than by hand both help here.
  • Missing required fields — model and prompt are the ones you'll most often forget; send both explicitly every time.
  • Unknown or unsupported fields — strict APIs reject fields they don't recognize. Remove anything extra until the request passes, then add one thing back at a time.
  • Wrong value types — a number sent as a string, or an array where a single value is expected. Match the documented types exactly.

Bad image inputs

Only relevant to image-to-image, but the most frustrating when it happens: an image URL that requires authentication, is behind a redirect, returns HTML instead of an image, is oversized, or is in an unsupported format. Verify the URL loads directly in a browser without logging in, and check the file type and size against the limits before sending.

A debugging sequence that works

  1. Read the error message and status code literally — they usually name the problem.
  2. Reproduce the failing request in curl with minimal fields, then add complexity back.
  3. Print the full response body in your code before processing it; don't rely on your assumptions about its shape.

If a minimal curl call works but your application fails, the bug is in your code, not the API. That's the fastest diagnostic split you have.

Wiring it into your application

A single working request is a good start; a reliable integration needs a little more around it. Here's how to move from one-off calls to something you can depend on.

Wrap the call in a function

Isolate the request in one function that takes a prompt (and optionally a reference image) and returns the result. Keep headers, the base URL, and payload construction inside that function so the rest of your codebase never touches them. When the API changes, you edit one place.

Handle retries deliberately

Generation can transiently fail for reasons unrelated to your payload. Retry with exponential backoff, but only on retryable failures — timeouts and certain server-side errors. Never retry authentication or payload validation errors; they'll fail identically every time and just add load. Cap the number of attempts so a persistent problem surfaces instead of hanging.

Timeouts and concurrency

Set a timeout that's generous enough for generation but bounded, and tune it once you've measured real response times. If you're issuing many requests, respect reasonable concurrency limits rather than firing everything at once — a queue with a worker pool is more predictable than unbounded parallel calls.

Store what you generate

The response gives you the generated image. Copy it to your own storage promptly rather than depending on a returned URL staying valid indefinitely. Name files deterministically and record the prompt and parameters next to each output — you'll want that provenance when you iterate on prompts later.

Keep secrets out of code

Read the API key from the environment or a secret manager in every environment. Rotate keys periodically. If a key ends up somewhere it shouldn't, revoke it in the dashboard.

Start small, then scale

Get one prompt working in curl, port it to Python, add the error handling from the previous section, and only then build the surrounding queue and storage. Each step proves the one before it.

With a verified curl call, a matching Python client, and the three error categories handled, you have the full path from first request to production integration.

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