> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/googleapis/python-genai/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Learn how to authenticate with the Gemini Developer API and Vertex AI

## 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:

```python theme={null}
from google import genai

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

#### Environment Variables

Set the API key using environment variables:

```bash theme={null}
# 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:

```python theme={null}
from google import genai

client = genai.Client()
```

<Note>
  If both `GOOGLE_API_KEY` and `GEMINI_API_KEY` are set, `GOOGLE_API_KEY` takes precedence.
</Note>

### Getting an API Key

To obtain a Gemini API key:

1. Visit [Google AI Studio](https://aistudio.google.com/app/apikey)
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

<Warning>
  Keep your API keys secure! Never commit them to version control or expose them in client-side code.
</Warning>

## 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

```python theme={null}
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:

```bash theme={null}
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:

```bash theme={null}
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account-key.json"
```

### Using Environment Variables

You can configure Vertex AI authentication entirely through environment variables:

```bash theme={null}
export GOOGLE_GENAI_USE_VERTEXAI=true
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='us-central1'
```

Then create the client:

```python theme={null}
from google import genai

client = genai.Client()
```

### Explicit Credentials

Pass credentials explicitly to the client:

```python theme={null}
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:

```python theme={null}
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.

<ParamField path="project" type="str" required>
  Your Google Cloud project ID. Find it in the [Google Cloud Console](https://console.cloud.google.com/)
  or by running `gcloud config get-value project`.
</ParamField>

<ParamField path="location" type="str" required>
  The Google Cloud location/region where requests will be sent (e.g., `us-central1`, `europe-west1`).
  See [available locations](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations).
</ParamField>

### Using Environment Variables

```bash theme={null}
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='us-central1'
```

```python theme={null}
from google import genai

client = genai.Client(vertexai=True)
```

### Direct Configuration

```python theme={null}
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:

```python theme={null}
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'}
    )
)
```

<Note>
  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.
</Note>

## Quota Projects

For Vertex AI, you can specify a quota project for billing:

```python theme={null}
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

<Warning>
  **Never hardcode credentials** in your source code. Always use environment variables
  or secure secret management systems.
</Warning>

<Note>
  **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
</Note>

<Note>
  **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
</Note>

## 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

```bash theme={null}
# 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:

```bash theme={null}
gcloud services enable aiplatform.googleapis.com --project=YOUR_PROJECT_ID
```

#### "Could not find default credentials"

* Set up Application Default Credentials:

```bash theme={null}
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

| Variable         | Description                       | Example   |
| ---------------- | --------------------------------- | --------- |
| `GOOGLE_API_KEY` | Gemini API key (takes precedence) | `AIza...` |
| `GEMINI_API_KEY` | Alternative Gemini API key        | `AIza...` |

### Vertex AI

| Variable                         | Description                 | Example             |
| -------------------------------- | --------------------------- | ------------------- |
| `GOOGLE_GENAI_USE_VERTEXAI`      | Enable Vertex AI mode       | `true`              |
| `GOOGLE_CLOUD_PROJECT`           | Google Cloud project ID     | `my-project-123`    |
| `GOOGLE_CLOUD_LOCATION`          | Google Cloud location       | `us-central1`       |
| `GOOGLE_APPLICATION_CREDENTIALS` | Path to service account key | `/path/to/key.json` |
