Complete Google Gemini API Tutorial with Python: From Basics to Advanced

# Tutorial Lengkap Google Gemini API dengan Python: Dari Dasar hingga Mahir Google Gemini API adalah salah satu API AI paling powerful yang tersedia saat ini. Dengan kemampuan multimodal — memproses...

By Ruby Abdullah · · tutorial
Gemini APIGoogle AILLMMultimodal AIPython

Complete Google Gemini API Tutorial with Python: From Basics to Advanced

Google Gemini API is one of the most powerful AI APIs available today. With native multimodal capabilities — processing text, images, audio, and video — Gemini provides exceptional flexibility for building modern AI applications. This tutorial will guide you from installation to advanced usage of the Gemini API using Python.

Why Google Gemini API?

Gemini API offers several advantages that make it worth learning:

  • Native Multimodal: Unlike many other LLMs that only process text, Gemini is designed from the ground up to understand text, images, audio, and video simultaneously
  • Large Context Window: Gemini 2.5 Pro supports context windows up to 1 million tokens, enabling analysis of long documents or large codebases
  • Grounding with Google Search: Ability to connect responses with real-time data from Google Search
  • Competitive Pricing: Generous free tier and competitive pricing for production use
  • Official Python SDK: Well-documented and easy-to-use google-genai library

Installation and Setup

Prerequisites

  • Python 3.9 or later
  • Google Cloud account or API key from Google AI Studio
  • pip or uv package manager

SDK Installation

pip install google-genai

Or using uv:

uv pip install google-genai

