OpenClaw's power comes from its ability to integrate with dozens of services through API keys. Proper API key setup is crucial for both functionality and security.
This comprehensive guide walks you through obtaining, configuring, and securing API keys for all major OpenClaw integrations, plus troubleshooting common issues and security best practices.
Understanding OpenClaw API Key Architecture
OpenClaw uses API keys to authenticate with external services on your behalf. Unlike some automation platforms that store your credentials in the cloud, OpenClaw keeps all API keys local to your installation.
Key principles:
- Local Storage: All API keys stay on your infrastructure
- Encryption at Rest: Keys are encrypted when stored locally
- Environment Variables: Sensitive data separated from code
- Granular Permissions: Each integration uses minimal required permissions
- Easy Rotation: Simple process to update keys without reconfiguration
Core API Keys (Required for Basic Functionality)
1. OpenAI API Key (Required)
OpenClaw requires an AI model for intelligent automation. OpenAI is the default provider.
Step 1: Get OpenAI API Key
- Visit https://platform.openai.com
- Click "Sign up" or "Log in"
- Navigate to "API" section
- Click "Create new secret key"
- Copy the key (starts with
sk-)
Step 2: Configure in OpenClaw
Add to your .env file:
# OpenAI Configuration
OPENAI_API_KEY=sk-your_openai_api_key_here
OPENAI_MODEL=gpt-4o # or gpt-3.5-turbo for cost optimization
OPENAI_MAX_TOKENS=2000
OPENAI_TEMPERATURE=0.1 # Lower = more consistent responses
Update ~/.openclaw/config.yaml:
ai:
provider: openai
model: gpt-4o
temperature: 0.1
max_tokens: 2000
# Cost controls (optional)
cost_controls:
daily_budget: 50.00 # USD
monthly_budget: 500.00
alert_threshold: 0.8 # Alert at 80% of budget
Step 3: Test Connection
openclaw test-integration openai
Cost Optimization Tips:
- Use
gpt-3.5-turbofor routine tasks,gpt-4ofor complex analysis - Set up cost alerts through OpenAI dashboard
- Monitor token usage with OpenClaw's built-in cost tracking
2. Alternative AI Providers
OpenClaw supports multiple AI providers for cost optimization or specific requirements:
Anthropic (Claude)
ANTHROPIC_API_KEY=sk-ant-api_key_here
ai:
provider: anthropic
model: claude-3-sonnet-20240229
Local Models (Ollama)
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_MODEL=llama2
ai:
provider: ollama
model: llama2
base_url: http://localhost:11434
Email Integration API Keys
Gmail API Setup
Gmail integration enables email automation, scheduling, and intelligent triage.
Step 1: Enable Gmail API
- Visit Google Cloud Console: https://console.cloud.google.com
- Create new project or select existing one
- Enable Gmail API:
- Go to "APIs & Services" → "Library"
- Search for "Gmail API"
- Click "Enable"
Step 2: Create OAuth2 Credentials
- Go to "APIs & Services" → "Credentials"
- Click "Create Credentials" → "OAuth 2.0 Client IDs"
- Configure consent screen (if first time):
- User Type: External (for personal) or Internal (for G Suite)
- App name: "OpenClaw Automation"
- Scopes: Add Gmail scopes
- Create OAuth client:
- Application type: Desktop application
- Name: "OpenClaw Gmail Integration"
- Download credentials JSON file
Step 3: Configure OpenClaw
Add to .env:
# Gmail Configuration
GMAIL_CLIENT_ID=your_client_id.apps.googleusercontent.com
GMAIL_CLIENT_SECRET=your_client_secret
GMAIL_REDIRECT_URI=http://localhost:8080/auth/callback
Update config:
integrations:
gmail:
enabled: true
auth_method: oauth2
client_id: ${GMAIL_CLIENT_ID}
client_secret: ${GMAIL_CLIENT_SECRET}
scopes:
- https://www.googleapis.com/auth/gmail.readonly
- https://www.googleapis.com/auth/gmail.send
- https://www.googleapis.com/auth/gmail.modify
credentials_file: ~/.openclaw/gmail_credentials.json
Step 4: Authenticate
openclaw auth gmail
# This will open browser for OAuth flow
Outlook/Exchange API Setup
For Microsoft email services:
Step 1: Azure App Registration
- Visit Azure Portal: https://portal.azure.com
- Navigate to "Azure Active Directory" → "App registrations"
- Click "New registration"
- Configure:
- Name: "OpenClaw Email Integration"
- Supported account types: "Accounts in this organizational directory only"
- Redirect URI:
http://localhost:8080/auth/callback
Step 2: Configure Permissions
- Go to "API permissions"
- Add permissions:
- Microsoft Graph → Delegated permissions
- Add:
Mail.Read,Mail.Send,Mail.ReadWrite
- Grant admin consent (if required)
Step 3: Create Client Secret
- Go to "Certificates & secrets"
- Click "New client secret"
- Copy the secret value
Configuration:
OUTLOOK_CLIENT_ID=your_azure_client_id
OUTLOOK_CLIENT_SECRET=your_azure_client_secret
OUTLOOK_TENANT_ID=your_azure_tenant_id
Communication Platform API Keys
Slack API Setup
Enables team communication automation and bot interactions.
Step 1: Create Slack App
- Visit https://api.slack.com/apps
- Click "Create New App" → "From scratch"
- App Name: "OpenClaw Automation"
- Select your workspace
Step 2: Configure Bot Permissions
- Go to "OAuth & Permissions"
- Add Bot Token Scopes:
channels:history channels:read chat:write files:write groups:history im:history im:write users:read
Step 3: Install App to Workspace
- Click "Install to Workspace"
- Authorize the app
- Copy the Bot User OAuth Token (starts with
xoxb-)
Configuration:
SLACK_BOT_TOKEN=xoxb-your-bot-token-here
SLACK_APP_TOKEN=xapp-your-app-token-here # For Socket Mode
integrations:
slack:
enabled: true
bot_token: ${SLACK_BOT_TOKEN}
app_token: ${SLACK_APP_TOKEN}
signing_secret: ${SLACK_SIGNING_SECRET}
socket_mode: true # For real-time events
Discord API Setup
For Discord server automation and bot functionality.
Step 1: Create Discord Application
- Visit https://discord.com/developers/applications
- Click "New Application"
- Name: "OpenClaw Bot"
Step 2: Create Bot
- Go to "Bot" section
- Click "Add Bot"
- Configure bot:
- Username: Choose bot name
- Copy Bot Token
- Enable necessary intents:
- Presence Intent
- Server Members Intent
- Message Content Intent
Step 3: Generate Bot Invite
- Go to "OAuth2" → "URL Generator"
- Scopes:
bot,applications.commands - Permissions: Configure based on needs
- Use generated URL to invite bot to server
Configuration:
DISCORD_BOT_TOKEN=your_discord_bot_token_here
DISCORD_GUILD_ID=your_server_id_here # Optional: restrict to specific server
Development Platform API Keys
GitHub API Setup
Enables repository management, issue tracking, and code automation.
Step 1: Generate Personal Access Token
- Go to GitHub Settings → Developer settings → Personal access tokens
- Click "Generate new token" (classic)
- Configure token:
- Name: "OpenClaw Integration"
- Expiration: Choose appropriate duration
- Scopes:
repo (full repository access) workflow (GitHub Actions) read:org (organization data) read:user (user data)
Step 2: Configure Organization Access (if applicable)
- If using with organization repos, authorize token for org access
Configuration:
GITHUB_TOKEN=ghp_your_github_token_here
GITHUB_USERNAME=your_github_username
GITHUB_ORG=your_organization_name # Optional
integrations:
github:
enabled: true
token: ${GITHUB_TOKEN}
username: ${GITHUB_USERNAME}
organization: ${GITHUB_ORG}
default_repos:
- "your-org/main-repo"
- "your-org/docs-repo"
GitLab API Setup
For GitLab repository integration:
Step 1: Create Personal Access Token
- Go to GitLab Profile Settings → Access Tokens
- Create token with scopes:
read_apiread_repositorywrite_repository
Configuration:
GITLAB_TOKEN=glpat-your_gitlab_token_here
GITLAB_URL=https://gitlab.com # Or your self-hosted instance
Calendar Integration API Keys
Google Calendar Setup
For calendar automation and meeting management.
Step 1: Enable Calendar API
- In Google Cloud Console (same project as Gmail)
- Enable "Google Calendar API"
Step 2: Use Same OAuth Credentials The Gmail OAuth credentials can be reused for Calendar API.
Additional Scopes:
integrations:
google_calendar:
enabled: true
client_id: ${GMAIL_CLIENT_ID}
client_secret: ${GMAIL_CLIENT_SECRET}
scopes:
- https://www.googleapis.com/auth/calendar
- https://www.googleapis.com/auth/calendar.events
Microsoft Calendar (Outlook)
Uses the same Azure app registration as Outlook email:
Additional Permissions:
Calendars.ReadCalendars.ReadWrite
Business Tools API Keys
Notion API Setup
For knowledge management and documentation automation.
Step 1: Create Notion Integration
- Visit https://www.notion.so/my-integrations
- Click "Create new integration"
- Configure:
- Name: "OpenClaw Integration"
- Associated workspace: Select your workspace
Step 2: Get Integration Secret
Copy the Internal Integration Secret (starts with secret_)
Step 3: Share Pages with Integration For each Notion page/database you want to access:
- Open page in Notion
- Click Share → Add people
- Add your integration
Configuration:
NOTION_TOKEN=secret_your_notion_integration_secret
integrations:
notion:
enabled: true
token: ${NOTION_TOKEN}
version: "2022-06-28" # API version
Airtable API Setup
Step 1: Generate API Key
- Visit https://airtable.com/account
- Generate API key in "API" section
Step 2: Get Base IDs Visit https://airtable.com/api to get base IDs for your databases.
Configuration:
AIRTABLE_API_KEY=key_your_airtable_api_key
AIRTABLE_BASE_ID=app_your_base_id_here
Linear API Setup
For issue tracking and project management:
Step 1: Create API Key
- Go to Linear Settings → API
- Create new personal API key
Configuration:
LINEAR_API_KEY=lin_api_your_linear_api_key_here
Advanced Configuration and Security
Environment Variable Management
Production Setup (.env file):
# Core AI
OPENAI_API_KEY=sk-your_key_here
# Communication
SLACK_BOT_TOKEN=xoxb-your_token_here
DISCORD_BOT_TOKEN=your_discord_token_here
# Email & Calendar
GMAIL_CLIENT_ID=your_client_id.apps.googleusercontent.com
GMAIL_CLIENT_SECRET=your_client_secret
# Development
GITHUB_TOKEN=ghp_your_github_token_here
# Business Tools
NOTION_TOKEN=secret_your_notion_token_here
# Database (if using external DB)
DATABASE_URL=postgresql://user:pass@localhost/openclaw
# Security
ENCRYPTION_KEY=your_32_character_encryption_key_here
JWT_SECRET=your_jwt_secret_for_api_auth
Encryption and Security
Enable API Key Encryption:
security:
encrypt_api_keys: true
encryption_key: ${ENCRYPTION_KEY}
key_rotation_days: 90
audit_api_usage: true
Generate Encryption Key:
# Generate secure encryption key
openssl rand -hex 32
Docker Environment Setup
docker-compose.yml:
version: '3.8'
services:
openclaw:
image: openclaw:latest
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY}
- SLACK_BOT_TOKEN=${SLACK_BOT_TOKEN}
- GMAIL_CLIENT_ID=${GMAIL_CLIENT_ID}
- GMAIL_CLIENT_SECRET=${GMAIL_CLIENT_SECRET}
env_file:
- .env
volumes:
- ./data:/app/data
- ./.env:/app/.env:ro
Kubernetes Secrets
secrets.yaml:
apiVersion: v1
kind: Secret
metadata:
name: openclaw-api-keys
type: Opaque
data:
openai-api-key: base64_encoded_key_here
slack-bot-token: base64_encoded_token_here
gmail-client-secret: base64_encoded_secret_here
Testing and Validation
API Key Validation Script
Create validate_api_keys.py:
#!/usr/bin/env python3
import asyncio
import os
from openclaw.core import Agent
from openclaw.integrations import *
async def validate_all_integrations():
"""Test all configured API keys"""
results = {}
# Test OpenAI
try:
openai_test = await test_openai_connection()
results['openai'] = {'status': 'success', 'details': openai_test}
except Exception as e:
results['openai'] = {'status': 'failed', 'error': str(e)}
# Test Gmail
if os.getenv('GMAIL_CLIENT_ID'):
try:
gmail_test = await test_gmail_connection()
results['gmail'] = {'status': 'success', 'details': gmail_test}
except Exception as e:
results['gmail'] = {'status': 'failed', 'error': str(e)}
# Test Slack
if os.getenv('SLACK_BOT_TOKEN'):
try:
slack_test = await test_slack_connection()
results['slack'] = {'status': 'success', 'details': slack_test}
except Exception as e:
results['slack'] = {'status': 'failed', 'error': str(e)}
# Test GitHub
if os.getenv('GITHUB_TOKEN'):
try:
github_test = await test_github_connection()
results['github'] = {'status': 'success', 'details': github_test}
except Exception as e:
results['github'] = {'status': 'failed', 'error': str(e)}
return results
async def test_openai_connection():
"""Test OpenAI API key"""
import openai
response = await openai.ChatCompletion.acreate(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello"}],
max_tokens=5
)
return {
'model': response.model,
'usage': response.usage._asdict()
}
# Run validation
if __name__ == "__main__":
results = asyncio.run(validate_all_integrations())
print("🔍 API Key Validation Results:")
print("=" * 40)
for service, result in results.items():
status = "✅" if result['status'] == 'success' else "❌"
print(f"{status} {service.upper()}: {result['status']}")
if result['status'] == 'failed':
print(f" Error: {result['error']}")
else:
print(f" Details: {result.get('details', 'Connected successfully')}")
Run Validation:
python validate_api_keys.py
Health Check Endpoint
Add to your OpenClaw instance:
@app.route('/health/integrations')
async def integration_health():
"""Health check endpoint for monitoring"""
health_status = {}
for integration_name, integration in agent.integrations.items():
try:
status = await integration.health_check()
health_status[integration_name] = {
'status': 'healthy',
'last_check': datetime.now().isoformat(),
'details': status
}
except Exception as e:
health_status[integration_name] = {
'status': 'unhealthy',
'last_check': datetime.now().isoformat(),
'error': str(e)
}
return health_status
Troubleshooting Common Issues
OpenAI API Issues
Problem: "Authentication Error" Solution:
# Verify API key format
echo $OPENAI_API_KEY | cut -c1-3 # Should output "sk-"
# Test direct API call
curl https://api.openai.com/v1/models \
-H "Authorization: Bearer $OPENAI_API_KEY"
Problem: "Rate limit exceeded" Solution:
ai:
rate_limiting:
requests_per_minute: 60
tokens_per_minute: 60000
retry_backoff: exponential
Gmail OAuth Issues
Problem: "insufficient authentication scopes" Solution:
- Delete existing credentials:
rm ~/.openclaw/gmail_credentials.json - Add required scopes to config
- Re-authenticate:
openclaw auth gmail
Problem: "redirect_uri_mismatch" Solution:
- Check OAuth redirect URI in Google Cloud Console
- Ensure it matches
GMAIL_REDIRECT_URIin .env - Common working URI:
http://localhost:8080/auth/callback
Slack Permission Issues
Problem: "missing_scope" errors Solution:
- Go to Slack App settings → OAuth & Permissions
- Add missing scopes
- Reinstall app to workspace
- Update bot token in OpenClaw
GitHub Token Issues
Problem: "Bad credentials" Solution:
# Test token directly
curl -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/user
# Check token scopes
curl -I -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/user
# Look for X-OAuth-Scopes header
Problem: "Resource not accessible by integration" Solution:
- Check if token has required scopes
- For organization repos, ensure token is authorized for the org
- Verify repository permissions
Cost Management and Optimization
API Usage Monitoring
Cost Tracking Configuration:
cost_management:
enabled: true
providers:
openai:
budget_monthly: 100.00
alert_thresholds: [0.5, 0.8, 0.95]
anthropic:
budget_monthly: 50.00
usage_tracking:
log_all_requests: true
detailed_metrics: true
export_daily_reports: true
Rate Limiting Best Practices
rate_limits:
openai:
requests_per_minute: 60
tokens_per_minute: 60000
github:
requests_per_hour: 5000
slack:
messages_per_minute: 100
gmail:
requests_per_second: 10
Cost Optimization Strategies
-
Use Appropriate Models:
gpt-3.5-turbofor routine tasksgpt-4oonly for complex analysis
-
Implement Caching:
caching: enabled: true ttl_seconds: 3600 # 1 hour cache_ai_responses: true cache_api_responses: true -
Batch Operations:
# Batch multiple email operations async def batch_email_operations(operations): results = await gmail.batch_execute(operations) return results
Advanced Security Configuration
API Key Rotation Strategy
Automated Rotation Script:
#!/usr/bin/env python3
"""
Automated API key rotation for OpenClaw
Run monthly via cron job
"""
import asyncio
import os
from datetime import datetime, timedelta
async def rotate_api_keys():
"""Rotate API keys that support programmatic rotation"""
rotation_log = []
# GitHub token rotation (if using GitHub Apps)
if os.getenv('GITHUB_APP_ID'):
new_token = await rotate_github_app_token()
rotation_log.append(f"GitHub: {new_token[:8]}...")
# Slack app token refresh
if os.getenv('SLACK_REFRESH_TOKEN'):
new_token = await refresh_slack_token()
rotation_log.append(f"Slack: {new_token[:8]}...")
# Update environment and restart services
await update_environment_file(rotation_log)
await restart_openclaw_services()
return rotation_log
# Schedule rotation
# Add to crontab: 0 2 1 * * /path/to/rotate_keys.py
Audit and Compliance
API Usage Audit:
audit:
enabled: true
log_level: detailed
retention_days: 90
events:
- api_key_usage
- authentication_attempts
- permission_changes
- integration_modifications
export:
format: json
destination: s3://your-audit-bucket/openclaw/
Multi-Environment Management
Development Environment (.env.dev):
# Separate API keys for development
OPENAI_API_KEY=sk-development_key_here
SLACK_BOT_TOKEN=xoxb-dev_token_here
GITHUB_TOKEN=ghp_dev_token_here
Production Environment (.env.prod):
# Production keys with full permissions
OPENAI_API_KEY=sk-production_key_here
SLACK_BOT_TOKEN=xoxb-prod_token_here
GITHUB_TOKEN=ghp_prod_token_here
Environment Switching:
# Switch to development
cp .env.dev .env
openclaw restart
# Switch to production
cp .env.prod .env
openclaw restart
Why Proper API Key Setup Matters
Correct API key configuration is the foundation of reliable OpenClaw automation:
Security: Proper key management prevents unauthorized access to your accounts Reliability: Correct permissions ensure skills work consistently Cost Control: Proper rate limiting and monitoring prevent surprise bills Compliance: Audit trails and key rotation meet enterprise requirements
For teams wanting enterprise-grade automation without the complexity of API key management, consider MrDelegate — offering the same AI-powered capabilities with managed infrastructure and automatic credential handling.
Start your free trial to experience AI automation without the setup complexity.
Next Steps
With your API keys properly configured:
- Test all integrations using the validation script
- Set up monitoring for cost and usage tracking
- Implement key rotation for security best practices
- Configure audit logging for compliance
- Start building skills that leverage your integrated services
Proper API key setup unlocks OpenClaw's full potential — turning a collection of separate tools into an integrated AI automation platform that works exactly how you do.
Your AI executive assistant is ready.
Morning brief at 7am. Inbox triaged overnight. Calendar protected. Dedicated VPS. No Docker. Live in 60 seconds.