DEV Community

Cover image for How to Use Google Nano Banana 2 API
Preecha
Preecha

Posted on

How to Use Google Nano Banana 2 API

Building applications with AI image generation feels like magic—until you hit the wall of complex API documentation, authentication headaches, and debugging nightmares. You've seen what Nano Banana 2 can do: stunning images generated from text prompts, Pro-quality output at Flash speeds, and features like subject consistency that make multi-image workflows possible. But actually integrating it into your codebase? That's where most developers get stuck.

Try Apidog today

You've probably tried wading through Google's documentation, piecing together authentication flows, and manually testing requests in a CLI. Maybe you've already burned through API quota debugging malformed requests or wondered why your images come back blurry every time. The truth is, integrating any new API, especially one as powerful as Nano Banana 2 requires more than just reading the docs. You need a workflow that lets you test quickly, iterate on prompts, and manage your API calls efficiently.

In this guide, we'll walk through everything you need to integrate Nano Banana 2 into your applications, from setting up your Google Cloud project to writing production-ready code in Python and JavaScript. But here's what makes this guide different: we'll show you how to test and debug every step using Apidog, so you're not just copying code, you're building a workflow you can maintain and scale.

Prerequisites

Before you start, make sure you have:

  • A Google Cloud account (or sign up at cloud.google.com)
  • Basic understanding of REST APIs
  • Python 3.8+ or Node.js 18+ installed
  • An API client like Apidog for testing

This guide assumes you're familiar with making HTTP requests and handling JSON data. If you're new to APIs, check out our API Testing Guide for fundamentals.

Setting Up Your Google Cloud Project

To use the Nano Banana 2 API, you need a Google Cloud project with the Generative Language API enabled.

Step 1: Create a New Project

  • Go to the Google Cloud Console k- Click "Select a project" → "New Project"
  • Enter a project name (e.g., "nano-banana-image-gen")
  • Click "Create"
  • Wait for the project to be created

Create Google Cloud Project

Step 2: Configure API Access

  • Go to "APIs & Services" → "Credentials"
  • Click "Create Credentials" → "API Key"
  • Copy your API key (you'll need it later)

Create API key In google Cloud project

Pro Tip: It's best practice to restrict your API key in production. Limit it to the Generative Language API and your specific domains or IP addresses.

Getting Your API Key

There are two ways to get API access:

Option 1: Google Cloud Console (Recommended for Production)

Follow the steps above—the API key you created is your access credential.

Option 2: Google AI Studio (Recommended for Development)

  • Go to Google AI Studio
  • Sign in with your Google account
  • Click "Get API Key" in the navigation
  • Click "Create API Key" (or select an existing project)
  • Copy your API key

Create API key in Google AI Studio

The AI Studio key is great for development and testing. For production, use the Google Cloud Console key for better management and security.

Your First API Request

Let's make a simple image generation request to verify everything works.

Using cURL

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp-image-generation:predict?key=YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "A cute banana character wearing sunglasses, fun cartoon style",
    "number_of_images": 1
  }'
Enter fullscreen mode Exit fullscreen mode

Understanding the Response

{
  "predictions": [
    {
      "image": {
        "mimeType": "image/png",
        "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
      },
      "generatedImageId": "img_abc123xyz",
      "metadata": {
        "prompt": "A cute banana character wearing sunglasses, fun cartoon style",
        "seed": 12345,
        "finishReason": "SUCCESS"
      }
    }
  ],
  "metadata": {
    "modelVersion": "gemini-3.1-flash-image-preview",
    "processingTimeMs": 1250,
    "contentAuthenticity": {
      "synthID": "enabled",
      "c2pa": "enabled"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The data field contains a base64-encoded PNG image. You'll need to decode it to save or display the image.

Python Integration

Here's how to integrate Nano Banana 2 into your Python applications:

Installing the Client Library

pip install google-generativeai
Enter fullscreen mode Exit fullscreen mode

Basic Image Generation

import google.generativeai as genai
import base64
import os

# Configure the API with your key
genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))

# Create the model
model = genai.GenerativeModel("gemini-3.1-flash-image-preview")

# Generate an image
response = model.generate_images(
    prompt="A modern minimalist office with natural lighting, indoor plants, standing desk, 4k quality",
    number_of_images=1
)

# Save the image
if response.generated_images:
    image_data = response.generated_images[0].image_bytes
    with open("output_image.png", "wb") as f:
        f.write(image_data)
    print("Image saved to output_image.png")
Enter fullscreen mode Exit fullscreen mode

Advanced Image Generation with Parameters

import google.generativeai as genai
from PIL import Image
import io

genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))

