Nano Banana API: Generate and Edit with gemini-nano-banana-2.1

Use Nano Banana 2.1 in an application through BetterToken’s Images API or Google’s Gemini API. Generate, save, and edit images; distinguish provider-specific model IDs; calculate image, thinking, and search charges; and diagnose access, billing, and quota failures.

Contents
Nano Banana API: Generate and Edit with gemini-nano-banana-2.1

For application-level image generation and editing, start new Nano Banana API integrations with Nano Banana 2.1. Google uses gemini-nano-banana-2.1; BetterToken’s Images route uses nano-banana-2.1. Choose a provider, save one generated image, and verify an edit before increasing traffic.

Choose an API route before copying code

As of 2026-11-26, these routes use separate credentials, request formats, and billing.

RouteRequirements and billingChoose it when
BetterToken Images APIYour own BetterToken account and API Key. Nano Banana is charged per delivered image and resolution tier. Payment options and fees depend on the console at payment time.You need generation and reference-image editing through an OpenAI-compatible Images interface.
Google Gemini APIA Google account, an eligible region, a project-linked API key, and active paid billing for Nano Banana 2.1. Input, text/thinking, image output, and search can have separate charges.You need Google’s native Interactions workflow, thinking controls, or search grounding.

Generate and save one image through BetterToken

Create your API Key in the workspace and check the current image prices. The Base URL is https://www.bettertoken.ai/v1; generation uses POST /v1/images/generations.

Run this in Bash, with curl and Python installed. Paste your key when read waits, then press Enter.

read -rs BETTERTOKEN_API_KEY && export BETTERTOKEN_API_KEY

curl --fail-with-body --max-time 650 \
  "https://www.bettertoken.ai/v1/images/generations" \
  -H "Authorization: Bearer $BETTERTOKEN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nano-banana-2.1",
    "prompt": "A studio photograph of a green ceramic mug on a white table",
    "image_size": "1K",
    "aspect_ratio": "1:1",
    "n": 1,
    "response_format": "b64_json"
  }' -o generated.json

Save the following as save_images.py. It decodes the returned image and chooses the extension from mime_type, rather than assuming PNG.

import base64
import json
import sys
from pathlib import Path

result = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
images = result.get("data") or []
if not images:
    raise RuntimeError("No image returned; inspect the response locally.")

for index, item in enumerate(images, 1):
    suffix = {"image/png": ".png", "image/jpeg": ".jpg"}.get(item.get("mime_type"))
    if suffix is None:
        raise ValueError("Missing or unsupported image MIME type.")
    destination = Path(f"{sys.argv[2]}-{index}{suffix}")
    destination.write_bytes(base64.b64decode(item["b64_json"], validate=True))
    print(f"Saved {destination}")

print("Billing:", json.dumps(result.get("bettertoken_image_billing")))

Run:

python save_images.py generated.json generated

Success means the saved image opens correctly and the billing receipt identifies the delivered dimensions, tier, and charge. This is a synchronous API: the response contains the image, so there is no task to poll. The documented response fields explain how to reconcile the result.

Create a BetterToken account

Which Nano Banana model should a new project use?

Google’s model-selection guide lists these API models as of 2026-11-26.

ModelGoogle model IDStarting decision
Nano Banana 2.1gemini-nano-banana-2.1Default choice for new generation and conversational-editing applications.
Nano Banana 2 Litegemini-3.1-flash-lite-imageTest for simple, high-volume work where speed and cost dominate. It is not optimized for multiple references or sequential edits.
Nano Banana 2gemini-3.1-flash-imagePrevious-generation option. Compare an existing integration with 2.1 before changing production behavior.
Nano Banana Progemini-3-pro-imageTest for complex visual instructions, brand consistency, and demanding text layouts.
Original Nano Bananagemini-2.5-flash-imageLegacy option. Google recommends migration to Nano Banana 2 Lite.

These are model-selection recommendations, not guarantees that an edit preserves every product detail. For strict source-geometry requirements, compare precise product-image editing alternatives before choosing a generative editing workflow.

BetterToken’s Nano Banana documentation lists nano-banana-2.1, nano-banana-2, and nano-banana-pro. Keep those provider-specific identifiers separate from Google’s IDs; the Nano Banana Pro API route provides another model option for the same integration.