Getting Your API Key

  • Visit Google AI Studio
  • Click "Get API Key" in the sidebar menu
  • Select "Create API key in new project" or choose an existing project
  • Copy the generated API key
  • Environment Configuration

    Store your API key as an environment variable for security:

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

    Or create a .env file:

    GOOGLEAPIKEY=your-api-key-here
    

    Basic Usage: Text Generation

    Hello Gemini

    from google import genai
    
    

    client = genai.Client(apikey="YOURAPIKEY")

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="Explain what machine learning is in 3 sentences."

    )

    print(response.text)

    Example output:

    Machine learning is a branch of artificial intelligence that enables 
    

    computers to learn from data without being explicitly programmed. ML

    algorithms identify patterns in training data and use those patterns

    to make predictions or decisions on new data. This technique is widely

    used in various applications such as image recognition, natural language

    processing, and recommendation systems.

    Choosing the Right Model

    Google provides several Gemini models:

    | Model | Strength | Use Case |

    |-------|----------|----------|

    | gemini-2.5-pro | Most capable, best reasoning | Complex tasks, coding, analysis |

    | gemini-2.5-flash | Fast and efficient | Chat, summarization, general tasks |

    | gemini-2.0-flash | Balanced speed/quality | Production workloads |

    models = client.models.list()
    

    for model in models:

    print(f"{model.name}: {model.displayname}")

    Generation Configuration

    You can control model behavior with parameters:

    from google.genai import types
    
    

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="Write a poem about artificial intelligence.",

    config=types.GenerateContentConfig(

    temperature=0.7,

    topp=0.9,

    topk=40,

    maxoutputtokens=500,

    )

    )

    print(response.text)

    Key parameters:

    • temperature (0.0-2.0): Higher values produce more creative output, lower values are more deterministic
    • topp: Nucleus sampling, controls output diversity
    • topk: Number of top candidate tokens to consider
    • maxoutputtokens: Maximum response length

    Multimodal: Processing Images

    Analyzing Images from Files

    from google import genai
    

    from google.genai import types

    from pathlib import Path

    client = genai.Client(apikey="YOURAPIKEY")

    imagepath = Path("photo.jpg")

    imagebytes = imagepath.readbytes()

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents=[

    types.Part.frombytes(

    data=imagebytes,

    mimetype="image/jpeg"

    ),

    "Describe this image in detail."

    ]

    )

    print(response.text)

    Analyzing Images from URLs

    from google import genai
    

    from google.genai import types

    client = genai.Client(apikey="YOURAPIKEY")

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents=[

    types.Part.fromuri(

    fileuri="https://example.com/image.jpg",

    mimetype="image/jpeg"

    ),

    "What is in this image?"

    ]

    )

    print(response.text)

    Comparing Multiple Images

    from google import genai
    

    from google.genai import types

    from pathlib import Path

    client = genai.Client(apikey="YOURAPIKEY")

    image1 = types.Part.frombytes(

    data=Path("chartq1.png").readbytes(),

    mimetype="image/png"

    )

    image2 = types.Part.frombytes(

    data=Path("chartq2.png").readbytes(),

    mimetype="image/png"

    )

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents=[

    image1,

    image2,

    "Compare these two charts. What are the main trends?"

    ]

    )

    print(response.text)

    Chat and Conversation

    Multi-turn Conversation

    from google import genai
    

    from google.genai import types

    client = genai.Client(apikey="YOURAPIKEY")

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

    response1 = chat.sendmessage("I'm learning Python. Where should I start?")

    print(f"Gemini: {response1.text}\n")

    response2 = chat.sendmessage("Can you suggest a simple project for beginners?")

    print(f"Gemini: {response2.text}\n")

    response3 = chat.sendmessage("What about web scraping? Is it suitable for beginners?")

    print(f"Gemini: {response3.text}")

    Chat with System Instructions

    from google import genai
    

    from google.genai import types

    client = genai.Client(apikey="YOURAPIKEY")

    chat = client.chats.create(

    model="gemini-2.5-flash",

    config=types.GenerateContentConfig(

    systeminstruction="You are an expert data science assistant. "

    "Answer questions with practical Python code examples. "

    "Keep explanations clear and concise."

    )

    )

    response = chat.sendmessage(

    "How do I perform feature engineering for tabular data?"

    )

    print(response.text)

    Streaming Responses

    For long responses, streaming provides a better user experience:

    from google import genai
    
    

    client = genai.Client(apikey="YOURAPIKEY")

    response = client.models.generatecontentstream(

    model="gemini-2.5-flash",

    contents="Write a comprehensive guide about Docker for data scientists."

    )

    for chunk in response:

    print(chunk.text, end="", flush=True)

    print()

    Async Streaming

    import asyncio
    

    from google import genai

    async def streamresponse():

    client = genai.Client(apikey="YOURAPIKEY")

    async for chunk in client.aio.models.generatecontentstream(

    model="gemini-2.5-flash",

    contents="Explain the Transformer architecture step by step."

    ):

    print(chunk.text, end="", flush=True)

    print()

    asyncio.run(streamresponse())

    Advanced Usage: Structured Output

    JSON Mode

    Force Gemini to produce valid JSON output:

    from google import genai
    

    from google.genai import types

    client = genai.Client(apikey="YOURAPIKEY")

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="List 5 Python libraries for data science with brief descriptions.",

    config=types.GenerateContentConfig(

    responsemimetype="application/json"

    )

    )

    import json

    data = json.loads(response.text)

    print(json.dumps(data, indent=2))

    Schema-based Structured Output

    Using Pydantic to define output schemas:

    from google import genai
    

    from google.genai import types

    from pydantic import BaseModel

    class BookRecommendation(BaseModel):

    title: str

    author: str

    genre: str

    rating: float

    summary: str

    class BookList(BaseModel):

    books: list[BookRecommendation]

    client = genai.Client(apikey="YOURAPIKEY")

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="Recommend 3 books about machine learning for beginners.",

    config=types.GenerateContentConfig(

    responsemimetype="application/json",

    responseschema=BookList

    )

    )

    booklist = BookList.modelvalidatejson(response.text)

    for book in booklist.books:

    print(f"Title: {book.title} by {book.author}")

    print(f" Genre: {book.genre} | Rating: {book.rating}")

    print(f" {book.summary}\n")

    Function Calling (Tool Use)

    Function calling enables Gemini to invoke your Python functions:

    from google import genai
    

    from google.genai import types

    def getweather(city: str, unit: str = "celsius") -> dict:

    """Get weather information for a specific city."""

    weatherdata = {

    "New York": {"temp": 22, "condition": "Partly cloudy", "humidity": 65},

    "London": {"temp": 16, "condition": "Overcast", "humidity": 80},

    "Tokyo": {"temp": 28, "condition": "Sunny", "humidity": 70},

    }

    data = weatherdata.get(city, {"temp": 25, "condition": "Unknown", "humidity": 50})

    return {

    "city": city,

    "temperature": data["temp"],

    "unit": unit,

    "condition": data["condition"],

    "humidity": data["humidity"]

    }

    def getpopulation(city: str) -> dict:

    """Get population information for a city."""

    populations = {

    "New York": 8336000,

    "London": 8982000,

    "Tokyo": 13960000,

    }

    return {"city": city, "population": populations.get(city, 0)}

    client = genai.Client(apikey="YOURAPIKEY")

    tools = [

    types.Tool(functiondeclarations=[

    types.FunctionDeclaration.fromcallable(getweather),

    types.FunctionDeclaration.fromcallable(getpopulation),

    ])

    ]

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="What's the weather in Tokyo today and what's its population?",

    config=types.GenerateContentConfig(tools=tools)

    )

    for part in response.candidates[0].content.parts:

    if part.functioncall:

    funcname = part.functioncall.name

    funcargs = dict(part.functioncall.args)

    print(f"Calling {funcname}({funcargs})")

    if funcname == "getweather":

    result = getweather(funcargs)

    elif funcname == "getpopulation":

    result = getpopulation(funcargs)

    print(f"Result: {result}")

    Automatic Function Calling

    The Gemini SDK supports automatic function execution:

    from google import genai
    

    from google.genai import types

    client = genai.Client(apikey="YOURAPIKEY")

    def calculatebmi(weightkg: float, heightcm: float) -> dict:

    """Calculate a person's BMI."""

    heightm = heightcm / 100

    bmi = weightkg / (heightm * 2)

    if bmi < 18.5:

    category = "Underweight"

    elif bmi < 25:

    category = "Normal"

    elif bmi < 30:

    category = "Overweight"

    else:

    category = "Obese"

    return {"bmi": round(bmi, 1), "category": category}

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="Calculate the BMI for a person weighing 70kg and 175cm tall.",

    config=types.GenerateContentConfig(

    tools=[calculatebmi],

    automaticfunctioncalling=types.AutomaticFunctionCallingConfig(

    disable=False

    )

    )

    )

    print(response.text)

    Connect Gemini responses with real-time data:

    from google import genai
    

    from google.genai import types

    client = genai.Client(apikey="YOURAPIKEY")

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="What are the latest AI technology news this week?",

    config=types.GenerateContentConfig(

    tools=[types.Tool(googlesearch=types.GoogleSearch())]

    )

    )

    print(response.text)

    if response.candidates[0].groundingmetadata:

    print("\nSources:")

    for chunk in response.candidates[0].groundingmetadata.groundingchunks:

    if chunk.web:

    print(f" - {chunk.web.title}: {chunk.web.uri}")

    File API: Upload and Analyze Files

    Uploading Files

    from google import genai
    
    

    client = genai.Client(apikey="YOURAPIKEY")

    uploadedfile = client.files.upload(file="report.pdf")

    print(f"File uploaded: {uploadedfile.name}")

    print(f"URI: {uploadedfile.uri}")

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents=[

    uploadedfile,

    "Create a summary of this document in 5 key points."

    ]

    )

    print(response.text)

    Video Analysis

    from google import genai
    

    import time

    client = genai.Client(apikey="YOURAPIKEY")

    videofile = client.files.upload(file="presentation.mp4")

    while videofile.state.name == "PROCESSING":

    print("Processing video...")

    time.sleep(5)

    videofile = client.files.get(name=videofile.name)

    if videofile.state.name == "ACTIVE":

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents=[

    videofile,

    "Analyze this presentation video. What are the main points discussed?"

    ]

    )

    print(response.text)

    Safety Settings

    Configure safety filters:

    from google import genai
    

    from google.genai import types

    client = genai.Client(apikey="YOURAPIKEY")

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="Explain common cybersecurity risks.",

    config=types.GenerateContentConfig(

    safetysettings=[

    types.SafetySetting(

    category="HARMCATEGORYDANGEROUSCONTENT",

    threshold="BLOCKONLYHIGH"

    ),

    types.SafetySetting(

    category="HARMCATEGORYHARASSMENT",

    threshold="BLOCKMEDIUMANDABOVE"

    )

    ]

    )

    )

    print(response.text)

    Embedding Generation

    Gemini also supports text embeddings for semantic search and RAG:

    from google import genai
    
    

    client = genai.Client(apikey="YOURAPIKEY")

    result = client.models.embedcontent(

    model="text-embedding-004",

    contents=[

    "Machine learning is a subset of AI.",

    "Deep learning uses multi-layered neural networks.",

    "Data engineering focuses on data pipelines.",

    ]

    )

    for i, embedding in enumerate(result.embeddings):

    print(f"Text {i+1}: dimensions={len(embedding.values)}, "

    f"preview={embedding.values[:5]}")

    import numpy as np
    

    from google import genai

    client = genai.Client(apikey="YOURAPIKEY")

    documents = [

    "Python is a popular programming language for data science.",

    "TensorFlow is a deep learning framework made by Google.",

    "Docker simplifies application deployment in containers.",

    "Kubernetes orchestrates containers at scale.",

    "Pandas is a Python library for tabular data manipulation.",

    ]

    query = "Library for data analysis"

    alltexts = documents + [query]

    result = client.models.embedcontent(

    model="text-embedding-004",

    contents=alltexts

    )

    embeddings = [np.array(e.values) for e in result.embeddings]

    queryembedding = embeddings[-1]

    docembeddings = embeddings[:-1]

    similarities = []

    for i, docemb in enumerate(docembeddings):

    similarity = np.dot(queryembedding, docemb) / (

    np.linalg.norm(queryembedding) np.linalg.norm(docemb)

    )

    similarities.append((similarity, documents[i]))

    similarities.sort(reverse=True)

    print(f"Query: {query}\n")

    for score, doc in similarities:

    print(f" [{score:.4f}] {doc}")

    Example Project: AI-Powered Document Analyzer

    Here's a complete application that combines several Gemini features:

    from google import genai
    

    from google.genai import types

    from pydantic import BaseModel

    from pathlib import Path

    class DocumentAnalysis(BaseModel):

    title: str

    summary: str

    keypoints: list[str]

    sentiment: str

    language: str

    wordcountestimate: int

    topics: list[str]

    class DocumentAnalyzer:

    def init(self, apikey: str):

    self.client = genai.Client(apikey=apikey)

    self.model = "gemini-2.5-flash"

    def analyzetext(self, text: str) -> DocumentAnalysis:

    response = self.client.models.generatecontent(

    model=self.model,

    contents=f"Analyze the following document thoroughly:\n\n{text}",

    config=types.GenerateContentConfig(

    responsemimetype="application/json",

    responseschema=DocumentAnalysis

    )

    )

    return DocumentAnalysis.modelvalidatejson(response.text)

    def analyzepdf(self, pdfpath: str) -> DocumentAnalysis:

    uploaded = self.client.files.upload(file=pdfpath)

    response = self.client.models.generatecontent(

    model=self.model,

    contents=[

    uploaded,

    "Analyze this PDF document thoroughly."

    ],

    config=types.GenerateContentConfig(

    responsemimetype="application/json",

    responseschema=DocumentAnalysis

    )

    )

    return DocumentAnalysis.modelvalidatejson(response.text)

    def comparedocuments(self, doc1: str, doc2: str) -> str:

    response = self.client.models.generatecontent(

    model=self.model,

    contents=f"""Compare the following two documents:

    Document 1:

    {doc1}

    Document 2:

    {doc2}

    Provide a comparison analysis covering similarities, differences,

    and recommendations."""

    )

    return response.text

    def summarizewithsources(self, text: str) -> str:

    response = self.client.models.generatecontent(

    model=self.model,

    contents=f"Summarize the following text and verify key facts:\n\n{text}",

    config=types.GenerateContentConfig(

    tools=[types.Tool(googlesearch=types.GoogleSearch())]

    )

    )

    return response.text

    analyzer = DocumentAnalyzer(apikey="YOURAPIKEY")

    sampletext = """

    Artificial Intelligence has transformed how companies operate.

    From business process automation to predictive analytics, AI provides

    significant competitive advantages. Companies that strategically adopt

    AI technology report an average 40% improvement in operational

    efficiency within the first two years of implementation.

    """

    analysis = analyzer.analyzetext(sampletext)

    print(f"Title: {analysis.title}")

    print(f"Summary: {analysis.summary}")

    print(f"Sentiment: {analysis.sentiment}")

    print(f"Topics: {', '.join(analysis.topics)}")

    print(f"\nKey Points:")

    for point in analysis.keypoints:

    print(f" - {point}")

    Best Practices

    1. Robust Error Handling

    from google import genai
    

    from google.genai import errors

    client = genai.Client(apikey="YOURAPIKEY")

    try:

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="Hello, Gemini!"

    )

    print(response.text)

    except errors.ClientError as e:

    print(f"Client error: {e}")

    except errors.ServerError as e:

    print(f"Server error (retry later): {e}")

    except Exception as e:

    print(f"Unexpected error: {e}")

    2. Rate Limiting and Retry

    import time
    

    from google import genai

    from google.genai import errors

    client = genai.Client(apikey="YOURAPIKEY")

    def generatewithretry(prompt: str, maxretries: int = 3) -> str:

    for attempt in range(maxretries):

    try:

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents=prompt

    )

    return response.text

    except errors.ServerError:

    if attempt < maxretries - 1:

    waittime = 2 * attempt

    print(f"Rate limited. Waiting {waittime}s...")

    time.sleep(waittime)

    else:

    raise

    return ""

    3. Token Counting

    from google import genai
    
    

    client = genai.Client(apikey="YOURAPIKEY")

    response = client.models.counttokens(

    model="gemini-2.5-flash",

    contents="Count how many tokens this text uses."

    )

    print(f"Total tokens: {response.totaltokens}")

    4. Caching for Cost Efficiency

    from google import genai
    

    from google.genai import types

    client = genai.Client(apikey="YOURAPIKEY")

    longdocument = "..." 10000 # Long document

    cache = client.caches.create(

    model="gemini-2.5-flash",

    contents=[longdocument],

    config=types.CreateCachedContentConfig(

    displayname="my-document-cache",

    ttl="3600s"

    )

    )

    response = client.models.generatecontent(

    model="gemini-2.5-flash",

    contents="What is the main theme of this document?",

    config=types.GenerateContentConfig(

    cachedcontent=cache.name

    )

    )

    print(response.text)

    5. API Key Security

    import os
    

    from google import genai

    apikey = os.environ.get("GOOGLEAPIKEY")

    if not apikey:

    raise ValueError("GOOGLEAPIKEY environment variable not set")

    client = genai.Client(apikey=api_key)

    Pricing Comparison

    | Model | Input (per 1M tokens) | Output (per 1M tokens) |

    |-------|----------------------|----------------------|

    | Gemini 2.5 Pro | $1.25 - $10.00 | $10.00 - $30.00 |

    | Gemini 2.5 Flash | $0.15 - $0.60 | $0.60 - $3.50 |

    | Gemini 2.0 Flash | $0.10 | $0.40 |

    Free tier available with limits:

    • 15 RPM (requests per minute) for Gemini 2.5 Flash
    • 2 RPM for Gemini 2.5 Pro
    • 1,500 requests per day

    Conclusion

    Google Gemini API is a powerful tool for building AI applications. With its multimodal capabilities, large context window, and intuitive Python SDK, Gemini is suitable for a wide range of use cases from simple chatbots to complex document analysis systems.

    Key takeaways to remember:

  • Start with Gemini Flash for development and prototyping as it's faster and cheaper
  • Use structured output with Pydantic schemas to get consistent data
  • Leverage function calling to integrate Gemini with your existing systems
  • Implement error handling and retry logic for production readiness
  • Use caching to reduce costs when analyzing the same documents repeatedly
  • Always store API keys as environment variables, never hardcode them
  • By following this tutorial, you now have a solid foundation for building AI applications using the Google Gemini API. Next steps include exploring advanced features like the Live API for real-time interactions, or combining Gemini with frameworks like LangChain or LlamaIndex to build more sophisticated RAG systems.

    Related Articles

    Complete Aisuite Tutorial: Unified Multi-LLM Interface by Andrew Ng

    Tutorial Lengkap Aisuite: Unified Multi-LLM Interface dari Andrew Ng Apa itu Aisuite? Aisuite adalah library Python open...

    Complete Jupyter AI Tutorial: Integrate LLMs Directly Into Your Notebooks

    Tutorial Lengkap Jupyter AI: Integrasikan LLM Langsung ke Notebook Anda Jupyter Notebook telah menjadi alat utama bagi d...

    Complete Anthropic Claude API Tutorial: From Basics to Advanced Features

    Tutorial Lengkap Anthropic Claude API: Dari Dasar hingga Fitur Lanjutan Anthropic Claude adalah salah satu Large Languag...

    ScrapeGraphAI Tutorial: Intelligent Web Scraping with LLMs and Graph Logic

    Tutorial ScrapeGraphAI: Web Scraping Cerdas dengan LLM dan Graph Logic Pendahuluan Web scraping adalah salah satu teknik...