model = genai.GenerativeModel("gemini-3.1-flash-image-preview")

# Generate with advanced parameters
response = model.generate_images(
    prompt="A futuristic cityscape at night with neon lights, flying cars, cyberpunk aesthetic",
    number_of_images=1,
    aspect_ratio="16:9",
    negative_prompt="blurry, low quality, distorted, ugly",
    safety_filter_level="block_medium_and_above"
)

# Process the response
for idx, generated_image in enumerate(response.generated_images):
    # Convert to PIL Image
    image = Image.open(io.BytesIO(generated_image.image_bytes))

    # Save with custom name
    image.save(f"generated_image_{idx}.png")

    # Access metadata
    print(f"Image {idx}: {generated_image.finish_reason}")
    print(f"Seed: {generated_image.seed}")
Enter fullscreen mode Exit fullscreen mode

Batch Image Generation

import google.generativeai as genai
import os

genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
model = genai.GenerativeModel("gemini-3.1-flash-image-preview")

# Generate multiple images at once
prompts = [
    "A red sports car on a mountain road",
    "A cozy coffee shop interior",
    "A minimalist bedroom design",
    "A tropical beach sunset"
]

# Generate all images
for idx, prompt in enumerate(prompts):
    response = model.generate_images(
        prompt=prompt,
        number_of_images=1,
        aspect_ratio="16:9"
    )

    if response.generated_images:
        image_data = response.generated_images[0].image_bytes
        with open(f"image_{idx + 1}.png", "wb") as f:
            f.write(image_data)
        print(f"Generated: image_{idx + 1}.png")
Enter fullscreen mode Exit fullscreen mode

Character Consistency Example

import google.generativeai as genai

genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
model = genai.GenerativeModel("gemini-3.1-flash-image-preview")

# Base character description
base_character = "A friendly cartoon robot with round body, blue eyes, antenna on head, white and light blue color scheme"

# Generate base character (note the seed for consistency)
response1 = model.generate_images(
    prompt=base_character + ", front view, standing pose",
    number_of_images=1,
    seed=42  # Important: note this seed
)

base_seed = response1.generated_images[0].seed
print(f"Base character seed: {base_seed}")

# Generate variations using the same seed
poses = [
    "sitting pose",
    "waving hand",
    "holding a ball",
    "walking"
]

for pose in poses:
    response = model.generate_images(
        prompt=f"{base_character}, {pose}, same character as seed {base_seed}",
        number_of_images=1,
        seed=base_seed  # Same seed maintains consistency
    )

    if response.generated_images:
        filename = f"robot_{pose.replace(' ', '_')}.png"
        with open(filename, "wb") as f:
            f.write(response.generated_images[0].image_bytes)
        print(f"Generated: {filename}")
Enter fullscreen mode Exit fullscreen mode

JavaScript/Node.js Integration

Installing the Client Library

npm install @google/generative-ai
Enter fullscreen mode Exit fullscreen mode

Basic Image Generation

const { GoogleGenerativeAI } = require("@google/generative-ai");
const fs = require("fs");
const path = require("path");

// Initialize with API key
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);

async function generateImage() {
  // Get the model
  const model = genAI.getGenerativeModel({
    model: "gemini-3.1-flash-image-preview",
  });

  // Generate image
  const result = await model.generateImages({
    prompt: "A beautiful sunset over the ocean with palm trees silhouette",
    numberOfImages: 1,
  });

  // Process the response
  if (result.generatedImages && result.generatedImages.length > 0) {
    const imageData = result.generatedImages[0].imageBytes;

    // Save to file
    fs.writeFileSync("sunset.png", Buffer.from(imageData, "base64"));
    console.log("Image saved to sunset.png");

    // Log metadata
    console.log("Seed:", result.generatedImages[0].seed);
    console.log("Finish Reason:", result.generatedImages[0].finishReason);
  }
}

generateImage().catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Handling Base64 Responses

const { GoogleGenerativeAI } = require("@google/generative-ai");
const fs = require("fs");

const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);

async function generateAndProcessImage() {
  const model = genAI.getGenerativeModel({
    model: "gemini-3.1-flash-image-preview",
  });

  const result = await model.generateImages({
    prompt: "Professional headshot of a person in business attire, studio lighting",
    numberOfImages: 1,
    aspectRatio: "1:1",
    resolution: "1024x1024"
  });

  const generatedImage = result.generatedImages[0];

  // Decode base64
  const imageBuffer = Buffer.from(generatedImage.imageBytes, "base64");

  // Save with metadata in filename
  const filename = `portrait_${generatedImage.seed}.png`;
  fs.writeFileSync(filename, imageBuffer);

  return {
    filename,
    seed: generatedImage.seed,
    finishReason: generatedImage.finishReason
  };
}

generateAndProcessImage()
  .then(info => console.log("Generated:", info))
  .catch(err => console.error("Error:", err));
Enter fullscreen mode Exit fullscreen mode

Express.js REST API Example

const express = require("express");
const { GoogleGenerativeAI } = require("@google/generative-ai");
const multer = require("multer");
const fs = require("fs");

const app = express();
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);

app.use(express.json());

// Image generation endpoint
app.post("/api/generate", async (req, res) => {
  try {
    const { prompt, aspect_ratio, negative_prompt, number_of_images } = req.body;

    const model = genAI.getGenerativeModel({
      model: "gemini-2.0-flash-exp-image-generation",
    });

    const result = await model.generateImages({
      prompt,
      numberOfImages: number_of_images || 1,
      aspectRatio: aspect_ratio || "1:1",
      negativePrompt: negative_prompt
    });

    // Convert images to base64 for response
    const images = result.generatedImages.map((img, idx) => ({
      id: idx,
      seed: img.seed,
      finishReason: img.finishReason,
      data: img.imageBytes // Base64 encoded
    }));

    res.json({
      success: true,
      images,
      metadata: {
        modelVersion: result.response?.metadata?.modelVersion,
        processingTimeMs: result.response?.metadata?.processingTimeMs
      }
    });
  } catch (error) {
    console.error("Generation error:", error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

// Batch generation endpoint
app.post("/api/generate/batch", async (req, res) => {
  try {
    const { prompts } = req.body;
    const model = genAI.getGenerativeModel({
      model: "gemini-3.1-flash-image-preview",
    });

    const results = [];

    for (const prompt of prompts) {
      const result = await model.generateImages({
        prompt,
        numberOfImages: 1
      });

      results.push({
        prompt,
        seed: result.generatedImages[0]?.seed,
        success: !!result.generatedImages[0]
      });
    }

    res.json({ success: true, results });
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});
Enter fullscreen mode Exit fullscreen mode

Advanced Parameters

Nano Banana 2 supports various parameters to fine-tune your image generation:

Parameter Reference

Parameter Type Description Example
prompt string Text description of desired image "A cat sitting on a mat"
number_of_images integer Number of images to generate (1-4) 2
aspect_ratio string Image aspect ratio "16:9", "1:1", "4:3"
resolution string Output resolution "1024x1024", "2048x2048"
negative_prompt string Elements to exclude "blurry, watermark"
seed integer Random seed for reproducibility 12345
safety_filter_level string Content filtering "block_medium_and_above"

Resolution Options

# Available resolutions
resolutions = [
    "512x512",    # Thumbnail, social media
    "768x768",    # Small web images
    "1024x1024",  # Standard square
    "1024x768",   # 4:3 landscape
    "1280x720",   # HD ready
    "1920x1080",  # Full HD
    "2048x2048",  # High quality
    "3840x2160"   # 4K
]

# Using specific resolution
response = model.generate_images(
    prompt="Professional product photography of a watch",
    resolution="2048x2048"
)
Enter fullscreen mode Exit fullscreen mode

Aspect Ratios

aspect_ratios = [
    "1:1",    # Square (Instagram posts)
    "4:3",    # Standard photo
    "16:9",   # Landscape (YouTube, web)
    "9:16",   # Portrait (Stories, TikTok)
    "21:9",   # Ultrawide
    "3:4",    # Portrait standard
    "2:3"     # Portrait photo
]

# Using specific aspect ratio
response = model.generate_images(
    prompt="Modern office interior design",
    aspect_ratio="16:9"
)
Enter fullscreen mode Exit fullscreen mode

Handling Responses

Parsing the Response Structure


python
import google.generativeai as genai

genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
model = genai.GenerativeModel("gemini-3.1-flash-image-preview")

response = model.generate_images(
    prompt="A fantasy castle on a mountain",
    number_of_images=2
)

# Access predictions (generated images)
for idx
Enter fullscreen mode Exit fullscreen mode

Top comments (0)