Connect to Gemini from Python
Connect to Gemini from Python
Section titled โ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
1. Install the SDK
Section titled โ1. Install the SDKโpython -m pip install google-genai python-dotenv2. Store the API Key
Section titled โ2. Store the API KeyโSet the key as an environment variable.
Windows PowerShell
Section titled โWindows PowerShellโ$env:GEMINI_API_KEY="your-api-key-here"macOS or Linux
Section titled โmacOS or Linuxโexport GEMINI_API_KEY="your-api-key-here"For local development, a .env file is also fine:
GEMINI_API_KEY=your-api-key-here3. Make a First Request
Section titled โ3. Make a First Requestโ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)Why This Example Uses google-genai
Section titled โWhy This Example Uses google-genaiโ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.
4. Add .env Support for Local Development
Section titled โ4. Add .env Support for Local Developmentโimport osfrom dotenv import load_dotenvfrom google import genai
load_dotenv()
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))Common Mistakes
Section titled โCommon Mistakesโ- 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
Practical Advice
Section titled โPractical Adviceโ- 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