Skip to content

Connect to Gemini from Python

This guide shows the clean path for calling the Gemini API from Python:

  • install the recommended SDK
  • store the API key securely
  • send a first request
  • keep the code easy to evolve into a real application
Terminal window
python -m pip install google-genai python-dotenv

Set the key as an environment variable.

Terminal window
$env:GEMINI_API_KEY="your-api-key-here"
Terminal window
export GEMINI_API_KEY="your-api-key-here"

For local development, a .env file is also fine:

GEMINI_API_KEY=your-api-key-here
from google import genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Explain the difference between fine-tuning and RAG."
)
print(response.text)

Googleโ€™s current Gemini API documentation recommends the Google GenAI SDK. Older tutorials may still use earlier package names and older API styles. This page intentionally uses the newer recommended client shape.

import os
from dotenv import load_dotenv
from google import genai
load_dotenv()
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
  • storing the key directly in source files
  • using an outdated SDK example without checking the current recommended package
  • assuming the same model name will remain the best choice for every workload
  • keep authentication separate from business logic
  • treat model names as config, not hardcoded design decisions
  • start with a single request script before wiring Gemini into a larger app