GEMINI LABJP
NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20
Articles/API / SDK
API / SDK/2026-03-11Intermediate

Gemini API Quickstart — Getting Started with Python and TypeScript

Step-by-step guide to set up and use Gemini API with Python and TypeScript SDKs

Gemini API192Python38TypeScript8SDKquickstart

Gemini API Quickstart — Getting Started with Python and TypeScript

Getting your first Gemini response back takes minutes — the only real decisions are where to grab an API key and which SDK to install. The friction shows up later, once you start layering in streaming and error handling.

We'll go from key, to first request, to something you'd actually ship, in both Python and TypeScript/JavaScript.

Prerequisites

Before you start, you'll need:

  • A Google account
  • Python 3.7+ (for Python projects) or Node.js 14+ (for TypeScript)
  • pip or npm package manager
  • An API key from Google AI Studio

Getting Your API Key

  1. Visit aistudio.google.com
  2. Click on "API key" in the left sidebar
  3. Select "Create API key"
  4. Choose "Create API key in new project" or use an existing project
  5. Copy your API key immediately—you'll only see it once
  6. Store it securely in your environment

Never hardcode API keys in your source code. Use environment variables instead:

export GEMINI_API_KEY="your-api-key-here"

Python Quickstart

Installation

Install the Google AI Python SDK:

pip install google-genai

Basic Text Generation

Create your first program:

import os
from google import genai
 
# Initialize the client (reads GEMINI_API_KEY from environment)
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
 
# Simple text generation
response = client.models.generate_content(
    model="gemini-2.5-pro",
    contents="Explain quantum computing in simple terms"
)
 
print(response.text)

Understanding the Response

The response object contains:

# Full text content
print(response.text)
 
# Stop reason (why the model stopped generating)
print(response.stop_reason)  # "STOP", "MAX_TOKENS", etc.
 
# Usage metrics
print(response.usage_metadata)
# {
#   "prompt_tokens": 15,
#   "candidates_tokens": 150,
#   "total_tokens": 165
# }

Multi-Turn Conversations

Build interactive conversations:

client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
 
# Start a new chat session
chat = client.chats.create(model="gemini-2.5-pro")
 
# First turn
response1 = chat.send_message("What is machine learning?")
print(response1.text)
 
# Second turn (context is maintained)
response2 = chat.send_message("Can you give me a real-world example?")
print(response2.text)
 
# Third turn (full conversation context is preserved)
response3 = chat.send_message("How is that different from deep learning?")
print(response3.text)

Streaming Responses

Get real-time output as it's generated:

client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
 
# Streaming generation
stream = client.models.generate_content_stream(
    model="gemini-2.5-pro",
    contents="Write a short story about a robot learning to dream"
)
 
# Process chunks as they arrive
for chunk in stream:
    print(chunk.text, end="", flush=True)

Streaming is valuable for user-facing applications where displaying content as it arrives improves perceived responsiveness.

Image Processing with Python

Process images with Gemini:

from pathlib import Path
import base64
 
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
 
# Load an image
image_path = "cat.jpg"
image_data = base64.standard_b64encode(Path(image_path).read_bytes()).decode("utf-8")
 
# Analyze the image
response = client.models.generate_content(
    model="gemini-2.5-pro",
    contents=[
        {
            "role": "user",
            "parts": [
                {"text": "Describe this image in detail"},
                {
                    "inline_data": {
                        "mime_type": "image/jpeg",
                        "data": image_data,
                    }
                },
            ],
        }
    ],
)
 
print(response.text)

TypeScript Quickstart

Installation

Install the Google AI TypeScript SDK:

npm install @google/generative-ai

Basic Text Generation

Create your first TypeScript application:

import { GoogleGenerativeAI } from "@google/generative-ai";
 
const apiKey = process.env.GEMINI_API_KEY;
const client = new GoogleGenerativeAI(apiKey);
 
async function main() {
  const model = client.getGenerativeModel({ model: "gemini-2.5-pro" });
 
  const response = await model.generateContent(
    "Explain artificial intelligence in one paragraph"
  );
 
  console.log(response.response.text());
}
 
main();

Multi-Turn Conversations in TypeScript

import { GoogleGenerativeAI } from "@google/generative-ai";
 
const apiKey = process.env.GEMINI_API_KEY;
const client = new GoogleGenerativeAI(apiKey);
 
