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
| Item | Value |
|---|---|
| Base URL | https://bettertoken.ai |
| Request | POST /v1beta/models/{model}:generateContent |
| Authentication | x-goog-api-key: YOUR_API_KEY or Authorization: Bearer YOUR_API_KEY |
| Content type | Content-Type: application/json |
| Model IDs | nano-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.
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.jsonIn-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
| Field | Setting |
|---|---|
generationConfig.responseModalities | Set to ["IMAGE"]. |
generationConfig.imageConfig.imageSize | Uppercase 1K, 2K, or 4K; defaults to 1K when omitted. |
generationConfig.imageConfig.aspectRatio | Use 1:1 for square images, 16:9 for landscape covers, or 3:4 / 9:16 for portrait content. |
generationConfig.candidateCount | Omit 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 base64import jsonfrom pathlib import Path
result = json.loads(Path("response.json").read_text(encoding="utf-8"))suffixes = {"image/png": ".png", "image/jpeg": ".jpg"}saved = 0for 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.
| Field | Meaning |
|---|---|
currency, settled_amount | Billing currency and total settled amount; monetary values are decimal strings. |
outputs[].index | Image number in the billing list, not an index into parts. |
outputs[].width, outputs[].height | Actual decoded image dimensions in pixels. |
outputs[].billing_resolution | Actual billed tier for the output. |
outputs[].currency, outputs[].amount | Currency 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
403witherror.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.
Related guides
- Reference-image editing and two-image composition
- OpenAI Images and Python SDK setup
- Model selection and output comparison
- Model plaza
/v1beta/models/{model}:generateContentAuthorizations
BetterToken API Key.
Headers
Maximum number of returned and billable images, not a guaranteed count. Defaults to 1.
Path Parameters
BetterToken Model ID. Choose one of the three Nano Banana models.
Body application/json
Conversation contents. Keep the complete model content and thoughtSignature for follow-up edits.
Show child attributes
Use user for a new request; use model for previous model responses in editing history.
Text and image parts. Put text and inlineData in separate parts.
Image description or editing instruction.
"A studio product photograph of a blue ceramic mug on a white table."Reference image embedded as base64.
The reference image MIME type.
"image/png"Raw base64 image bytes, without a Data URL prefix.
"REPLACE_WITH_IMAGE_BASE64"Image generation settings.
Show child attributes
Explicitly request image output.
Omit or use the integer 1. Do not send root-level n.
Output image settings.
Output resolution. Use uppercase K.
Aspect ratio. Pro supports 10 ratios; 2 and 2.1 also support 1:4, 4:1, 1:8, and 8:1.
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
PNG Data URL: data:image/png;base64, followed by real PNG bytes encoded as base64. Remote URLs are not accepted.
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.
Actual decoded image width in pixels.
Actual decoded image height in pixels.
Actual billed tier for this image; do not infer it only from the requested tier.
Settlement amount for one image, as a decimal string.
{
"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.
{
"error": {
"code": "insufficient_user_quota",
"message": "Insufficient balance or token quota."
}
}
