Secure access to Gemini's APIs using API keys and environment variables. Learn how to authenticate requests for all Gemini features.
Create API KeyGenerate your authentication credentials through the Developer Console. This key grants programmatic access to all Gemini capabilities.
Store your API key securely using environment variables rather than hardcoded values. This protects credentials in both development and production environments.
{`# Linux/macOS
export GEMINI_API_key="yourkeyhere"
# Windows (CMD)
setx GEMINI_API_key "yourkeyhere"
# PowerShell
[Environment]::SetEnvironmentVariable("GEMINI_api_key", "yourkeyhere", "User")`}
Confirm your setup works by making a test request. This verifies both the API key format and environment variable are correctly configured.
{`curl -X POST https://api.gemini.com/v1/complete \\
-H "Authorization: Bearer $GEMINI_api_key" \\
-d '{"prompt":"Test request"}'`}
{`Authorization: Bearer YOUR_API_KEY`}
All API requests must include the Authorization header with a valid API key. Unauthenticated requests will return a 401 error.
{`gemini config set api_key "your_api_key_here"`}
{`import os
import requests
headers = {
'Authorization': f'Bearer {os.getenv("GEMINI_api_key")}'
}
response = requests.post('https://api.gemini.com/v1/complete', headers=headers, json={'prompt': 'Hello'})`}
Change your API key every 30 days and regenerate credentials if you suspect any potential compromise.
Don't include credentials in client-side code, open-source repositories, or public documentation.
Create separate API keys for different applications or teams within your organization.
Restrict API access to specific IP ranges for enterprise deployments.
The Gemini CLI and SDK automatically look for the API key in environment variables. You can override this with explicit configuration files.
{`echo 'export GEMINI_API_KEY="your_api_key"' >> ~/.bashrc
source ~/.bashrc`}
{`[System.Environment]::SetEnvironmentVariable("GEMINI_API_KEY", "your_api_key", "Machine")`}
Get your free API key and start building with Gemini. All features require authentication for secure access.
Get API Key