OpenClaw API Integration Guide - Build Custom AI Solutions
Introduction
OpenClaw provides a powerful REST API that allows you to integrate AI agents into any application or workflow. Whether you're building a chatbot, automation system, or custom AI solution, the OpenClaw API gives you full control over agent behavior, message routing, and data handling.
In this guide, you'll learn how to set up API authentication, send messages to agents, handle webhooks, and build production-ready integrations with OpenClaw.
Prerequisites
- OpenClaw installed and running (see our installation guide)
- Basic knowledge of REST APIs
- Node.js, Python, or any programming language for API calls
- An OpenClaw API token (generated from your gateway settings)
API Authentication
OpenClaw uses token-based authentication for all API requests.
Generating an API Token
- Start your OpenClaw gateway:
openclaw gateway start - Access the dashboard at
http://localhost:3000 - Navigate to Settings → API Tokens
- Click "Generate New Token"
- Copy the token (you won't see it again!)
Using the Token
Include your API token in the Authorization header:
Authorization: Bearer YOUR_API_TOKENCore API Endpoints
1. Send Message to Agent
Send a message to an OpenClaw agent and receive a response:
POST /api/v1/messages
Content-Type: application/json
Authorization: Bearer YOUR_API_TOKEN
{
"agentId": "my-agent",
"message": "Hello, how can you help me?",
"sessionId": "user-session-123",
"context": {
"userId": "user-456",
"metadata": {}
}
}2. Agent Status
Check the status and configuration of an agent:
GET /api/v1/agents/:agentId/status
Authorization: Bearer YOUR_API_TOKEN3. List Sessions
Retrieve all active sessions for an agent:
GET /api/v1/sessions?agentId=my-agent
Authorization: Bearer YOUR_API_TOKENImplementation Examples
Node.js Example
const axios = require('axios');
const API_URL = 'http://localhost:3000/api/v1';
const API_TOKEN = 'YOUR_API_TOKEN';
async function sendMessage(agentId, message) {
try {
const response = await axios.post(`${API_URL}/messages`, {
agentId,
message,
sessionId: 'session-' + Date.now()
}, {
headers: {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json'
}
});
console.log('Agent response:', response.data);
return response.data;
} catch (error) {
console.error('Error sending message:', error.response?.data || error.message);
}
}
// Usage
sendMessage('my-agent', 'What is OpenClaw?');Python Example
import requests
import json
API_URL = 'http://localhost:3000/api/v1'
API_TOKEN = 'YOUR_API_TOKEN'
headers = {
'Authorization': f'Bearer {API_TOKEN}',
'Content-Type': 'application/json'
}
def send_message(agent_id, message):
data = {
'agentId': agent_id,
'message': message,
'sessionId': f'session-{int(time.time())}'
}
try:
response = requests.post(
f'{API_URL}/messages',
json=data,
headers=headers
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f'Error: {e}')
return None
# Usage
result = send_message('my-agent', 'Help me write code')
print(result)Webhooks Integration
Configure webhooks to receive real-time notifications when agents process messages or complete tasks.
Setting Up a Webhook
- Create an endpoint on your server to receive POST requests
- Register the webhook URL with OpenClaw via the API or dashboard
- Verify webhook signatures for security
Webhook Payload
{
"event": "message.processed",
"agentId": "my-agent",
"sessionId": "user-session-123",
"timestamp": "2026-02-25T10:30:00Z",
"data": {
"userMessage": "Hello",
"agentResponse": "Hi! How can I help?",
"toolCalls": [],
"processingTime": 120
},
"signature": "sha256=abc123..."
}Verifying Webhook Signatures
const crypto = require('crypto');
function verifyWebhookSignature(payload, signature, webhookSecret) {
const hmac = crypto.createHmac('sha256', webhookSecret);
const digest = hmac.update(JSON.stringify(payload)).digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(digest)
);
}Building Automation Workflows
Combine OpenClaw APIs with external services to create powerful automation workflows.
Example: Slack Bot Integration
const { App } = require('@slack/bolt');
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
signingSecret: process.env.SLACK_SIGNING_SECRET
});
// Listen for messages in Slack
app.message(async ({ message, say }) => {
// Forward to OpenClaw agent
const response = await sendMessage('slack-agent', message.text);
// Send agent response back to Slack
await say(response.data.reply);
});
app.start(3000);Example: Email Automation
// Process incoming emails via webhooks
app.post('/webhook/email', async (req, res) => {
const { from, subject, body } = req.body;
// Send to OpenClaw for processing
const response = await sendMessage('email-agent',
`New email from ${from}: ${subject}\n${body}`
);
// Take action based on agent response
if (response.data.action === 'reply') {
await sendEmail(from, response.data.reply);
}
res.sendStatus(200);
});Best Practices
- Security: Never expose API tokens in client-side code. Use environment variables.
- Rate Limiting: Implement client-side rate limiting to avoid API throttling.
- Error Handling: Always handle API errors gracefully with retry logic.
- Session Management: Maintain session IDs for conversation continuity.
- Webhook Verification: Always verify webhook signatures to prevent spoofing.
- Logging: Log API requests and responses for debugging and analytics.
Troubleshooting
- 401 Unauthorized: Check that your API token is correct and not expired.
- 404 Not Found: Verify the agent ID exists and the endpoint URL is correct.
- 429 Too Many Requests: Implement rate limiting and add exponential backoff.
- 500 Internal Server Error: Check the OpenClaw gateway logs for details.
- Webhook Not Received: Ensure your endpoint is publicly accessible and returns 200 OK.
Next Steps
- Learn about AI Skills development to extend agent capabilities
- Explore advanced configuration for production deployments
- Check out our tools directory for pre-built integrations
- Join the Discord community to share your integrations
Pro Tip
Use the OpenClaw DEBUG environment variable to see detailed API logs during development. Set DEBUG=openclaw:* to enable all debug output.