Nano Banana 2K Image, GIF & Video API

Click any model to load a ready-to-copy request in the terminal.

ModelCredits · from
# OpenAI Images-compatible format (BananaPic engine)
curl -X POST "https://bananapic.app/v1/images/generations" \
  -H "Authorization: Bearer obk_YOUR_API_KEY" \
  -H "Idempotency-Key: demo-nano-banana-2.1" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nano-banana-2.1",
    "prompt": "Studio shot of frosted perfume bottle on wet basalt",
    "size": "3:4",
    "response_format": "url",
    "strip_metadata": true
  }'

# Balance: GET https://bananapic.app/v1/account
# Image-to-image: pass "image_url": "https://..."
# Gemini-compatible v1beta format (BananaPic engine)
curl -X POST \
  "https://bananapic.app/v1beta/models/nano-banana-2.1:generateContent" \
  -H "x-goog-api-key: obk_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{"parts": [
      {"text": "Sunlit ceramic coffee mug on linen table"}
    ]}],
    "generationConfig": {
      "imageConfig": {
        "aspectRatio": "3:4"
      },
      "stripMetadata": true
    }
  }'
# Roadmap (currently disabled on public endpoint; check /.well-known/x402)
curl -i "https://bananapic.app/.well-known/x402"
Free pool status
Free Developer Access

Grab a free key in @BananaPicBot to test your integration: single images include a BananaPic badge. Batches and clean originals use paid credits.

Up to 5 images per 6 hours per user from the shared pool.

Endpoints and Balance

OpenAI Images (/v1/images/generations, /v1/images/edits) with Bearer obk_... and Gemini (/v1beta/models/{model}:generateContent) with x-goog-api-key. Check credits via GET /v1/account or X-Credits-Remaining.

Up to 4 References and GIF

Pass 1–4 source images (JPEG, PNG, WebP up to 8 MiB) via image_url / image_urls in JSON, multipart files in /v1/images/edits, or inlineData in Gemini. Select a GIF model for native image/gif loops.

Batches, ZIP and 24h Storage

POST /v1/batches accepts JSON or CSV up to 200 jobs with shared references and exports GET /v1/batches/{id}/zip. Both single renders and batch archives are stored for 24 hours.

How the API Works

  • One result per single-image call (n=1). The size parameter is an aspect-ratio hint, not an exact pixel size. Check the dimensions of the returned file.
  • A subset of OpenAI Images and Gemini fields is supported. Unknown SDK fields may be ignored; full compatibility with every feature of these APIs is not claimed.
  • strip_metadata cleans supported C2PA / EXIF containers. It does not guarantee removal of every AI indicator or hidden marks embedded in pixels.
  • Requests run in a queue. A 504 response with job_pending means the job is still running: save X-Job-ID and poll GET /v1/jobs/{id} (in the official OpenAI SDK, set max_retries=0 or pass Idempotency-Key to prevent duplicate charges).
  • Keep obk_YOUR_API_KEY on your server (credit balance is returned in X-Credits-Remaining). Signed URLs from response_format=url and job results remain available for 24 hours.

Zero-Downtime Primary + Auto-Fallback

Use BananaPic as your primary 2K provider and keep your existing provider as a fallback. Both examples return image bytes.

  • Allow a 90s client timeout for the 85s sync budget. On 504 job_pending, poll the job using X-Job-ID.
  • Switch providers after a rejection, failed job, confirmed queued cancellation, or preview. Verify the original using X-Image-Variant.
  • Save an Idempotency-Key for each request. If the connection drops, retry with the same key.

Python · AsyncOpenAI

import asyncio
import base64
import os

import httpx
from openai import APIStatusError, AsyncOpenAI

BASE_URL = 'https://bananapic.app'
API_KEY = os.environ["BANANAPIC_API_KEY"]
MODEL = 'nano-banana-2.1'


def original_or_preview(headers, content):
    variant = headers.get("X-Image-Variant")
    if variant == "original":
        return content
    if variant == "preview":
        return None
    raise RuntimeError("Missing or unexpected X-Image-Variant")


async def recover_primary(http, status, job_id, pending, cancel_queued=True):
    # With an 85s sync budget, 504 job_pending + X-Job-ID means the job is live.
    if status != 504 or not pending:
        return None
    if not job_id:
        raise RuntimeError("Pending job without X-Job-ID. Retry with the same Idempotency-Key.")
    job_url = f"/v1/jobs/{job_id}"
    for _ in range(300):
        job = await http.get(job_url)
        job.raise_for_status()
        state = job.json()["status"]
        if state in ("failed", "cancelled"):
            return None
        if state == "succeeded":
            result = await http.get(f"{job_url}/result")
            result.raise_for_status()
            return original_or_preview(result.headers, result.content)
        if state == "queued" and cancel_queued:
            cancellation = await http.delete(job_url)
            if cancellation.status_code == 409:
                cancel_queued = False
                continue  # A worker may have picked it up. Re-check the original job.
            cancellation.raise_for_status()
            return None
        await asyncio.sleep(2)
    raise TimeoutError(f"Job {job_id} is unresolved. Resume polling before using the fallback.")


async def generate(prompt, request_id, fallback, image_urls=()):
    # Save request_id before calling. On a transport error retry with the same key.
    # fallback is your existing provider's async function returning image bytes.
    headers = {"Idempotency-Key": request_id}
    options = {"strip_metadata": True}
    if image_urls:
        options["image_urls"] = list(image_urls)
    async with (
        AsyncOpenAI(base_url=BASE_URL + "/v1", api_key=API_KEY, timeout=90.0, max_retries=0) as primary,
        httpx.AsyncClient(base_url=BASE_URL, headers={"Authorization": f"Bearer {API_KEY}"}) as http,
    ):
        try:
            response = await primary.images.with_raw_response.generate(
                model=MODEL, prompt=prompt, response_format="b64_json",
                extra_headers=headers, extra_body=options,
            )
        except APIStatusError as exc:
            code = exc.code
            if not code or exc.status_code == 500:
                raise  # Submission may still have been accepted.
            image = await recover_primary(
                http, exc.status_code, exc.response.headers.get("X-Job-ID"), code == "job_pending",
            )
        else:
            data = response.parse().data[0].b64_json
            image = original_or_preview(response.headers, base64.b64decode(data))
    return image if image is not None else await fallback(prompt, image_urls)

Python · google-genai v1beta

import json
import asyncio
import base64
import os

import httpx
from google import genai
from google.genai import errors, types

BASE_URL = 'https://bananapic.app'
API_KEY = os.environ["BANANAPIC_API_KEY"]
MODEL = 'nano-banana-2.1'


def original_or_preview(headers, content):
    variant = headers.get("X-Image-Variant")
    if variant == "original":
        return content
    if variant == "preview":
        return None
    raise RuntimeError("Missing or unexpected X-Image-Variant")


async def recover_primary(http, status, job_id, pending, cancel_queued=True):
    # With an 85s sync budget, 504 job_pending + X-Job-ID means the job is live.
    if status != 504 or not pending:
        return None
    if not job_id:
        raise RuntimeError("Pending job without X-Job-ID. Retry with the same Idempotency-Key.")
    job_url = f"/v1/jobs/{job_id}"
    for _ in range(300):
        job = await http.get(job_url)
        job.raise_for_status()
        state = job.json()["status"]
        if state in ("failed", "cancelled"):
            return None
        if state == "succeeded":
            result = await http.get(f"{job_url}/result")
            result.raise_for_status()
            return original_or_preview(result.headers, result.content)
        if state == "queued" and cancel_queued:
            cancellation = await http.delete(job_url)
            if cancellation.status_code == 409:
                cancel_queued = False
                continue  # A worker may have picked it up. Re-check the original job.
            cancellation.raise_for_status()
            return None
        await asyncio.sleep(2)
    raise TimeoutError(f"Job {job_id} is unresolved. Resume polling before using the fallback.")


async def generate(prompt, request_id, fallback, references=()):
    # Save request_id before calling. On a transport error retry with the same key.
    # references is a sequence of (bytes, MIME type) pairs encoded as inlineData.
    parts = [types.Part.from_text(text=prompt)]
    parts.extend(types.Part.from_bytes(data=data, mime_type=mime) for data, mime in references)
    options = types.HttpOptions(
        base_url=BASE_URL, api_version="v1beta", timeout=90000,
        retry_options=types.HttpRetryOptions(attempts=1),
        headers={"Idempotency-Key": request_id},
        extra_body={"generationConfig": {"stripMetadata": True}},
    )
    async with (
        genai.Client(api_key=API_KEY, http_options=options).aio as primary,
        httpx.AsyncClient(base_url=BASE_URL, headers={"Authorization": f"Bearer {API_KEY}"}) as http,
    ):
        try:
            response = await primary.models.generate_content(
                model=MODEL, contents=parts,
                config=types.GenerateContentConfig(should_return_http_response=True),
            )
        except errors.APIError as exc:
            details = exc.details.get("error", {}).get("details", [])
            reasons = {detail.get("reason") for detail in details}
            if not reasons or exc.code == 500 or exc.response is None:
                raise  # Submission may still have been accepted.
            image = await recover_primary(
                http, exc.code, exc.response.headers.get("X-Job-ID"), "job_pending" in reasons,
            )
        else:
            raw = response.sdk_http_response
            payload = json.loads(raw.body)
            parts = payload["candidates"][0]["content"]["parts"]
            data = next(part["inlineData"]["data"] for part in parts if "inlineData" in part)
            image = original_or_preview(httpx.Headers(raw.headers), base64.b64decode(data))
    return image if image is not None else await fallback(prompt, references)