GeminiBeginner

How to Call the Gemini API from Python

Install the google-genai SDK and generate text from Gemini in a few lines of Python.

7 minBeginner

When you want Gemini inside a script or app rather than the terminal, the official Python SDK is the cleanest route. The package is google-genai, and it reads your API key from the environment so no secrets end up in code. This guide gets a first generation working.

What you need

  • Python 3.9 or newer
  • A Gemini API key in the GEMINI_API_KEY environment variable
  • pip for installing packages
  • About 5 minutes

Step 1: Install the SDK

Install the google-genai package into your project, ideally inside a virtual environment so it does not pollute your system Python.

terminal
python -m venv .venv
source .venv/bin/activate
pip install google-genai

Step 2: Write a minimal script

Create a file and import the client. With no key passed explicitly, the SDK looks for GEMINI_API_KEY automatically. Pick a current model such as gemini-2.5-flash, which is fast and inexpensive for everyday work.

ask.py
from google import genai

client = genai.Client()  # reads GEMINI_API_KEY from the environment

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Write a one-line git commit message for fixing a null pointer in auth.",
)

print(response.text)

Step 3: Run it

Execute the script. If the key is set correctly you get a single generated line printed to your terminal.

zsh - run
$python ask.py
fix(auth): guard against null user before reading session
$
ask.py - editor
Explorer
ask.py
.venv/
requirements.txt
ask.py
1from google import genai
2
3client = genai.Client()
4response = client.models.generate_content(
5 model="gemini-2.5-flash",
6 contents="...",
7)
8print(response.text)
The full script in your editor.
Pin the model name
Hardcoding gemini-2.5-flash is fine to start. For production, keep the model name in config so you can swap to a newer or larger model without editing code.

Result

You can now generate text from Gemini in any Python program. From here you can loop over inputs, feed it file contents, or wire it into a web handler, all on the same client.models.generate_content call.

Watch related tutorials

Tags
#python#api#sdk#google-genai#coding