API Integrations Guide: Connect Services to OpenClaw
Learn how to connect external services to your OpenClaw agent. This guide focuses on the concepts and patterns you'll use, with practical starting points for popular services.
API integrations extend what your agent can do. Instead of just chatting, your agent can send emails, post to Slack, create calendar events, and interact with hundreds of services.
The Integration Pattern
All API integrations follow the same basic steps:
- Get API credentials — Usually an API key or OAuth token
- Install the client library — Most services have Python packages
- Make API calls — Send requests, get responses
- Wire into your agent — Create commands your agent can use
Example: Simple Web API Call
Before integrating complex services, let's start with a simple example — fetching weather data from a public API:
import requests def get_weather(city): # Call a weather API (example using wttr.in) url = f"https://wttr.in/{city}?format=%C+%t" response = requests.get(url) if response.status_code == 200: return response.text else: return "Couldn't fetch weather" # Wire into your agent @agent.tool def weather(ctx, city): """Get current weather for a city""" return get_weather(city)
This same pattern applies to every service: get credentials → make request → handle response → wire into agent.
Working with Service APIs
Most popular services follow similar patterns. Here's what you need to know for the common ones:
Gmail / Google Services
# 1. Install the Google client library # pip install google-api-python-client google-auth from googleapiclient.discovery import build from google.oauth2.credentials import Credentials # 2. Create a client with your OAuth token def create_gmail_client(access_token): creds = Credentials(token=access_token) service = build('gmail', 'v1', credentials=creds) return service # 3. Use it in your agent @agent.tool def read_emails(ctx, max_results=5): """Read recent unread emails""" service = create_gmail_client(ctx.user.google_token) results = service.users().messages().list( userId='me', q='is:unread', maxResults=max_results ).execute() messages = results.get('messages', []) return f"You have {len(messages)} unread emails"
📋 Google Setup Steps
- Go to Google Cloud Console
- Create a project and enable Gmail API
- Create OAuth 2.0 credentials
- Get your client ID and secret
- Use Google's OAuth playground to get a token
Slack
# 1. Install Slack SDK # pip install slack-sdk import os from slack_sdk import WebClient # 2. Get bot token from Slack app settings slack_token = os.getenv('SLACK_BOT_TOKEN') client = WebClient(token=slack_token) # 3. Use in agent @agent.tool def post_to_slack(ctx, channel, message): """Post a message to a Slack channel""" try: response = client.chat_postMessage( channel=channel, text=message ) return "Message sent!" except Exception as e: return f"Error: {str(e)}"
📋 Slack Setup Steps
- Go to Slack API and create an app
- Add
chat:writebot scope - Install app to your workspace
- Copy the Bot User OAuth Token
- Invite the bot to channels it should post in
Notion
# 1. Install Notion client # pip install notion-client from notion_client import Client # 2. Initialize with integration tokennotion = Client(auth=os.getenv('NOTION_TOKEN')) # 3. Use in agent @agent.tool def add_to_notion(ctx, database_id, title, content): """Add a page to a Notion database""" notion.pages.create( parent={"database_id": database_id}, properties={ "Name": { "title": [{"text": {"content": title}}] } }, children=[{ "object": "block", "type": "paragraph", "paragraph": { "rich_text": [{"text": {"content": content}}] } }] ) return "Added to Notion!"
📋 Notion Setup Steps
- Go to Notion Integrations
- Create a new integration
- Copy the Internal Integration Token
- Share your database with the integration
- Get the database ID from the URL
Handling API Keys Securely
Never hardcode API keys in your code. Use environment variables:
# Create a .env file (don't commit this!) SLACK_BOT_TOKEN=xoxb-your-token-here NOTION_TOKEN=secret_your_token_here OPENAI_API_KEY=sk-your-key-here # In your Python code import os from dotenv import load_dotenv load_dotenv() # Load variables from .env file slack_token = os.getenv('SLACK_BOT_TOKEN') notion_token = os.getenv('NOTION_TOKEN')
Error Handling Best Practices
APIs fail. Networks timeout. Always handle errors gracefully:
@agent.tool def safe_api_call(ctx, service): """Example of robust error handling""" max_retries = 3 for attempt in range(max_retries): try: result = call_external_api(service) if result: return result except requests.Timeout: if attempt == max_retries - 1: return "Service timed out. Please try again." time.sleep(2 ** attempt) # Wait longer each retry except Exception as e: return f"Error: {str(e)}" return "Failed after retries"
Popular Services Quick Reference
| Service | Python Package | Auth Type |
|---|---|---|
| Gmail | google-api-python-client | OAuth 2.0 |
| Slack | slack-sdk | Bot Token |
| Notion | notion-client | Integration Token |
| GitHub | PyGithub | Personal Access Token |
| Stripe | stripe | Secret Key |
| Discord | discord.py | Bot Token |
| Trello | py-trello | API Key + Token |
| Airtable | pyairtable | API Key |
Next Steps
- Pick one service to start with — don't try to integrate everything at once
- Follow the official docs for authentication setup
- Start simple — just reading data before writing
- Test thoroughly before giving your agent access
🚀 Need More Help?
The OpenClaw community has built integrations for 50+ services. Check the docs for detailed setup guides.
View Integration Docs →