🔌 OpenClaw API 集成与调用指南

凌晨3点55分,我敲下了第一个curl命令。API响应回来的那一刻,我感觉自己像在和数字世界的脉搏握手。

API是桥梁,连接你的系统和OpenClaw

通过REST API,你可以从任何语言、任何平台调用OpenClaw能力:发送消息、触发任务、查询状态、管理Agent。Webhook让OpenClaw主动通知你,实现双向通信。

🎯 API基础配置

启用API服务

# ~/.openclaw/config.yaml
gateway:
  # REST API配置
  api:
    enabled: true
    port: 3000
    host: "0.0.0.0"
    
    # 认证方式
    auth:
      type: "bearer"  # 或 "api_key"
      secret: ${API_SECRET}  # 生成强密钥
    
    # CORS配置(跨域)
    cors:
      enabled: true
      origins: ["https://your-app.com", "http://localhost:3000"]
    
    # 速率限制
    rate_limit:
      requests_per_minute: 60
      burst: 10

生成API密钥

# 生成随机密钥
openssl rand -hex 32

# 或使用OpenClaw CLI
openclaw api key generate --name "production"
# 输出: oc_api_sk_abc123...

📡 核心API端点

POST /api/v1/chat
发送消息给Agent
# 请求示例
curl -X POST http://localhost:3000/api/v1/chat \
  -H "Authorization: Bearer oc_api_sk_xxx" \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "user_123",
    "message": "帮我写个Python脚本",
    "context": {
      "model": "claude-3-5-sonnet",
      "temperature": 0.7
    }
  }'

# 响应
{
  "id": "msg_abc123",
  "content": "当然!这是一个Python脚本...",
  "model": "claude-3-5-sonnet-20241022",
  "usage": {
    "input_tokens": 45,
    "output_tokens": 156
  },
  "timestamp": "2026-04-17T01:15:30Z"
}
GET /api/v1/sessions/{session_id}
获取会话信息
curl http://localhost:3000/api/v1/sessions/user_123 \
  -H "Authorization: Bearer oc_api_sk_xxx"
POST /api/v1/agents/spawn
创建子Agent
curl -X POST http://localhost:3000/api/v1/agents/spawn \
  -H "Authorization: Bearer oc_api_sk_xxx" \
  -d '{
    "task": "分析这份文档",
    "model": "gpt-4o",
    "timeout": 300,
    "skills": ["web_fetch", "file_read"]
  }'

🪝 Webhook配置

让OpenClaw在特定事件发生时主动通知你的系统:

# ~/.openclaw/config.yaml
webhooks:
  enabled: true
  endpoints:
    # 消息事件
    - url: "https://your-app.com/webhooks/openclaw/message"
      events: ["message.received", "message.sent"]
      secret: ${WEBHOOK_SECRET}
    
    # Agent状态变更
    - url: "https://your-app.com/webhooks/openclaw/agent"
      events: ["agent.spawned", "agent.completed", "agent.error"]
      secret: ${WEBHOOK_SECRET}
    
    # 系统告警
    - url: "https://your-app.com/webhooks/openclaw/alert"
      events: ["system.error", "rate_limit.exceeded"]
      secret: ${WEBHOOK_SECRET}

Webhook载荷示例

{
  "event": "message.received",
  "timestamp": "2026-04-17T01:20:00Z",
  "data": {
    "session_id": "user_123",
    "message_id": "msg_abc456",
    "content": "今天天气怎么样",
    "channel": "telegram",
    "user": {
      "id": "tg_user_789",
      "username": "john_doe"
    }
  },
  "signature": "sha256=xxx"  // 用于验证来源
}

💻 多语言SDK示例

Python

from openclaw import OpenClawClient

client = OpenClawClient(
    base_url="http://localhost:3000",
    api_key="oc_api_sk_xxx"
)

# 发送消息
response = client.chat.send(
    session_id="user_123",
    message="帮我总结一下"
)
print(response.content)

# 创建子Agent
sub_agent = client.agents.spawn(
    task="分析数据",
    model="claude-3-5-sonnet"
)
result = sub_agent.wait_for_completion()

JavaScript/Node.js

const { OpenClawClient } = require('openclaw-sdk');

const client = new OpenClawClient({
  baseURL: 'http://localhost:3000',
  apiKey: 'oc_api_sk_xxx'
});

// 流式响应
const stream = await client.chat.stream({
  sessionId: 'user_123',
  message: '讲个故事'
});

for await (const chunk of stream) {
  process.stdout.write(chunk.content);
}

Go

package main

import (
    "context"
    "fmt"
    "github.com/openclaw/go-sdk"
)

func main() {
    client := openclaw.NewClient("http://localhost:3000", "oc_api_sk_xxx")
    
    resp, err := client.Chat.Send(context.Background(), openclaw.ChatRequest{
        SessionID: "user_123",
        Message:   "Hello",
    })
    
    fmt.Println(resp.Content)
}

🔒 安全最佳实践

Webhook签名验证(Python示例)

import hmac
import hashlib

def verify_webhook(payload, signature, secret):
    expected = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(f"sha256={expected}", signature)

🎯 常见集成场景

场景1:客服系统集成

用户 → 客服系统 → OpenClaw API → AI回复 → 用户
              ↓
         Webhook通知处理状态

场景2:自动化工作流

定时任务 → 触发OpenClaw Agent
              ↓
         分析数据/生成报告
              ↓
         Webhook推送结果到钉钉/飞书

场景3:多Agent协作

主Agent接收任务
    ├─ 子Agent1: 搜索信息 (spawn)
    ├─ 子Agent2: 分析数据 (spawn)
    └─ 子Agent3: 生成报告 (spawn)
    
结果汇总 → 返回给用户

🔗 相关资源

API的世界没有边界:
"API是数字世界的通用语言。学会它,你就拥有了连接一切的力量。凌晨4点12分,我合上电脑——API文档还在发光,但我知道,明天的集成会更简单。"