Want to integrate **OpenClaw** into your own applications? Whether you’re building a custom dashboard, automating workflows, or creating a unique AI-powered experience, the OpenClaw API gives you programmatic access to your AI agent’s capabilities.

This **2026 developer guide** covers everything you need to know about the **OpenClaw API**: authentication, endpoints, code examples in Python and JavaScript, rate limits, error handling, and real-world integration scenarios.

## What is the OpenClaw API?

OpenClaw is an AI agent framework that connects language models (like Claude, GPT, Gemini) to messaging platforms, tools, and automations. While most users interact through Discord, Telegram, or the CLI, developers can also interact programmatically via the Gateway API.

The OpenClaw Gateway exposes a REST API that allows you to:
– Send messages to sessions
– Spawn sub-agent tasks
– Manage cron jobs and reminders
– Check session status
– Execute browser automation
– And much more

## Getting Started: Authentication

The OpenClaw Gateway API uses token-based authentication. Your gateway token is defined in your `openclaw.yml` configuration file.

### Finding Your Gateway Token

“`yaml
# openclaw.yml
gateway:
token: “your-secret-gateway-token-here”
port: 3000
“`

If you haven’t set a token, add one now. This token authenticates all API requests.

### Making Authenticated Requests

Include your token in the `Authorization` header:

“`bash
curl -X POST http://localhost:3000/api/sessions/send \
-H “Authorization: Bearer your-secret-gateway-token-here” \
-H “Content-Type: application/json” \
-d ‘{“sessionKey”: “main”, “message”: “Hello from the API!”}’
“`

## Core API Endpoints

Here are the most commonly used OpenClaw API endpoints:

### 1. Send Message to Session

**POST** `/api/sessions/send`

Send a message to an existing session and get the agent’s response.

“`json
{
“sessionKey”: “main”,
“message”: “What’s the weather like today?”,
“timeoutSeconds”: 120
}
“`

### 2. Spawn a Sub-Agent Task

**POST** `/api/sessions/spawn`

Create a new isolated session that runs a task and reports back.

“`json
{
“task”: “Research the top 5 competitors for AI chatbots and summarize findings”,
“model”: “claude-sonnet-4-5”,
“runTimeoutSeconds”: 300
}
“`

### 3. List Sessions

**GET** `/api/sessions/list`

Get a list of active sessions with optional filters.

“`json
{
“kinds”: [“main”, “isolated”],
“limit”: 10,
“messageLimit”: 5
}
“`

### 4. Get Session History

**GET** `/api/sessions/history`

Fetch the conversation history for a specific session.

“`json
{
“sessionKey”: “main”,
“limit”: 50,
“includeTools”: true
}
“`

### 5. Manage Cron Jobs

**POST** `/api/cron/add`

Schedule recurring tasks or one-time reminders.

“`json
{
“job”: {
“name”: “daily-summary”,
“schedule”: {
“kind”: “cron”,
“expr”: “0 9 * * *”,
“tz”: “America/New_York”
},
“payload”: {
“kind”: “systemEvent”,
“text”: “Time for the daily summary!”
},
“sessionTarget”: “main”
}
}
“`

### 6. Session Status

**GET** `/api/session/status`

Get token usage, cost, and configuration for a session.

## Python Integration Example

Here’s a complete Python example for integrating OpenClaw into your application:

“`python
import requests
import json
from typing import Optional

class OpenClawClient:
“””Python client for the OpenClaw Gateway API.”””

def __init__(self, base_url: str, token: str):
self.base_url = base_url.rstrip(‘/’)
self.headers = {
‘Authorization’: f’Bearer {token}’,
‘Content-Type’: ‘application/json’
}

def send_message(
self,
message: str,
session_key: str = “main”,
timeout_seconds: int = 120
) -> dict:
“””Send a message to an OpenClaw session.”””
response = requests.post(
f'{self.base_url}/api/sessions/send’,
headers=self.headers,
json={
‘sessionKey’: session_key,
‘message’: message,
‘timeoutSeconds’: timeout_seconds
}
)
response.raise_for_status()
return response.json()

def spawn_task(
self,
task: str,
model: Optional[str] = None,
timeout_seconds: int = 300
) -> dict:
“””Spawn an isolated sub-agent to perform a task.”””
payload = {
‘task’: task,
‘runTimeoutSeconds’: timeout_seconds
}
if model:
payload[‘model’] = model

response = requests.post(
f'{self.base_url}/api/sessions/spawn’,
headers=self.headers,
json=payload
)
response.raise_for_status()
return response.json()

def get_session_status(self, session_key: str = “main”) -> dict:
“””Get status and usage for a session.”””
response = requests.get(
f'{self.base_url}/api/session/status’,
headers=self.headers,
params={‘sessionKey’: session_key}
)
response.raise_for_status()
return response.json()

# Usage example
if __name__ == “__main__”:
client = OpenClawClient(
base_url=”http://localhost:3000″,
token=”your-gateway-token”
)

# Send a message
result = client.send_message(“What time is it?”)
print(f”Agent response: {result}”)

# Spawn a background task
task_result = client.spawn_task(
task=”Research the latest Python web frameworks”,
model=”claude-sonnet-4-5″
)
print(f”Task spawned: {task_result}”)
“`

## JavaScript/Node.js Integration Example

Here’s the equivalent in JavaScript using fetch:

