Skip to content
繁體中文
Generate Image

Generate Image Overview ​

Generate an image from text and save the result locally.

This page uses the OpenAI-compatible image route, POST /v1/images/generations. A non-streaming request returns data[].url or data[].b64_json; the example saves the result locally. For native Nano Banana requests, see Nano Banana.

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/v1/images/generations" \
  --header "Authorization: Bearer $API_KEY" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "YOUR_ENABLED_IMAGE_MODEL_ID",
  "prompt": "A white ceramic cup on a pale gray background, studio lighting",
  "n": 1
}'
python
import os
import requests

headers = {
    'Authorization': 'Bearer ' + os.environ["API_KEY"],
    'Content-Type': 'application/json',
}
payload = {'model': 'YOUR_ENABLED_IMAGE_MODEL_ID',
 'prompt': 'A white ceramic cup on a pale gray background, studio lighting',
 'n': 1}
response = requests.request(
    'POST', 'https://api.tokatlas.ai/v1/images/generations', 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/v1/images/generations", {
  method: "POST",
  headers: {
    "Authorization": "Bearer " + process.env.API_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
  "model": "YOUR_ENABLED_IMAGE_MODEL_ID",
  "prompt": "A white ceramic cup on a pale gray background, studio lighting",
  "n": 1
}),
  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",
            "{",
            "  \"model\": \"YOUR_ENABLED_IMAGE_MODEL_ID\",",
            "  \"prompt\": \"A white ceramic cup on a pale gray background, studio lighting\",",
            "  \"n\": 1",
            "}"
        );
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30)).build();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.tokatlas.ai/v1/images/generations"))
            .timeout(Duration.ofSeconds(180))
            .header("Authorization", "Bearer " + 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());
    }
}

1. Prepare ​

Get a key and available model using API Basics. IMAGE_MODEL_ID must support /v1/images/generations; a text model cannot generate images on this endpoint. Install Python 3, then run:

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

2. Generate and Save ​

Save this as generate_image.py and run python3 generate_image.py. Success creates generated-0.image in the current directory. It contains the original image bytes; open it with an image viewer and use an extension matching the actual format.

python
import base64
import os
from pathlib import Path
import requests

base = os.environ.get("API_BASE_URL", "https://api.tokatlas.ai").rstrip("/")
response = requests.post(
    base + "/v1/images/generations",
    headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
    json={"model": os.environ["IMAGE_MODEL_ID"],
          "prompt": "A white ceramic cup on a pale gray background, studio lighting",
          "n": 1},
    timeout=180,
)
response.raise_for_status()
body = response.json()
if not isinstance(body.get("data"), list) or not body["data"]:
    raise RuntimeError(f"Missing image data: {body}")
for index, item in enumerate(body["data"]):
    if item.get("b64_json"):
        data = base64.b64decode(item["b64_json"], validate=True)
    elif item.get("url"):
        download = requests.get(item["url"], timeout=120)
        download.raise_for_status()
        data = download.content
    else:
        raise RuntimeError(f"Expected an image, received: {item}")
    path = Path(f"generated-{index}.image")
    path.write_bytes(data)
    print(f"Saved {path}: {len(data)} bytes")

3. Adjust and Troubleshoot ​

  • Start with only model, prompt, and n: 1. Add size or quality according to the model after success; aspect ratios and pixel sizes are different values.
  • 401 / 403: check the key and model access. For 400, read the error body and check model parameters.
  • 404 or unsupported model: check image support on the selected route; use the Nano Banana page for native Gemini images.
  • Only task_id returned: this is a different asynchronous route. Do not treat an ID as an image URL; select a route matching this page's response format.
  • After a timeout, check usage/request records before submitting again. URL expiry depends on the route; save images promptly.

See File Analysis for reference-image editing and Tool Calling for chat integration.