Back to HomeAI API

Gemini API Python Tutorial: 2026 Complete Guide to Calling Google AI Models from Scratch

14 min min read
#Gemini API#Python#Google AI SDK#API Integration#Multimodal#Code Examples#Function Calling#Streaming#Error Handling#Tutorial

Gemini API Python Tutorial: 2026 Complete Guide to Calling Google AI Models from Scratch

Get Gemini API Running in 5 Minutes

You've already heard that Gemini API is powerful and affordable.

But you open Google's official documentation and find it long and scattered, with no clear starting point.

This tutorial saves you the time of sifting through docs. I'll walk you through Gemini API Python integration from scratch in the simplest steps -- from SDK installation to multimodal applications, with copy-paste-ready code at every step.

Need a Gemini API enterprise plan? Get better pricing through CloudInsight, no overseas payment hassles.

Python developer integrating Gemini API

TL;DR

Install the google-genai package -> Set API Key -> Create a genai.Client -> Call client.models.generate_content() and you're done. This tutorial covers text generation, image understanding, Streaming, and Function Calling, with complete runnable code.


Python Environment Preparation & Gemini SDK Installation

Answer-First: All you need is Python 3.9+, pip, and one line pip install google-genai to get started. The old google-generativeai package is no longer maintained -- use Google's official unified google-genai SDK.

Environment Requirements

ItemMinimumRecommended
Python3.93.11+
pip21.0Latest
google-genai1.0.0latest
OSWindows / macOS / LinuxAny

Installation Steps

We recommend creating a virtual environment first to avoid package conflicts:

# Create virtual environment
python -m venv gemini-env

# Activate virtual environment (macOS / Linux)
source gemini-env/bin/activate

# Activate virtual environment (Windows)
gemini-env\Scripts\activate

# Install Gemini SDK
pip install google-genai

After installation, verify:

python -c "from google import genai; print(genai.__version__)"

If you see a version number, the installation was successful.

Common Installation Issues

  • pip version too old: Run pip install --upgrade pip first
  • SSL errors: Corporate networks may need proxy configuration
  • M1/M2 Mac compatibility: The SDK fully supports Apple Silicon

Getting Your Gemini API Key & Setting Up Authentication

Answer-First: Get an API Key in just two clicks at Google AI Studio. Storing it in an environment variable is the safest approach.

Get Your API Key

  1. Go to Google AI Studio
  2. Log in with your Google account
  3. Click "Get API Key" -> "Create API Key"
  4. Copy the generated Key

No credit card required to get a free API Key. For complete application steps, see Gemini API Official Documentation & Feature Guide.

Set Up API Key (The Safe Way)

Never hardcode your API Key in source code.

The correct approach is using environment variables:

# macOS / Linux
export GEMINI_API_KEY="your-api-key-here"

# Windows PowerShell
$env:GEMINI_API_KEY="your-api-key-here"

Then read it in Python:

import os
from google import genai

client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])

If you manage environment variables with .env files, use python-dotenv:

from dotenv import load_dotenv
load_dotenv()

client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))

Text Generation API Call Implementation with Code Examples

Answer-First: Create a genai.Client, call client.models.generate_content() with your model and Prompt, and get AI-generated text back.

Basic Text Generation

import os
from google import genai

client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])

# Call API (pass model and contents directly to generate_content)
response = client.models.generate_content(
    model="gemini-3.6-flash",
    contents="Describe Taiwan's night market culture in 3 key points"
)

# Print result
print(response.text)

That's the simplest usage. Just a few lines of code to get Gemini API running.

Adjusting Generation Parameters

You can control generation results via GenerationConfig:

from google.genai import types

config = types.GenerateContentConfig(
    temperature=0.7,       # Creativity level (0-2, higher = more creative)
    top_p=0.9,             # Sampling range
    top_k=40,              # Candidate token count
    max_output_tokens=1024 # Maximum output length
)

response = client.models.generate_content(
    model="gemini-3.6-flash",
    contents="Write a short poem about a rainy day in Taipei",
    config=config
)

Parameter recommendations:

Scenariotemperaturetop_pDescription
Translation, summarization0.1-0.30.8Accuracy needed
General Q&A0.5-0.70.9Balance creativity and accuracy
Creative writing1.0-1.50.95Diversity needed

Multi-Turn Conversation

chat = client.chats.create(model="gemini-3.6-flash")

response = chat.send_message("Hi! I want to learn Python")
print(response.text)

response = chat.send_message("Can you recommend some beginner books?")
print(response.text)

client.chats.create() automatically maintains conversation history -- you don't need to manage context manually.

Purchase Gemini API through CloudInsight for exclusive enterprise discounts and uniform invoices. Learn about enterprise plans

Gemini API multimodal input processing flow


Multimodal Applications: Image Understanding & Video Analysis

Answer-First: Gemini API natively supports multimodal input -- you can send text + images (or video) simultaneously, letting AI understand visual content and generate text responses.

Image Understanding

import PIL.Image

# Load local image
img = PIL.Image.open("receipt.jpg")

# Send image + text prompt
response = client.models.generate_content(
    model="gemini-3.6-flash",
    contents=[
        "Please identify the item names and amounts on this receipt, output in table format",
        img
    ]
)

print(response.text)

Supported image formats: JPEG, PNG, GIF, WebP. Maximum 20MB per image.

Multi-Image Comparison

img1 = PIL.Image.open("product_a.jpg")
img2 = PIL.Image.open("product_b.jpg")

response = client.models.generate_content(
    model="gemini-3.6-flash",
    contents=[
        "Compare the visual differences between these two products",
        img1,
        img2
    ]
)

Video Analysis

Gemini API supports direct video file uploads:

video_file = client.files.upload(file="demo.mp4")

# Wait for file processing to complete
import time
while video_file.state.name == "PROCESSING":
    time.sleep(2)
    video_file = client.files.get(name=video_file.name)

response = client.models.generate_content(
    model="gemini-3.6-flash",
    contents=[
        "Please generate 5 key takeaways from this video",
        video_file
    ]
)

Video analysis is currently a unique Gemini API advantage -- neither OpenAI nor Claude supports direct video uploads.

But note: video analysis consumes a lot of tokens. A 1-minute video uses approximately 4,000-8,000 tokens. Long videos can get expensive.

If you also want to learn OpenAI's Python integration approach, see OpenAI API Python SDK Integration Complete Tutorial. The two APIs have different design philosophies, and learning both helps you choose the best fit for your project.


Advanced Techniques: Streaming, Function Calling & Error Handling

Answer-First: Streaming enables real-time response display, Function Calling lets AI call custom functions, and error handling ensures stable production operation. These three advanced techniques are essential for going live.

Streaming Response

Don't want to wait for AI to finish before seeing results? Use Streaming:

response = client.models.generate_content_stream(
    model="gemini-3.6-flash",
    contents="Give a detailed introduction to 5 must-visit tourist spots in Taiwan"
)

for chunk in response:
    print(chunk.text, end="", flush=True)

Streaming is especially useful for chatbot scenarios. Users don't have to stare at a blank screen waiting for the AI to finish.

Function Calling

Let AI call functions you define:

from google.genai import types

def get_weather(city: str) -> dict:
    """Get weather information for a specified city"""
    # Would actually call a weather API
    return {"city": city, "temp": 28, "condition": "Sunny"}

# Hand the Python function to the SDK to enable automatic Function Calling
chat = client.chats.create(
    model="gemini-3.6-flash",
    config=types.GenerateContentConfig(tools=[get_weather])
)
response = chat.send_message("What's the weather like in Taipei today?")

Gemini automatically determines when to call get_weather and passes the correct city parameter.

Error Handling

Error handling is a must for production environments:

from google.genai import errors

try:
    response = client.models.generate_content(
        model="gemini-3.6-flash",
        contents="Your Prompt"
    )
    print(response.text)
except errors.ClientError as e:
    # 4xx client-side errors (e.g. 429 rate limit, 400 bad params, 403 permission)
    print(f"Client error ({e.code}): {e.message}")
except errors.ServerError as e:
    # 5xx server-side errors
    print(f"Server error ({e.code}): {e.message}")
except Exception as e:
    print(f"Unknown error: {e}")