“`javascript
class OpenClawClient {
constructor(baseUrl, token) {
this.baseUrl = baseUrl.replace(/\/$/, ”);
this.headers = {
‘Authorization’: `Bearer ${token}`,
‘Content-Type’: ‘application/json’
};
}

async sendMessage(message, sessionKey = ‘main’, timeoutSeconds = 120) {
const response = await fetch(`${this.baseUrl}/api/sessions/send`, {
method: ‘POST’,
headers: this.headers,
body: JSON.stringify({
sessionKey,
message,
timeoutSeconds
})
});

if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}

return response.json();
}

async spawnTask(task, model = null, runTimeoutSeconds = 300) {
const payload = { task, runTimeoutSeconds };
if (model) payload.model = model;

const response = await fetch(`${this.baseUrl}/api/sessions/spawn`, {
method: ‘POST’,
headers: this.headers,
body: JSON.stringify(payload)
});

if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}

return response.json();
}

async getSessionStatus(sessionKey = ‘main’) {
const response = await fetch(
`${this.baseUrl}/api/session/status?sessionKey=${sessionKey}`,
{ headers: this.headers }
);

if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}

return response.json();
}
}

// Usage
const client = new OpenClawClient(‘http://localhost:3000’, ‘your-token’);

// Send a message
const result = await client.sendMessage(‘Hello from JavaScript!’);
console.log(‘Response:’, result);

// Spawn a task
const taskResult = await client.spawnTask(
‘Generate a haiku about programming’,
‘claude-haiku-4’
);
console.log(‘Task result:’, taskResult);
“`

## Rate Limits and Best Practices

### Rate Limits

OpenClaw doesn’t impose strict rate limits by default, but the underlying AI providers do:

| Provider | Requests/Minute | Tokens/Minute |
|———-|—————–|—————|
| Anthropic (Claude) | 60 | 100,000 |
| OpenAI (GPT) | 60 | 90,000 |
| Google (Gemini) | 60 | 120,000 |

### Best Practices

1. **Implement exponential backoff** for retries
2. **Cache responses** when appropriate
3. **Use sub-agents** for parallel tasks to maximize throughput
4. **Monitor token usage** via the status endpoint
5. **Set reasonable timeouts** to avoid hung requests

## Error Handling

The API returns standard HTTP status codes:

| Code | Meaning | Action |
|——|———|——–|
| 200 | Success | Process response |
| 400 | Bad Request | Check your payload |
| 401 | Unauthorized | Verify your token |
| 404 | Not Found | Check endpoint URL |
| 429 | Rate Limited | Implement backoff |
| 500 | Server Error | Retry with backoff |

### Python Error Handling Example

“`python
import requests
from requests.exceptions import HTTPError, Timeout
import time

def send_with_retry(client, message, max_retries=3):
for attempt in range(max_retries):
try:
return client.send_message(message)
except HTTPError as e:
if e.response.status_code == 429:
wait_time = 2 ** attempt # Exponential backoff
print(f”Rate limited. Waiting {wait_time}s…”)
time.sleep(wait_time)
else:
raise
except Timeout:
print(f”Timeout on attempt {attempt + 1}”)
time.sleep(1)

raise Exception(“Max retries exceeded”)
“`

## Real-World Integration Scenarios

### Scenario 1: Customer Support Automation

Integrate OpenClaw with your help desk to automatically draft responses:

“`python
def draft_support_response(ticket_content):
client = OpenClawClient(BASE_URL, TOKEN)

response = client.spawn_task(
task=f”””Draft a helpful customer support response for:

{ticket_content}

Be professional, empathetic, and provide actionable solutions.”””,
model=”claude-sonnet-4-5″
)

return response[‘reply’]
“`

### Scenario 2: Content Generation Pipeline

Use sub-agents to parallelize content generation:

“`python
import concurrent.futures

def generate_content_batch(topics):
client = OpenClawClient(BASE_URL, TOKEN)

def generate_one(topic):
return client.spawn_task(
task=f”Write a 500-word blog post about {topic}”,
model=”claude-sonnet-4-5″
)

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(generate_one, topics))

return results
“`

### Scenario 3: Scheduled Reporting

Set up automated daily reports:

“`python
def schedule_daily_report():
client = OpenClawClient(BASE_URL, TOKEN)

requests.post(
f'{BASE_URL}/api/cron/add’,
headers=client.headers,
json={
“job”: {
“name”: “daily-analytics”,
“schedule”: {
“kind”: “cron”,
“expr”: “0 8 * * *”, # 8 AM daily
“tz”: “America/New_York”
},
“payload”: {
“kind”: “agentTurn”,
“message”: “Generate today’s analytics summary”
},
“sessionTarget”: “isolated”
}
}
)
“`

## Security Considerations

1. **Never expose your gateway token** in client-side code
2. **Use HTTPS** in production (configure SSL in your gateway)
3. **Restrict network access** to your gateway (firewall rules)
4. **Rotate tokens periodically** for sensitive applications
5. **Audit API access** using gateway logs

## Conclusion

The **OpenClaw API** opens up powerful possibilities for integrating AI agents into your applications. Whether you’re building internal tools, customer-facing products, or automation workflows, the REST API provides the flexibility you need.

Start simple with the `/sessions/send` endpoint, then explore sub-agents for parallel processing and cron jobs for scheduled tasks. With proper error handling and rate limit awareness, you can build robust, production-ready integrations.

*Need help getting started? Check out our [OpenClaw setup guides](/category/setup/) or join the [OpenClaw Discord community](https://discord.com/invite/clawd).*