Edit a reference image through BetterToken

Save a PNG you have permission to use as reference.png. This request follows the documented Nano Banana multipart editing example, with n=1 requesting one image. It uses multipart form data, not the JSON body used for generation.

curl --fail-with-body --max-time 650 \
  "https://www.bettertoken.ai/v1/images/edits" \
  -H "Authorization: Bearer $BETTERTOKEN_API_KEY" \
  -F 'model=nano-banana-2.1' \
  -F 'prompt=Change the mug to blue. Preserve its shape and background.' \
  -F 'image=@reference.png;type=image/png' \
  -F 'image_size=1K' \
  -F 'aspect_ratio=1:1' \
  -F 'n=1' \
  -F 'response_format=b64_json' \
  -o edited.json &&
python save_images.py edited.json edited

For a JPEG reference, change the filename and use type=image/jpeg. Let curl supply the multipart boundary; do not add Content-Type: application/json. Open the edited image and compare the mug’s outline, handle, and background with the reference.

Keep each provider’s model names and parameters in a separate adapter. When maintaining a second image backend, the GPT Image migration guide covers that model family’s separate migration path.

Generate and edit with the official Gemini API

For Google’s own route, create a Gemini API key and enable billing on its project. Complete the billing plan presented by AI Studio, including funding the account when assigned Prepay. The Python example below uses that Google key, not your BetterToken key.

Google recommends the Interactions API for new projects. Its image guide uses client.interactions.create, then retrieves the last generated image through interaction.output_image. The following example makes two requests: one generation and one edit, each with its own usage.

In Bash, install or update the Google SDK and Pillow, then collect your Google key:

python -m pip install --upgrade google-genai Pillow
read -rs GEMINI_API_KEY && export GEMINI_API_KEY

Save this as nano_google.py. It requests the documented image/jpeg output format. The helper decodes the returned bytes with Pillow, then saves RGB PNG files. The edit uploads that saved PNG as image/png, without reading response MIME metadata.

import base64
import os
from io import BytesIO
from pathlib import Path
from google import genai
from PIL import Image

client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
model = "gemini-nano-banana-2.1"
image_format = {
    "type": "image",
    "mime_type": "image/jpeg",
    "image_size": "1K",
    "aspect_ratio": "1:1",
}

def save_image(interaction, stem: str):
    image = interaction.output_image
    if image is None or not image.data:
        raise RuntimeError("No image returned; inspect status and safety metadata.")
    image_bytes = base64.b64decode(image.data, validate=True)
    path = Path(stem + ".png")
    with Image.open(BytesIO(image_bytes)) as decoded:
        decoded.convert("RGB").save(path, format="PNG")
    return path, "image/png"

generated = client.interactions.create(
    model=model,
    input="Generate a studio photograph of a green ceramic mug on a white table.",
    response_format=image_format,
)
path, mime = save_image(generated, "google-generated")

edited = client.interactions.create(
    model=model,
    input=[
        {"type": "text", "text": "Change the mug to blue. Preserve its shape and background."},
        {"type": "image", "mime_type": mime,
         "data": base64.b64encode(path.read_bytes()).decode("ascii")},
    ],
    response_format=image_format,
)
edited_path, _ = save_image(edited, "google-edited")
print("Saved:", path, edited_path)
print("Generation usage:", generated.usage)
print("Editing usage:", edited.usage)

Run:

python nano_google.py

The expected result is google-generated.png and google-edited.png: the original mug and its edited version. Change image_size to 2K or 4K to request another resolution tier. The official generation and editing examples document these inputs and output controls.

Does gemini-nano-banana-2.1 still support generateContent?

Yes. Google still documents client.models.generate_content for this model. Its legacy-format image guide also shows POST https://generativelanguage.googleapis.com/v1/models/gemini-nano-banana-2.1:generateContent, authenticated with x-goog-api-key.

That interface uses contents and generationConfig. Interactions uses input and response_format. Keep the request and response schemas together; changing only the endpoint is not a migration. Google’s migration guide confirms that generateContent remains supported.

The BetterToken examples above use its documented Images interface. They do not assume compatibility with Google’s Interactions API.

