Skip to content
繁體中文
Generate Image

Nano Banana Image Generation ​

Generate and edit images through the native Gemini route.

This page uses Gemini's native generateContent route. Your account must have an enabled Gemini image model; a text-only model cannot generate images.

API Calls in Multiple Languages ​

See language setup. Set API_KEY and replace model, file URL, and ID placeholders first. Each version displays the raw response to the same request.

These examples display the raw API response. Continue with this page or the image overview for Base64 decoding, download, and storage.

bash
curl --fail-with-body --silent --show-error --max-time 180 \
  --request POST \
  --url "https://api.tokatlas.ai/v1beta/models/YOUR_ENABLED_GEMINI_IMAGE_MODEL_ID:generateContent" \
  --header "x-goog-api-key: $API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "A white ceramic cup on a pale gray background, studio lighting"
        }
      ]
    }
  ],
  "generationConfig": {
    "responseModalities": [
      "TEXT",
      "IMAGE"
    ]
  }
}'
python
import os
import requests

headers = {
    'x-goog-api-key': os.environ["API_KEY"],
    'Content-Type': 'application/json',
}
payload = {'contents': [{'role': 'user',
               'parts': [{'text': 'A white ceramic cup on a pale gray background, '
                                  'studio lighting'}]}],
 'generationConfig': {'responseModalities': ['TEXT', 'IMAGE']}}
response = requests.request(
    'POST', 'https://api.tokatlas.ai/v1beta/models/YOUR_ENABLED_GEMINI_IMAGE_MODEL_ID:generateContent', headers=headers,
    json=payload,
    timeout=180,
)
response.raise_for_status()
print(response.text)
js
if (!process.env.API_KEY) throw new Error("Set API_KEY first.");
const response = await fetch("https://api.tokatlas.ai/v1beta/models/YOUR_ENABLED_GEMINI_IMAGE_MODEL_ID:generateContent", {
  method: "POST",
  headers: {
    "x-goog-api-key": process.env.API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "A white ceramic cup on a pale gray background, studio lighting"
        }
      ]
    }
  ],
  "generationConfig": {
    "responseModalities": [
      "TEXT",
      "IMAGE"
    ]
  }
}),
  signal: AbortSignal.timeout(180_000),
});
if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}
console.log(await response.text());
java
import java.net.URI;
import java.net.http.*;
import java.time.Duration;

public class Example {
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("API_KEY");
        if (apiKey == null || apiKey.isBlank()) {
            throw new IllegalArgumentException("Set API_KEY first.");
        }
        String payload = String.join("\n",
            "{",
            "  \"contents\": [",
            "    {",
            "      \"role\": \"user\",",
            "      \"parts\": [",
            "        {",
            "          \"text\": \"A white ceramic cup on a pale gray background, studio lighting\"",
            "        }",
            "      ]",
            "    }",
            "  ],",
            "  \"generationConfig\": {",
            "    \"responseModalities\": [",
            "      \"TEXT\",",
            "      \"IMAGE\"",
            "    ]",
            "  }",
            "}"
        );
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30)).build();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.tokatlas.ai/v1beta/models/YOUR_ENABLED_GEMINI_IMAGE_MODEL_ID:generateContent"))
            .timeout(Duration.ofSeconds(180))
            .header("x-goog-api-key", apiKey)
            .header("Content-Type", "application/json")
            .method("POST", HttpRequest.BodyPublishers.ofString(payload))
            .build();
        HttpResponse<String> response = client.send(
            request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() < 200 || response.statusCode() >= 300) {
            throw new IllegalStateException("HTTP " + response.statusCode() + ": "
                + response.body());
        }
        System.out.println(response.body());
    }
}

Model Selection ​

Current official image IDs checked on 2026-10-03 include gemini-3.1-flash-image (Nano Banana 2), gemini-3.1-flash-lite-image (Nano Banana 2 Lite), and gemini-3-pro-image (Nano Banana Pro). Use the actual ID from your available models, including any configured Tokatlas alias.

1. Prepare ​

Install Python 3 and replace the key and enabled Gemini image model ID:

bash
python3 -m pip install requests
export API_KEY='YOUR_TOKATLAS_API_KEY'
export IMAGE_MODEL_ID='YOUR_ENABLED_GEMINI_IMAGE_MODEL_ID'

2. Generate and Save ​

Save as nano_banana.py and run python3 nano_banana.py. Success prints the saved path and creates the image in the current directory.

python
import base64
import os
from pathlib import Path
from urllib.parse import quote
import requests

base = os.environ.get("API_BASE_URL", "https://api.tokatlas.ai").rstrip("/")
model = quote(os.environ["IMAGE_MODEL_ID"], safe="")
parts = [{"text": "A white ceramic cup on a pale gray background, studio lighting"}]
response = requests.post(
    f"{base}/v1beta/models/{model}:generateContent",
    headers={"x-goog-api-key": os.environ["API_KEY"]},
    json={"contents": [{"role": "user", "parts": parts}],
          "generationConfig": {"responseModalities": ["TEXT", "IMAGE"]}},
    timeout=180,
)
response.raise_for_status()
body = response.json()
count = 0
for candidate in body.get("candidates", []):
    for part in candidate.get("content", {}).get("parts", []):
        if part.get("text"):
            print(part["text"])
        inline = part.get("inlineData")
        if inline and inline.get("data"):
            extension = {"image/png": ".png", "image/jpeg": ".jpg",
                         "image/webp": ".webp"}.get(inline.get("mimeType"), ".image")
            path = Path(f"nano-banana-{count}{extension}")
            path.write_bytes(base64.b64decode(inline["data"], validate=True))
            print("Saved", path)
            count += 1
if not count:
    raise RuntimeError(f"No image returned; inspect candidate finish reasons and promptFeedback: {body}")

3. Edit an Existing Image ​

Follow Reference Image Input to add a local image to parts and replace the text with an editing instruction.

Troubleshooting ​

  • 404: check the model ID and /v1beta/models/{model}:generateContent path.
  • Text only: check image-output support, responseModalities, and promptFeedback / finishReason.
  • 400: remove optional size/quality fields and start with this minimal request. Limits vary by model.
  • Repeating a prompt does not guarantee an identical image; describe details to preserve when editing.

Google image generation documentation