Skip to content
Sign Up Free
Nano Banana

Gemini image editing API

Edit or combine Nano Banana images with BetterToken’s native Gemini API. Send PNG or JPEG references, use supported masks, and check dimensions and billing.

Upload an existing image and describe the change to make. Nano Banana 2, 2.1, and Pro can recolor an object, adjust a background, or combine multiple references into one scene, using your existing BetterToken API Key.

This page uses native Gemini JSON. To upload local files directly or use an OpenAI SDK, see OpenAI Images reference-image editing. Both entry points accept reference images; submit each request in the format required by its protocol.

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 and editing use the same endpoint. Add images to contents for editing; for text-only requests, see the text-to-image API.

Reference images

Use a separate part for each text instruction and image. inlineData.data contains raw base64 without a Data URL prefix. Use PNG or JPEG reference images; this endpoint accepts JSON, not multipart uploads or image URLs.

Before sending, replace REPLACE_WITH_IMAGE_BASE64 with your image’s base64 and set inlineData.mimeType to match the file. The sample instruction describes a mug; change it too if you use a different subject.

Images are converted locally. In the Playground, replace inlineData.data with the copied base64 and set inlineData.mimeType to the displayed MIME type. Keep each additional image in a separate part.

Edit one image

The example changes a blue mug to red. Before sending, replace REPLACE_WITH_IMAGE_BASE64 with your JPEG image’s Base64; for PNG, set mimeType to image/png. Change the instruction if your image shows a different subject.

Terminal window
export BETTERTOKEN_API_KEY="YOUR_API_KEY"
curl --fail-with-body --max-time 650 \
"https://bettertoken.ai/v1beta/models/nano-banana-2.1: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": "Change the mug to red. Preserve its shape, the table, and the background."},
{"inlineData": {"mimeType": "image/jpeg", "data": "REPLACE_WITH_IMAGE_BASE64"}}
]
}],
"generationConfig": {
"responseModalities": ["IMAGE"],
"candidateCount": 1,
"imageConfig": {"imageSize": "1K", "aspectRatio": "1:1"}
}
}' -o response.json

In-page Playground

After preparing your reference image, enter your BetterToken API Key in x-goog-api-key, select model, and add the editing instruction and image data in contents. For a standard reference edit, select referenceEdit and leave the root mask field empty.

Combine two reference images into one image

Add both images in order to the same user message and state each image’s role. Replace both Base64 placeholders and set the MIME type for each file.

{
"contents": [{
"role": "user",
"parts": [
{"text": "In one photograph on the same white table, place the blue mug from the first reference image on the left and the red mug from the second on the right. Preserve both mug shapes. Do not add other mugs."},
{"inlineData": {"mimeType": "image/png", "data": "REPLACE_WITH_FIRST_IMAGE_BASE64"}},
{"inlineData": {"mimeType": "image/jpeg", "data": "REPLACE_WITH_SECOND_IMAGE_BASE64"}}
]
}],
"generationConfig": {
"responseModalities": ["IMAGE"],
"candidateCount": 1,
"imageConfig": {"imageSize": "1K", "aspectRatio": "1:1"}
}
}

The two references are input materials; they do not request two output images. X-BetterToken-Max-Images: 1 still allows one combined image. State which subject comes from each reference, where to place it, and which details to preserve.

Resolution and iterative editing

All three models support 1K, 2K, and 4K. Nano Banana 2 and 2.1 support 14 aspect ratios; Pro supports 10. Set generationConfig.imageConfig.imageSize and aspectRatio; see all supported ratios. Confirm actual pixels from the returned image. Explicit quality is not supported.

For another editing turn, inspect and save the current result, then send it as a new reference image. State what to change and what to preserve. Each turn generates a new image, so check labels, small text, and product details separately.

If your application already keeps Gemini message history, preserve the complete model content, part order, and returned thoughtSignature when continuing. Do not generate a signature yourself. Multi-turn editing with Nano Banana 2.1 may not follow the requested change; uploading the verified image again each turn makes results easier to inspect.

Confirm SDK compatibility separately for text-to-image and reference editing. For nano-banana-2.1 reference edits, use this native HTTP request or upload a file with OpenAI Images; a successful SDK generation does not confirm every editing mode works.

Read and save images

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

Use the image-saving code on the text-to-image page to save the response from response.json and read its billing receipt.

Actual billing

After a successful generation or edit, the JSON root returns BetterToken’s bettertoken_image_billing extension alongside candidates. This settlement information is delivered with the image and can be read with your own API Key; no administrator permission or separate billing-query request is required. 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.

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.

Mask scope

A standard reference edit does not need mask. Masking is a conditional extension of the native Gemini API and works only when the selected model and image size support it. Nano Banana editing through OpenAI Images does not support mask.

Set the root JSON field mask to a PNG Data URL or an object such as {"image_url":"data:image/png;base64,..."}. This is a BetterToken extension, not a Gemini field. The mask must be a PNG with the same dimensions as the source image.

The final contents entry must have role user, with one or more text parts and exactly one source PNG or JPEG image in inlineData. Do not send the mask as a second inlineData image. For an alpha mask, use only alpha 0 for editable pixels and 255 for protected pixels; semi-transparent values are not supported, and RGB values, including gray, are ignored. Alternatively, use a fully opaque black-and-white mask: white is editable and black is protected. In this mode, use only pure white and black, with no gray pixels. Include at least one editable pixel. Masked editing is available only when the selected model and image size support it.

Set BETTERTOKEN_API_KEY before running the command and replace both base64 placeholders. The sample uses a JPEG source; if your source is PNG, change inlineData.mimeType to image/png. You can send this request directly to the endpoint above; changes outside the mask are not guaranteed to be prevented.

Terminal window
export BETTERTOKEN_API_KEY="YOUR_API_KEY"
curl --fail-with-body --max-time 650 \
"https://bettertoken.ai/v1beta/models/nano-banana-2.1:generateContent" \
-H "x-goog-api-key: $BETTERTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"mask": "data:image/png;base64,REPLACE_WITH_MASK_BASE64",
"contents": [{
"role": "user",
"parts": [
{"text": "Edit only the area marked by the mask. Preserve everything else."},
{"inlineData": {"mimeType": "image/jpeg", "data": "REPLACE_WITH_SOURCE_BASE64"}}
]
}],
"generationConfig": {
"responseModalities": ["IMAGE"],
"candidateCount": 1,
"imageConfig": {"imageSize": "1K", "aspectRatio": "1:1"}
}
}'

In the Playground, select maskedEdit, replace the source image Base64, and enter the mask PNG Data URL in the root mask field. Set inlineData.mimeType to match the source image. If the API returns no_eligible_image_service, that model, size, and operation combination has no available service; do not repeat the same request.

Limits and error handling

  • Google Web Search, Image Search, and other search-assisted image generation are not supported. Do not add search tools.
  • Use non-streaming generateContent. Files / fileData, Batch, Interactions, and streaming are not supported.
  • For 400, check Base64, MIME type, JSON nesting, and the selected aspect ratio. Replace all placeholders before sending.
  • For 403 with error.code=insufficient_user_quota, add quota or lower the maximum image count.
  • A successful response only confirms a result was returned; check whether the requested edit was achieved. Images arrive in this response, without background retrieval or polling. Save them promptly.
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:"Change the mug to red. Keep its shape, the background, and the lighting unchanged."
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 image bytes encoded as base64, without a Data URL prefix. Before sending, replace REPLACE_WITH_IMAGE_BASE64 with data from your own PNG or JPEG image.

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.