What do resolution, thinking, and search actually cost?

Google’s Nano Banana 2.1 pricing, checked on 2026-11-26, lists Standard rates of $1.50 per million input tokens and $7.50 per million text/thinking output tokens. Image output is $30 per million tokens; Batch image output is $15 per million.

The following are image-output estimates only, using the pricing page’s square-image token counts.

ResolutionImage output tokensStandard image outputBatch image output
1K, 1024×10241120$0.0336$0.0168
2K, 2048×20481680$0.0504$0.0252
4K, 4096×40963780$0.1134$0.0567

For example, 3780 × $30 / 1,000,000 = $0.1134; Google rounds the Standard 4K figure to $0.113. Batch prices require the separate Batch API, currently available through generateContent, rather than the Interactions calls above.

For a Standard request without search, calculate:

USD =
  input_tokens × 1.50 / 1,000,000
  + (text_output_tokens + thinking_tokens) × 7.50 / 1,000,000
  + image_output_tokens × 30.00 / 1,000,000

An illustrative request with 500 input tokens, 1000 combined text/thinking tokens, and one 1K image costs an estimated $0.04185. That is $0.00075 + $0.0075 + $0.0336, not merely the image-output price.

Nano Banana 2.1 defaults to medium thinking, according to its model documentation. Inspect interaction.usage, including output_tokens_by_modality and total_thought_tokens in the Interactions reference, instead of pricing all tokens as image output. Use returned usage to reconcile the request rather than treating a resolution estimate as a final invoice.

When you enable Google Search grounding, one generation can trigger several billable search queries. Google’s grounding prices include 5,000 free search requests monthly, shared across Gemini 3 and newer models, then $14 per 1,000. A default daily cap of 1,500 requests applies per project. Retrieved search context is not charged as input tokens.

For Nano Banana Pro, Google’s Standard prices, checked on the same date, are $2 per million input tokens, $12 for text/thinking output, and $120 for image output. Calculate its request cost from its own usage and rates, rather than applying the Nano Banana 2.1 table.

BetterToken uses per-delivered-image resolution billing for Nano Banana, rather than this Google token calculation. Compare its current prices with your complete workload. Follow the billing-receipt instructions to inspect bettertoken_image_billing for the actual tier and settled amount. A missing receipt needs verification, not a zero-cost assumption.

Diagnose access, billing, and generation failures

AI Studio redirects to the region list. Check Google’s available regions before changing code or payment settings. An unsupported location and an unfunded account are different problems. When direct Google access is unavailable, evaluate a separate provider’s account and payment conditions; use the BetterToken route above after confirming those conditions for your account.

The request fails on a free or unfunded project. Nano Banana 2.1 has no Gemini API Free Tier. For Interactions, Google’s error reference documents 400 failed_precondition for unmet prerequisites and 402 payment_required for depleted Prepay credit. Check the key’s project and billing status, correct the identified condition, then repeat one small request.

The API returns 429. Google distinguishes rate_limit_exceeded from quota_exceeded in its Interactions error reference. Check your active rate limits, reduce concurrency for short-term limits, or wait for the relevant quota reset. Limits apply per project, so creating another key in that project does not create another quota.

The response contains no image, or the saved file will not open. Check for an image block before decoding it. With BetterToken, decode data[].b64_json and match the extension to mime_type. With Google, inspect the response status and request an image explicitly when the model returned only text.

A BetterToken image request times out. Its timeout guidance says to check the request record and charge before resending. A disconnected client does not prove generation stopped; an automatic retry can create another charged image. Align your application and proxy timeouts with the request’s expected wait.

The image includes SynthID. That is expected: Google’s image guide states that generated images include it. SynthID is an invisible digital watermark rather than a visible logo. It is not evidence of a failed request or a Free Tier restriction.

BetterToken API
Claude, GPT, Gemini, and DeepSeek with one API key
Text & code
ClaudeGPTGeminiDeepSeekGLMKimiQwenMiniMax+4
Video & images
SeedanceKlingWanHailuoGPT ImageNano Banana+2
  • One key for every model
  • Pay as you go, no subscription
  • OpenAI- and Anthropic-compatible