Friday, May 29, 2026

How does Google Gemini Client accesses the API Key?

See All on GenAI    « Previously

Gemini said

When you instantiate genai.Client() without passing any arguments, the Google GenAI SDK automatically looks for your API key in your system's environment variables.

Specifically, it checks for these two variables:

  1. GEMINI_API_KEY (Recommended)

  2. GOOGLE_API_KEY (Supported as a fallback or for legacy compatibility)

If it finds either of these variables, it automatically injects the key into the client. If both happen to be set, GOOGLE_API_KEY takes precedence.

Why do it this way?

This is a standard security best practice. By relying on environment variables rather than explicitly passing the key like genai.Client(api_key="YOUR_KEY"), you avoid hardcoding sensitive credentials directly into your source code, preventing accidental leaks if you push your code to a public repository like GitHub.

How to set the environment variable

To make this code work on your machine, you need to set the variable before running your script.

On Mac/Linux (Terminal):

Bash
export GEMINI_API_KEY="your_api_key_here"
python your_script.py

On Windows (Command Prompt):

DOS
set GEMINI_API_KEY=your_api_key_here
python your_script.py

Alternatively, in Python (using python-dotenv): If you are using a .env file to manage your secrets, you can load it before calling the client:

Python
import os
from dotenv import load_dotenv
from google import genai

# This loads the GEMINI_API_KEY from your .env file into the environment
load_dotenv() 

client = genai.Client()
response = client.models.generate_content(
    model="gemini-3.5-flash",
    contents="Explain how AI works in a few words"
)
print(response.text)

See All on GenAI    « Previously

No comments:

Post a Comment