Common error codes:

Error CodeCauseSolution
429Rate limit exceededAdd retry logic with increasing intervals
400Invalid request formatCheck Prompt and parameters
403Invalid API KeyConfirm Key is correct and active
500Server-side errorRetry later

API error handling flow


Next Steps: From Practice to Production

You've now learned the complete Gemini API Python integration process.

But there are several things to keep in mind between "it runs" and "it's live":

  • API Key security: Never commit to Git; use environment variables or Secret Manager. For more security tips, see API Key Management & Security Best Practices
  • Cost monitoring: Set daily usage limits to avoid unexpected overcharges. For cost differences across APIs, see AI API Pricing Comparison Complete Guide
  • Model selection: Use the Flash family for development testing (cheap), choose a Pro-tier model for production based on quality needs; the current model lineup and rates are per the official Gemini API pricing page (the Gemini 2.0 series was shut down on 2026-06-01 -- don't specify gemini-2.0-* any more)
  • Rate limits: Implement exponential backoff retry mechanisms

For a comprehensive look at Gemini API features and pricing, see Gemini API Complete Development Guide.

If you have broader interest in Python AI development, Python AI API Integration Beginner's Tutorial covers common concepts and comparisons across providers. For a deeper look at pricing differences, AI API Pricing Comparison Complete Guide is very helpful.

Need an enterprise-grade Gemini API plan? CloudInsight offers bulk token purchase discounts, uniform invoices, and Chinese technical support. Get an enterprise quote now, or join LINE Official Account for instant technical support.

FAQ

Q1: Which endpoint should I call Gemini through -- Google AI Studio or Vertex AI?

The SDK is now unified as google-genai; the only difference is which endpoint you target. The old google-generativeai is no longer maintained; Google launched the unified google-genai SDK in 2025 supporting both backends, and new projects should use it exclusively. (1) Google AI Studio endpoint (recommended for beginners) — client = genai.Client(api_key='YOUR_API_KEY'), calls generativelanguage.googleapis.com, needs only API key auth, best for personal / prototype development; example: client.models.generate_content(model='gemini-3.6-flash', contents=...). (2) Vertex AI endpointclient = genai.Client(vertexai=True, project='my-project', location='us-central1'), requires GCP account and Application Default Credentials, suits enterprise production. Selection principles: (A) personal / learning / prototyping → AI Studio endpoint; (B) company commercial product, need audit logs, data protection → Vertex AI endpoint; (C) already on GCP, want unified IAM management → Vertex AI endpoint. Migration notes: it's the same google-genai SDK — the two endpoints differ only in the genai.Client() initialization parameters, the generate_content() call is identical, so switching takes just one line.

Q2: How to implement streaming response? How to send to frontend with Flask / FastAPI?

Gemini SDK supports streaming; combining with SSE (Server-Sent Events) to frontend is most common. Python implementation: response = client.models.generate_content_stream(model='gemini-3.6-flash', contents=prompt)for chunk in response: print(chunk.text). FastAPI + SSE complete example: (1) Backend: from fastapi.responses import StreamingResponse; async def generate(): for chunk in response: yield f"data: {chunk.text}\n\n"; return StreamingResponse(generate(), media_type="text/event-stream"); (2) Frontend: const eventSource = new EventSource('/api/chat'); eventSource.onmessage = (e) => { document.getElementById('output').innerText += e.data; }. Flask version: similar but uses yield + Response(stream_with_context(...), mimetype='text/event-stream'). Considerations: (1) CORS headers — SSE may be blocked by browsers; (2) Timeout — some reverse proxies (nginx) default 60-second timeout, set longer for long responses; (3) Error handling — handle mid-stream breaks gracefully, don't silently fail; (4) Testing — use curl -N http://localhost:8000/chat to test streaming. When not to use streaming: (A) structured output (JSON mode) doesn't need streaming, wait for completion then parse; (B) short responses (<100 tokens) — streaming adds complexity > benefits.

Q3: What's the safest API Key management approach? How to handle different environments (dev/staging/prod)?

Three-stage security upgrade. (1) Absolutely don't do: (A) hardcode in code, (B) commit to git, (C) place in frontend JavaScript (visible to users), (D) paste in Slack / email. (2) Basic approach (personal / small projects): (A) .env file + .gitignoreGEMINI_API_KEY=xxx in .env, code uses os.getenv(); (B) use python-dotenvfrom dotenv import load_dotenv; load_dotenv(). (3) Advanced approach (teams / production): (A) GCP Secret Managerfrom google.cloud import secretmanager; client.access_secret_version(...); (B) AWS Secrets Manager / Azure Key Vault — similar; (C) Environment variable injection — Kubernetes Secrets, Cloud Run env vars, GitHub Actions secrets. Managing across environments: (A) dev: personal API keys (one per person, lower quotas); (B) staging: shared test key with domain whitelist; (C) prod: production key in Secret Manager + rotation policy (90-day rotation); (D) CI/CD: GitHub Secrets, GCP Secret Manager — never hardcode. Leak emergency response: (1) Immediately revoke key (one-click in AI Studio / GCP console); (2) Rotate keys in all applications; (3) Check logs for abnormal usage; (4) Clean git history (use BFG Repo-Cleaner). Google auto-scans GitHub and disables detected Gemini API keys, but don't rely on this alone.

Q4: Got hit with rate limits — what's the strategy for handling 429 errors?

Exponential backoff + Retry is the gold standard. Gemini API rate limits depend on your account's usage tier, and Google no longer publishes fixed numbers: check the official Rate Limits doc for the current per-minute and per-day caps, or log in to AI Studio's rate limit page to see your own account's live quota. Python implementation: from tenacity import retry, stop_after_attempt, wait_exponential; @retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=2, max=60)) def call_gemini(): response = client.models.generate_content(model='gemini-3.6-flash', contents=...); return response. Or Google's native google.api_core.retry. Prevention strategies: (1) Caching identical queries — store in Redis for 60 minutes; (2) Batch API — move non-real-time tasks to the Batch API (its discount and quota are per the official pricing page); (3) Queue requests — use Celery / RQ for unified scheduling; (4) Multi-project distribution — each GCP project has independent quota, linearly scales (but requires payment); (5) Upgrade Tier — sustained usage auto-upgrades; or file a request to accelerate. Monitoring: set Cloud Monitoring alerts at 80% quota threshold to add capacity proactively.

Q5: For long documents (100-page PDFs, 1-hour videos), can Gemini's context really handle it?

Yes, but watch cost and strategy. Current Gemini models all offer long context, with the exact ceiling varying by model (see the official model docs); a 100-page PDF or a 1-hour video can be fed in one shot. How: upload with client.files.upload(file='report.pdf') and reference it in the prompt; same for video via client.files.upload(file='video.mp4'). Sizing the cost: long documents and video produce a lot of tokens (a 1-hour video can reach hundreds of thousands of tokens depending on resolution), and your bill is token count x that model's rate — look the rate up on the official Gemini API pricing page and measure with client.models.count_tokens(model='gemini-3.6-flash', contents=prompt) before going live instead of guessing. Practical strategies: (1) Context Caching — when querying the same long document repeatedly, enable cached_content; the cache-hit discount is per the official pricing page; (2) Don't blindly stuff full text — chunking + retrieval (RAG) is sometimes cheaper for specific use cases; (3) Chunk summarize then analyze — summarize each chapter first, then analyze overall; necessary once you exceed a single context window; (4) File API reuse — upload once, reference multiple times without re-upload until expiration; (5) Watch token count — re-estimate every time the prompt changes. Limitations (per the official File API docs): uploaded files have a retention period, single files have a size cap, and the context ceiling differs by model.


References

  1. Google AI for Developers -- Gemini API Quickstart with Python (https://ai.google.dev/gemini-api/docs/quickstart?lang=python)
  2. google-genai PyPI package (https://pypi.org/project/google-genai/)
  3. Gemini API Cookbook -- GitHub (https://github.com/google-gemini/cookbook)
  4. Google AI Studio (https://aistudio.google.com)

Need Professional Cloud Advice?

Whether you're evaluating cloud platforms, optimizing existing architecture, or looking for cost-saving solutions, we can help

Book Free Consultation

Related Articles