async function main() {
  const model = client.getGenerativeModel({ model: "gemini-2.5-pro" });
 
  const chat = model.startChat({
    history: [],
  });
 
  // First turn
  let result = await chat.sendMessage("What is TypeScript?");
  console.log(result.response.text());
 
  // Second turn (context is maintained)
  result = await chat.sendMessage("What are its main advantages?");
  console.log(result.response.text());
}
 
main();

Streaming in TypeScript

import { GoogleGenerativeAI } from "@google/generative-ai";
 
const apiKey = process.env.GEMINI_API_KEY;
const client = new GoogleGenerativeAI(apiKey);
 
async function main() {
  const model = client.getGenerativeModel({ model: "gemini-2.5-pro" });
 
  const stream = await model.generateContentStream(
    "Write a poem about the future of AI"
  );
 
  // Process stream chunks
  for await (const chunk of stream.stream) {
    const chunkText = chunk.candidates?.[0]?.content?.parts?.[0]?.text || "";
    process.stdout.write(chunkText);
  }
}
 
main();

Safety Settings

Control content filtering with Safety Settings:

Python

from google.genai import types
 
client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
 
response = client.models.generate_content(
    model="gemini-2.5-pro",
    contents="Your prompt here",
    safety_settings=[
        types.SafetySetting(
            category="HARM_CATEGORY_HATE_SPEECH",
            threshold="BLOCK_MEDIUM_AND_ABOVE"
        ),
        types.SafetySetting(
            category="HARM_CATEGORY_DANGEROUS_CONTENT",
            threshold="BLOCK_ONLY_HIGH"
        ),
    ]
)

TypeScript

import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from "@google/generative-ai";
 
const client = new GoogleGenerativeAI(apiKey);
const model = client.getGenerativeModel({
  model: "gemini-2.5-pro",
  safetySettings: [
    {
      category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
      threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
    },
  ],
});

Error Handling

Always implement proper error handling:

Python

try:
    response = client.models.generate_content(
        model="gemini-2.5-pro",
        contents="Your prompt"
    )
    print(response.text)
except genai.APIError as e:
    print(f"API Error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

TypeScript

try {
  const response = await model.generateContent("Your prompt");
  console.log(response.response.text());
} catch (error) {
  if (error instanceof Error) {
    console.error("Error:", error.message);
  } else {
    console.error("Unknown error occurred");
  }
}

Rate Limiting and Quotas

The free tier includes:

  • 60 requests per minute
  • 1.5 million tokens per month
  • 1000 requests per day

Implement exponential backoff for rate limit handling:

Python

import time
import random
 
def generate_with_retry(client, prompt, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.models.generate_content(
                model="gemini-2.5-pro",
                contents=prompt
            )
        except Exception as e:
            if attempt < max_retries - 1:
                wait_time = (2 ** attempt) + random.uniform(0, 1)
                print(f"Rate limited. Waiting {wait_time:.2f}s...")
                time.sleep(wait_time)
            else:
                raise

Best Practices

  1. Always use environment variables for API keys
  2. Implement error handling for production applications
  3. Use streaming for long responses to improve UX
  4. Set appropriate safety settings for your use case
  5. Monitor API usage to stay within quotas
  6. Test with cheaper models (Flash) before using Pro
  7. Cache responses when appropriate to reduce API calls

Next Steps

Now that you can make basic API calls, explore:

  • Function calling for external tool integration
  • Image and document processing
  • Building multi-step AI workflows
  • Deploying to production with proper monitoring

The Gemini API is flexible and powerful. Start simple, then layer in advanced features as your needs grow.

Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

API / SDK2026-06-11
Gemini 3.2 API Developer Guide — Correct Model IDs, Migration from 3.1, and Production Checklist
A practical guide to calling Gemini 3.2 via the API: correct model IDs, what changed from Gemini 3.1, Python and TypeScript code examples, and a production migration checklist.
API / SDK2026-04-27
Cancelling Gemini API Streams the Right Way — AbortController, asyncio, and the User-Initiated Stop Button
Hitting your chat UI's stop button shouldn't just freeze the screen — it should also stop billing. This guide shows how to wire up AbortController, request.is_disconnected, and the buffered-history pattern so cancellation actually does what users expect.
API / SDK2026-07-16
I Asked Gemini to Grade My App Store Screenshots. Everything Scored 78–85.
Ask Gemini Vision to grade App Store screenshots out of 100 and good candidates and deliberately broken ones both land at 78–85. Here is how I measured the judge's discrimination power, dropped absolute scoring, and rebuilt it as debiased pairwise comparison.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →