◉GEMINI LABJP
●ARGON — gemini-4-argon is generally available as of 10/13, aimed at complex coding, agents, math and science●DEEP RES — deep-research-pro-preview-12-2025 shuts down 10/23, 6 days left. Move to deep-research-preview-04-2026●NANO — gemini-nano-banana-2.1 is GA (10/06). gemini-3.1-flash-image is deprecated with no shutdown date yet●MCP — One write-up cut an 85,000-token tool result to 310 tokens by wrapping it in an ADK FunctionTool●FLASH — gemini-3.7-flash and 3.5-flash now route automatically to newer Flash models (10/08)●NEW — Stop Re-Reading Every Crash Report: Gre…●ARGON — gemini-4-argon is generally available as of 10/13, aimed at complex coding, agents, math and science●DEEP RES — deep-research-pro-preview-12-2025 shuts down 10/23, 6 days left. Move to deep-research-preview-04-2026●NANO — gemini-nano-banana-2.1 is GA (10/06). gemini-3.1-flash-image is deprecated with no shutdown date yet●MCP — One write-up cut an 85,000-token tool result to 310 tokens by wrapping it in an ADK FunctionTool●FLASH — gemini-3.7-flash and 3.5-flash now route automatically to newer Flash models (10/08)●NEW — Stop Re-Reading Every Crash Report: Gre…
Articles/API / SDK
◈ API / SDK/2026-03-11Intermediate

Gemini API Quickstart — Getting Started with Python and TypeScript

Get started with the Gemini API in Python or TypeScript — from API key setup and SDK installation to streaming, safety settings, and practical error handling.

Gemini API249Python51TypeScript8SDKquickstart

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-10-14
When Your config Raises "Extra inputs are not permitted", Check the Spelling of Every Key
If a google-genai call fails with a pydantic ValidationError (extra_forbidden) the moment you pass a config, it is almost always a one-letter typo. Here is the output I reproduced, a small function that checks keys before the call, and how to tell why response.text came back as None.
◈ API / SDK2026-10-08
When a Deprecation Has No Shutdown Date: Re-Picking an Image Model on Three Conditions
gemini-nano-banana-2.1 went GA on October 6, and gemini-3.1-flash-image was deprecated with no shutdown date. Here is a table and a short script for choosing a replacement by resolution, reference images, and search grounding.
◈ API / SDK2026-09-22
When Function Calls Turn Into Plain Text, Suspect the Property Names in Your Tool Declarations
A record of chasing MALFORMED_FUNCTION_CALL after output limits and schema conflicts were ruled out, bisecting nine tool declarations down to one property name, and adding a linter that stops bad names before they ship.