Skip to content
Sign Up Free
Nano Banana

Gemini text-to-image API

Generate Nano Banana images with BetterToken’s native Gemini API. Set model, resolution, and aspect ratio; save results and check dimensions and billing.

Generate product photos, content illustrations, and visual drafts from text with Nano Banana 2, 2.1, or Pro. One BetterToken API Key can call every image-generation model available on the platform.

This page uses the native Gemini format. If you already use an OpenAI SDK or Images client, use OpenAI Images generation. For an existing Chat integration, see how to choose among the three protocols. All entry points use the same Key; configure the fields for the protocol you choose.

Connection details

ItemValue
Base URLhttps://bettertoken.ai
RequestPOST /v1beta/models/{model}:generateContent
Authenticationx-goog-api-key: YOUR_API_KEY or Authorization: Bearer YOUR_API_KEY
Content typeContent-Type: application/json
Model IDsnano-banana-2, nano-banana-2.1, nano-banana-pro

Text-to-image needs only text. To edit an existing image, use the same endpoint and add a reference image to contents; see the image editing API.

Generate your first image

Set BETTERTOKEN_API_KEY in your terminal first. The example below creates a 1K square product image and saves the full response to response.json. Adjust the prompt for your product and keep the key in a server-side environment variable.

Terminal window
export BETTERTOKEN_API_KEY="YOUR_API_KEY"
curl --fail-with-body --max-time 650 \
"https://bettertoken.ai/v1beta/models/nano-banana-2:generateContent" \
-H "x-goog-api-key: $BETTERTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-H "X-BetterToken-Max-Images: 1" \
-d '{
"contents": [{
"role": "user",
"parts": [{"text": "A studio product photo of a blue ceramic mug on a white table, with soft side lighting and the entire mug and handle visible."}]
}],
"generationConfig": {
"responseModalities": ["IMAGE"],
"candidateCount": 1,
"imageConfig": {"imageSize": "1K", "aspectRatio": "1:1"}
}
}' -o response.json

In-page Playground

Enter your BetterToken API Key in x-goog-api-key, select model, and edit the text in contents. Start with 1K and 1:1, then click Send.

Resolution and aspect ratio

FieldSetting
generationConfig.responseModalitiesSet to ["IMAGE"].
generationConfig.imageConfig.imageSizeUppercase 1K, 2K, or 4K; defaults to 1K when omitted.
generationConfig.imageConfig.aspectRatioUse 1:1 for square images, 16:9 for landscape covers, or 3:4 / 9:16 for portrait content.
generationConfig.candidateCountOmit or set to the integer 1; do not add the root-level Images parameter n to native requests.

Nano Banana 2 and 2.1 support 14 aspect ratios; Pro supports 10. See all supported ratios. The requested ratio and resolution set the output specification; use the returned image to confirm actual pixels. Writing “4K” in the prompt does not replace imageSize. To check whether the returned image was generated directly at 4K, see how to tell native 4K from upscaled 4K.

Do not add OpenAI Images fields size, image_size, or aspect_ratio to this native endpoint. Explicit quality is not supported; set output specifications with resolution and aspect ratio.

Read and save images

Images are returned in candidates[].content.parts[].inlineData. Iterate over the parts, skip thought: true, decode data, and choose the file extension from mimeType. Do not assume the image is always the first part or always PNG.

The following code reads response.json saved by curl, saves every final image, and prints settlement details when a billing receipt is present.

import base64
import json
from pathlib import Path
result = json.loads(Path("response.json").read_text(encoding="utf-8"))
suffixes = {"image/png": ".png", "image/jpeg": ".jpg"}
saved = 0
for candidate in result.get("candidates", []):
for part in candidate.get("content", {}).get("parts", []):
if part.get("thought") or not part.get("inlineData"):
continue
blob = part["inlineData"]
suffix = suffixes.get(blob.get("mimeType"))
if suffix is None:
raise ValueError("Unexpected image MIME type.")
saved += 1
Path(f"generated-{saved}{suffix}").write_bytes(
base64.b64decode(blob["data"], validate=True)
)
if saved == 0:
raise RuntimeError("No final image returned; inspect response.json.")
billing = result.get("bettertoken_image_billing")
if billing is None:
print("Billing receipt missing; check the request record.")
else:
print("Settled:", billing["settled_amount"], billing["currency"])
for output in billing.get("outputs", []):
print(output["width"], output["height"], output["billing_resolution"],
output["amount"], output["currency"])

Actual billing

The response includes BetterToken’s bettertoken_image_billing extension at the JSON root, alongside candidates. Use it to check actual image dimensions and billed tier, not only the requested settings.

FieldMeaning
currency, settled_amountBilling currency and total settled amount; monetary values are decimal strings.
outputs[].indexImage number in the billing list, not an index into parts.
outputs[].width, outputs[].heightActual decoded image dimensions in pixels.
outputs[].billing_resolutionActual billed tier for the output.
outputs[].currency, outputs[].amountCurrency and amount for each output; the amount is a decimal string.

BetterToken reserves up to the highest available per-image price multiplied by X-BetterToken-Max-Images, then settles against the images actually returned and their dimensions. The header defaults to 1 and accepts 1–4. It sets the maximum number of images that may be delivered and billed; it does not guarantee that many images will be returned. Start with one image. If you need a fixed number, submit separate requests and record each result.

This is BetterToken settlement information delivered with the image. You can read it with your own API Key; no administrator permission or separate billing-query request is required.

