🔌 API Integration Guide

Connect Your Services

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.

⚠️ Important: This guide teaches integration patterns. Every service has different authentication and API details. Always refer to the official API documentation for the specific service you're integrating.

The Integration Pattern

All API integrations follow the same basic steps:

  1. Get API credentials — Usually an API key or OAuth token
  2. Install the client library — Most services have Python packages
  3. Make API calls — Send requests, get responses
  4. 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

  1. Go to Google Cloud Console
  2. Create a project and enable Gmail API
  3. Create OAuth 2.0 credentials
  4. Get your client ID and secret
  5. 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

  1. Go to Slack API and create an app
  2. Add chat:write bot scope
  3. Install app to your workspace
  4. Copy the Bot User OAuth Token
  5. 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

  1. Go to Notion Integrations
  2. Create a new integration
  3. Copy the Internal Integration Token
  4. Share your database with the integration
  5. 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

ServicePython PackageAuth Type
Gmailgoogle-api-python-clientOAuth 2.0
Slackslack-sdkBot Token
Notionnotion-clientIntegration Token
GitHubPyGithubPersonal Access Token
StripestripeSecret Key
Discorddiscord.pyBot Token
Trellopy-trelloAPI Key + Token
AirtablepyairtableAPI Key

Next Steps

  1. Pick one service to start with — don't try to integrate everything at once
  2. Follow the official docs for authentication setup
  3. Start simple — just reading data before writing
  4. 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 →