Skip to main content

Overview

The Google Gen AI SDK supports two authentication methods depending on which API you’re using:
  • Gemini Developer API: Uses API keys
  • Vertex AI API: Uses Google Cloud credentials (service accounts, Application Default Credentials)

Gemini Developer API Authentication

Using API Keys

The Gemini Developer API requires an API key for authentication.

Direct API Key

Pass the API key directly to the client:
from google import genai

client = genai.Client(api_key='GEMINI_API_KEY')

Environment Variables

Set the API key using environment variables:
# Option 1: GOOGLE_API_KEY
export GOOGLE_API_KEY='your-api-key'

# Option 2: GEMINI_API_KEY
export GEMINI_API_KEY='your-api-key'
Then initialize the client without explicit parameters:
from google import genai

client = genai.Client()
If both GOOGLE_API_KEY and GEMINI_API_KEY are set, GOOGLE_API_KEY takes precedence.

Getting an API Key

To obtain a Gemini API key:
  1. Visit Google AI Studio
  2. Sign in with your Google account
  3. Create a new API key or use an existing one
  4. Copy the API key for use in your application
Keep your API keys secure! Never commit them to version control or expose them in client-side code.

Vertex AI Authentication

Using Application Default Credentials (ADC)

Vertex AI uses Google Cloud’s Application Default Credentials for authentication. The SDK automatically discovers credentials in the following order:
  1. Environment variable GOOGLE_APPLICATION_CREDENTIALS
  2. User credentials from gcloud auth application-default login
  3. Compute Engine/App Engine/Cloud Run service account
  4. Cloud SDK credentials

Basic Vertex AI Client

from google import genai

client = genai.Client(
    vertexai=True,
    project='your-project-id',
    location='us-central1'
)

Setting Up ADC

For Local Development

Use the Google Cloud SDK to set up your credentials:
gcloud auth application-default login
This command opens a browser window for you to authenticate and stores the credentials locally.

Using a Service Account Key File

For production or automated environments, use a service account:
  1. Create a service account in the Google Cloud Console
  2. Download the JSON key file
  3. Set the environment variable:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"

Using Environment Variables

You can configure Vertex AI authentication entirely through environment variables:
export GOOGLE_GENAI_USE_VERTEXAI=true
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='us-central1'
Then create the client:
from google import genai

client = genai.Client()

Explicit Credentials

Pass credentials explicitly to the client:
from google import genai
import google.auth

credentials, project = google.auth.default()

client = genai.Client(
    vertexai=True,
    credentials=credentials,
    project='your-project-id',
    location='us-central1'
)

Service Account Credentials

Load service account credentials directly:
from google import genai
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file(
    '/path/to/service-account-key.json'
)

client = genai.Client(
    vertexai=True,
    credentials=credentials,
    project='your-project-id',
    location='us-central1'
)

Project and Location Configuration

For Vertex AI

Vertex AI requires a Google Cloud project ID and location.
project
str
required
Your Google Cloud project ID. Find it in the Google Cloud Console or by running gcloud config get-value project.
location
str
required
The Google Cloud location/region where requests will be sent (e.g., us-central1, europe-west1). See available locations.

Using Environment Variables

export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='us-central1'
from google import genai

client = genai.Client(vertexai=True)

Direct Configuration

from google import genai

client = genai.Client(
    vertexai=True,
    project='your-project-id',
    location='us-central1'
)

Custom Base URLs

For advanced use cases like API gateway proxies:
from google import genai
from google.genai import types

client = genai.Client(
    vertexai=True,
    http_options=types.HttpOptions(
        base_url='https://custom-api-gateway.com',
        headers={'Authorization': 'Bearer custom_token'}
    )
)
When using a custom base URL, you may need to bypass standard authentication checks. This is typically used for API gateway proxies or testing environments.

Quota Projects

For Vertex AI, you can specify a quota project for billing:
from google import genai
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file(
    '/path/to/service-account-key.json'
)

# Set quota project
credentials = credentials.with_quota_project('quota-project-id')

client = genai.Client(
    vertexai=True,
    credentials=credentials,
    project='your-project-id',
    location='us-central1'
)

Authentication Best Practices

Never hardcode credentials in your source code. Always use environment variables or secure secret management systems.
For production deployments:
  • Use service accounts with minimal required permissions
  • Rotate API keys and service account keys regularly
  • Use secret management services (Google Secret Manager, AWS Secrets Manager, etc.)
  • Enable audit logging for credential usage
For local development:
  • Use gcloud auth application-default login for Vertex AI
  • Store API keys in .env files (add to .gitignore)
  • Use separate credentials for development and production

IAM Permissions (Vertex AI)

For Vertex AI, ensure your credentials have the necessary IAM permissions:

Required Roles

  • Vertex AI User (roles/aiplatform.user) - For making API calls
  • Storage Object Viewer (roles/storage.objectViewer) - For accessing files in Cloud Storage

Grant Permissions

# Grant Vertex AI User role
gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
    --member="serviceAccount:SERVICE_ACCOUNT_EMAIL" \
    --role="roles/aiplatform.user"

# Grant Storage Object Viewer role (if using Cloud Storage)
gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
    --member="serviceAccount:SERVICE_ACCOUNT_EMAIL" \
    --role="roles/storage.objectViewer"

Troubleshooting

Common Issues

”API key not valid”

  • Verify your API key is correct
  • Check if the API key has been restricted to specific APIs
  • Ensure the Gemini API is enabled for your API key

”Permission denied” (Vertex AI)

  • Verify your credentials have the required IAM roles
  • Check if the Vertex AI API is enabled in your project:
gcloud services enable aiplatform.googleapis.com --project=YOUR_PROJECT_ID

“Could not find default credentials”

  • Set up Application Default Credentials:
gcloud auth application-default login
  • Or set GOOGLE_APPLICATION_CREDENTIALS environment variable

”Invalid project ID”

  • Verify your project ID is correct
  • Ensure billing is enabled for your project
  • Check that you have access to the project

Environment Variable Reference

Gemini Developer API

VariableDescriptionExample
GOOGLE_API_KEYGemini API key (takes precedence)AIza...
GEMINI_API_KEYAlternative Gemini API keyAIza...

Vertex AI

VariableDescriptionExample
GOOGLE_GENAI_USE_VERTEXAIEnable Vertex AI modetrue
GOOGLE_CLOUD_PROJECTGoogle Cloud project IDmy-project-123
GOOGLE_CLOUD_LOCATIONGoogle Cloud locationus-central1
GOOGLE_APPLICATION_CREDENTIALSPath to service account key/path/to/key.json

Build docs developers (and LLMs) love