Google GenAI SDK google-genai==2.30.1 does not expose this extension in its standard typed response. Use raw HTTP JSON when you need both the image and its billing receipt; do not treat a missing receipt as free usage. Aggregate monetary amounts with decimal types and by currency. Check current prices for your account currency and requested resolution on the model plaza.

Limits and error handling

  • Use non-streaming generateContent. Files / fileData, Batch, Interactions, and streaming are not supported.
  • Google Web Search, Image Search, and other search-assisted image generation are not supported. Do not add search tools.
  • For 400, check JSON nesting, parameter names, resolution case, and model aspect ratios. Do not resend the same invalid request.
  • For 403 with error.code=insufficient_user_quota, add quota or lower the maximum image count.
  • Results are delivered in the current response, without background image retrieval or task polling. Allow enough time in the client and proxy, and save images immediately after success.
POST/v1beta/models/{model}:generateContent

Authorizations

x-goog-api-keystringheaderrequired

BetterToken API Key.

Headers

X-BetterToken-Max-Imagesintegerdefault: 1

Maximum number of returned and billable images, not a guaranteed count. Defaults to 1.

Required range: 1 <= x <= 4

Path Parameters

modelenum<string>default: nano-banana-2.1required

BetterToken Model ID. Choose one of the three Nano Banana models.

Available options: nano-banana-pro, nano-banana-2, nano-banana-2.1

Body application/json

contentsobject[]required

Conversation contents. Keep the complete model content and thoughtSignature for follow-up edits.

Minimum array length: 1

Show child attributes
contents[].roleenum<string>default: user

Use user for a new request; use model for previous model responses in editing history.

Available options: user, model

contents[].partsobject[]required

Text and image parts. Put text and inlineData in separate parts.

Minimum array length: 1

contents[].parts[].textstringrequiredanyOf 1

Image description or editing instruction.

Example:"A studio product photograph of a blue ceramic mug on a white table."
contents[].parts[].inlineDataobjectrequiredanyOf 2

Reference image embedded as base64.

contents[].parts[].inlineData.mimeTypeenum<string>requiredanyOf 2

The reference image MIME type.

Available options: image/png, image/jpeg

Example:"image/png"

Raw base64 image bytes, without a Data URL prefix.

Example:"REPLACE_WITH_IMAGE_BASE64"

Image generation settings.

Show child attributes
generationConfig.responseModalitiesstring[]default: ["IMAGE"]

Explicitly request image output.

generationConfig.candidateCountenum<integer>default: 1

Omit or use the integer 1. Do not send root-level n.

Available options: 1

Output image settings.

Output resolution. Use uppercase K.

Available options: 1K, 2K, 4K

Aspect ratio. Pro supports 10 ratios; 2 and 2.1 also support 1:4, 4:1, 1:8, and 8:1.

Available options: 1:1, 1:4, 1:8, 2:3, 3:2, 3:4, 4:1, 4:3, 4:5, 5:4, 8:1, 9:16, 16:9, 21:9

maskstring | object

BetterToken gateway extension, not a Google-native field. Send a PNG Data URL string or an object containing image_url at the JSON root. The final contents entry must have role user and exactly one PNG/JPEG inlineData reference image. The PNG mask must match its dimensions. With binary Alpha, transparent pixels are editable and opaque pixels protected; with pure black-and-white masks, WHITE is editable and BLACK protected. At least one editable pixel is required. Alpha must be fully transparent or fully opaque; fully opaque black-and-white masks must not contain gray or colored pixels. The gateway converts this to reference images and editing instructions, without guaranteeing strict region isolation. The model/size editing combination must be available. Replace both image and mask base64 placeholders before sending.

Show child attributes
mask.image_urlstringrequiredoneOf 2

PNG Data URL: data:image/png;base64, followed by real PNG bytes encoded as base64. Remote URLs are not accepted.

Pattern: ^data:image/png;base64,

Response

200Generation response. Inspect final image parts and finishReason.

BetterToken billing extension. Settlement follows the actual delivered pixels and billing tier, which can differ from the requested tier. Amounts are decimal strings; use the returned values.

Show child attributes

Currency actually used to settle this request; do not hard-code USD or CNY.

Total amount settled for this request, as a decimal string.

Delivered image indices, actual dimensions, billing tiers, and per-image amounts. index numbers delivered images, not positions in the Gemini parts array.

Required range: x >= 0

Actual decoded image width in pixels.

Required range: x >= 1

Actual decoded image height in pixels.

Required range: x >= 1

Actual billed tier for this image; do not infer it only from the requested tier.

Available options: 1K, 2K, 4K

Settlement amount for one image, as a decimal string.

Example
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "inlineData": {
              "mimeType": "image/png",
              "data": "BASE64_IMAGE_DATA"
            }
          }
        ]
      },
      "finishReason": "STOP"
    }
  ]
}
400Invalid parameters or unsupported capability.
401Missing or invalid API Key.
402Insufficient balance.
403Insufficient balance or token quota: error.code is insufficient_user_quota. Funds must also cover the reservation of the highest-tier unit price times the image-count upper bound, before actual-delivery settlement. Inspect error.code rather than treating every 403 as an authorization error.
errorobject
Show child attributes
Example
{
  "error": {
    "code": "insufficient_user_quota",
    "message": "Insufficient balance or token quota."
  }
}
429Rate limit or upstream busy.
500Generation service error. Check the request result before retrying.