Interacting with the Google Gemini API from Python

How to set up a Google account, get an API key, and query Gemini from Python.
Python
AI
Published

May 6, 2026

What is Google Gemini?

Google Gemini is Google’s AI assistant. You can talk to it from Python by sending it a prompt (a question or instruction) and it sends back a response. This post walks through everything you need to get started.

Step 1 — Create a Google Account

If you have Gmail, you already have one. If not, go to accounts.google.com and sign up.

Step 2 — Get Your API Key

  1. Go to aistudio.google.com
  2. Sign in and click “Get API Key”“Create API Key”
  3. Copy it and save it somewhere safe — treat it like a password

Step 3 — Store Your Key Safely

Never paste your key directly in the notebook. In your terminal, run:

# Run this in your terminal BEFORE opening the notebook (not as a code cell)
# Mac/Linux:  export GEMINI_API_KEY="your-key-here"
# Windows:    set GEMINI_API_KEY=your-key-here

# Install the library
!pip install google-generativeai

Step 4 — Connect to Gemini

import os
import google.generativeai as genai

genai.configure(api_key=os.environ["GEMINI_API_KEY"])
model = genai.GenerativeModel("gemini-1.5-flash")
print("Connected successfully!")

Step 5 — Send Prompts

Now we can send questions to Gemini and print the responses.

# Basic question
response = model.generate_content("What is machine learning? Explain in 3 sentences.")
print("--- Basic Question ---")
print(response.text)

# Ask it to write code
response = model.generate_content("Write a Python function that calculates the mean of a list.")
print("--- Code Generation ---")
print(response.text)

# Summarize text
text = "Pandas is a Python library for data manipulation. It provides DataFrames for working with tabular data and integrates well with NumPy and Matplotlib."
response = model.generate_content(f"Summarize this in one sentence: {text}")
print("--- Summarization ---")
print(response.text)

Step 6 — Multi-Turn Conversation

Gemini can also hold a conversation where it remembers previous messages.

chat = model.start_chat(history=[])
print("Turn 1:", chat.send_message("I'm learning Python for data science. Where should I start?").text)
print("Turn 2:", chat.send_message("What should I learn after Pandas?").text)

Summary

In this post we: - Created a Google account and obtained a Gemini API key from AI Studio - Installed google-generativeai and connected to the model safely using an environment variable - Sent basic questions, generated code, summarized text, and held a multi-turn conversation

The free tier is generous — it’s a great tool to experiment with in your data science work.