Skip to content

OpenClaw API 集成指南

通过 API 调用 OpenClaw,集成到自己的应用。


🌐 API 概览

基础信息

项目说明
基础 URLhttp://localhost:18789/api/v1
认证方式Bearer Token
数据格式JSON
字符编码UTF-8

快速示例

bash
# 发送消息
curl -X POST http://localhost:18789/api/v1/message \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "你好",
    "session": "default"
  }'

🔐 认证方式

获取 Token

bash
# 查看当前 Token
openclaw config get gateway.auth.token

# 生成新 Token
openclaw auth generate-token

使用 Token

bash
# 在请求头中携带 Token
curl -H "Authorization: Bearer YOUR_TOKEN" \
  http://localhost:18789/api/v1/status
javascript
// JavaScript 示例
const response = await fetch('http://localhost:18789/api/v1/status', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN'
  }
});

📤 消息 API

发送消息

端点: POST /api/v1/message

请求参数:

json
{
  "text": "你好,请介绍一下自己",
  "session": "default",
  "stream": false,
  "model": "qwen3.5-plus"
}

响应示例:

json
{
  "success": true,
  "data": {
    "messageId": "msg_xxx",
    "text": "你好!我是泡泡龙...",
    "usage": {
      "inputTokens": 20,
      "outputTokens": 100
    }
  }
}

完整示例:

bash
curl -X POST http://localhost:18789/api/v1/message \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "你好",
    "session": "default"
  }'

流式响应

端点: POST /api/v1/message/stream

请求参数:

json
{
  "text": "写一首诗",
  "session": "default",
  "stream": true
}

响应示例 (Server-Sent Events):

data: {"chunk": "春"}
data: {"chunk": "眠"}
data: {"chunk": "不"}
data: {"chunk": "觉"}
data: {"chunk": "晓"}
data: [DONE]

JavaScript 示例:

javascript
const response = await fetch('http://localhost:18789/api/v1/message/stream', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    text: '写一首诗',
    session: 'default'
  })
});

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value);
  console.log(chunk);
}

📥 会话 API

列出会话

端点: GET /api/v1/sessions

响应示例:

json
{
  "success": true,
  "data": {
    "sessions": [
      {
        "id": "default",
        "label": "默认会话",
        "createdAt": "2026-03-17T12:00:00Z",
        "messageCount": 50
      }
    ]
  }
}

创建会话

端点: POST /api/v1/sessions

请求参数:

json
{
  "label": "项目讨论",
  "model": "qwen3.5-plus"
}

响应示例:

json
{
  "success": true,
  "data": {
    "sessionId": "session_xxx",
    "label": "项目讨论",
    "createdAt": "2026-03-17T12:00:00Z"
  }
}

删除会话

端点: DELETE /api/v1/sessions/:id

响应示例:

json
{
  "success": true,
  "data": {
    "deleted": true
  }
}

🧠 记忆 API

搜索记忆

端点: GET /api/v1/memory/search

请求参数:

json
{
  "query": "OpenClaw 配置",
  "limit": 5,
  "minScore": 0.7
}

响应示例:

json
{
  "success": true,
  "data": {
    "results": [
      {
        "content": "OpenClaw 配置文件位于...",
        "score": 0.85,
        "source": "MEMORY.md"
      }
    ]
  }
}

添加记忆

端点: POST /api/v1/memory

请求参数:

json
{
  "content": "用户偏好简洁的回复风格",
  "tags": ["用户偏好", "风格"],
  "type": "long-term"
}

响应示例:

json
{
  "success": true,
  "data": {
    "memoryId": "mem_xxx",
    "createdAt": "2026-03-17T12:00:00Z"
  }
}

🛠️ 技能 API

列出技能

端点: GET /api/v1/skills

响应示例:

json
{
  "success": true,
  "data": {
    "skills": [
      {
        "name": "weather",
        "description": "查询天气预报",
        "enabled": true,
        "version": "1.0.0"
      }
    ]
  }
}

执行技能

端点: POST /api/v1/skills/:name/execute

请求参数:

json
{
  "args": ["北京"],
  "session": "default"
}

响应示例:

json
{
  "success": true,
  "data": {
    "result": "北京今天晴,温度 20-28°C",
    "executionTime": 1.5
  }
}

📊 状态 API

获取系统状态

端点: GET /api/v1/status

响应示例:

json
{
  "success": true,
  "data": {
    "gateway": {
      "status": "running",
      "version": "2026.3.13",
      "uptime": 86400
    },
    "models": {
      "available": 5,
      "default": "qwen3.5-plus"
    },
    "sessions": {
      "active": 3,
      "total": 10
    }
  }
}

🔧 配置 API

获取配置

端点: GET /api/v1/config/:path

示例:

bash
# 获取网关配置
curl http://localhost:18789/api/v1/config/gateway

响应示例:

json
{
  "success": true,
  "data": {
    "port": 18789,
    "mode": "local",
    "bind": "loopback"
  }
}

💻 SDK 使用

JavaScript SDK

安装:

bash
npm install openclaw-sdk

使用示例:

javascript
const OpenClaw = require('openclaw-sdk');

const client = new OpenClaw({
  baseUrl: 'http://localhost:18789',
  token: 'YOUR_TOKEN'
});

// 发送消息
const response = await client.message.send({
  text: '你好',
  session: 'default'
});

console.log(response.text);

// 流式响应
const stream = await client.message.stream({
  text: '写一首诗'
});

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

Python SDK

安装:

bash
pip install openclaw-sdk

使用示例:

python
from openclaw import OpenClaw

client = OpenClaw(
    base_url='http://localhost:18789',
    token='YOUR_TOKEN'
)

# 发送消息
response = client.message.send(
    text='你好',
    session='default'
)

print(response.text)

# 搜索记忆
memories = client.memory.search(
    query='OpenClaw 配置',
    limit=5
)

for memory in memories:
    print(memory.content)

cURL 示例集合

bash
# 1. 发送消息
curl -X POST http://localhost:18789/api/v1/message \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"text": "你好", "session": "default"}'

# 2. 流式响应
curl -X POST http://localhost:18789/api/v1/message/stream \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"text": "写一首诗"}'

# 3. 列出会话
curl http://localhost:18789/api/v1/sessions \
  -H "Authorization: Bearer YOUR_TOKEN"

# 4. 搜索记忆
curl "http://localhost:18789/api/v1/memory/search?query=配置" \
  -H "Authorization: Bearer YOUR_TOKEN"

# 5. 获取状态
curl http://localhost:18789/api/v1/status \
  -H "Authorization: Bearer YOUR_TOKEN"

🌍 Web 集成示例

HTML 聊天界面

html
<!DOCTYPE html>
<html>
<head>
  <title>OpenClaw 聊天</title>
  <style>
    #chat { height: 400px; overflow-y: auto; border: 1px solid #ccc; }
    .message { padding: 10px; margin: 5px; }
    .user { background: #e3f2fd; }
    .ai { background: #f5f5f5; }
  </style>
</head>
<body>
  <div id="chat"></div>
  <input id="input" placeholder="输入消息..." />
  <button onclick="send()">发送</button>

  <script>
    const TOKEN = 'YOUR_TOKEN';
    
    async function send() {
      const input = document.getElementById('input');
      const text = input.value;
      
      // 显示用户消息
      addMessage(text, 'user');
      
      // 发送到 API
      const response = await fetch('http://localhost:18789/api/v1/message', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${TOKEN}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ text, session: 'default' })
      });
      
      const data = await response.json();
      addMessage(data.data.text, 'ai');
      
      input.value = '';
    }
    
    function addMessage(text, type) {
      const chat = document.getElementById('chat');
      const div = document.createElement('div');
      div.className = `message ${type}`;
      div.textContent = text;
      chat.appendChild(div);
      chat.scrollTop = chat.scrollHeight;
    }
  </script>
</body>
</html>

📋 API 错误码

错误码说明解决方案
400请求参数错误检查请求参数
401认证失败检查 Token
403权限不足检查用户权限
404资源不存在检查资源 ID
429请求过于频繁降低请求频率
500服务器错误查看服务器日志

🛡️ 安全最佳实践

Token 管理

javascript
// ✅ 正确:从环境变量读取
const token = process.env.OPENCLAW_TOKEN;

// ❌ 错误:硬编码在代码中
const token = 'sk-123456';  // 不要这样

错误处理

javascript
try {
  const response = await client.message.send({ text: '你好' });
} catch (error) {
  if (error.status === 401) {
    console.error('认证失败,请检查 Token');
  } else if (error.status === 429) {
    console.error('请求过于频繁');
  } else {
    console.error('未知错误:', error);
  }
}

提示

API 让 OpenClaw 集成更灵活!

🟢🐉 泡泡龙

Released under the MIT License.