OpenClaw API Guide: Gateway Endpoints, Auth, and Integration
The OpenClaw Gateway exposes an OpenResponses-compatible HTTP API that gives you programmatic control over agents, sessions, and scheduled tasks. This guide covers the core endpoints, walks through three authentication strategies, and shows how to stream responses and handle errors.
What the OpenClaw Gateway API Exposes
The OpenClaw Gateway is a long-running daemon that serves both HTTP and WebSocket traffic on a single configurable port. The HTTP layer provides an OpenResponses-compatible REST interface for sending prompts, listing models, generating embeddings, and running chat completions. The WebSocket layer adds a protocol for session control, scheduled automation, event hooks, and skill management.
Five HTTP endpoints form the core REST surface:
The chat completions endpoint follows the widely adopted OpenAI-compatible format, so existing tooling can connect without major changes. The responses endpoint uses the OpenResponses format, which adds support for structured inputs beyond plain text.
Some endpoints require explicit activation in the Gateway configuration before they accept traffic. Once enabled, all endpoints share the same port, so there is no additional service to deploy. Check the official Gateway documentation for endpoint-specific setup steps.
The WebSocket protocol covers everything the REST endpoints do not. Clients connect and exchange JSON frames: requests use {type: "req", id, method, params}, responses return as {type: "res", id, ok, payload}, and server-push events arrive as {type: "event", event, payload}. The first frame on any connection must be a connect message carrying device identity.
Through this protocol you can list and manage sessions (sessions.list, sessions.create, sessions.send), schedule recurring agent runs (cron.add, cron.list, cron.run), manage skills (skills.status, skills.install), query tool catalogs (tools.catalog, tools.invoke), and inspect diagnostics and usage. The full method catalog spans dozens of operations across status, sessions, messages, cron, hooks, and skills categories. Most HTTP-only integrations need just the five REST endpoints.
Agent selection works through the model field in your request body. Set it to "openclaw" or "openclaw/default" for the default agent, or "openclaw/<agentId>" to route to a specific one. The x-openclaw-agent-id header provides an alternative routing path.
How to Send Requests to the Responses Endpoint
POST /v1/responses is the primary HTTP endpoint for running OpenClaw agents. A minimal request needs two fields: model for agent routing and input for the prompt.
curl -sS http://127.0.0.1:18789/v1/responses \
-H 'Authorization: Bearer YOUR_TOKEN' \
-H 'Content-Type: application/json' \
-d '{"model": "openclaw", "input": "Summarize the last three log entries"}'
The input field accepts a plain string or an array of structured items. When you pass an array, each item carries a type field that tells the Gateway how to process it.
Message items use roles to shape the conversation. system and developer roles append text to the system prompt. user and assistant roles build conversation history, with the most recent user message becoming the current turn.
Image items (input_image) accept base64-encoded data or a URL. Supported formats include JPEG, PNG, GIF, WebP, HEIC, and HEIF, with a 10MB size limit. HEIC and HEIF images are converted to JPEG before reaching the model provider.
File items (input_file) handle text, markdown, HTML, CSV, JSON, and PDF content up to 5MB. The Gateway decodes file content and adds it to the system prompt as untrusted external content wrapped in boundary markers. For PDFs, text extraction runs first. If the extracted text is under 200 characters, the Gateway rasterizes the first pages to images instead.
Function call output items (function_call_output) let you implement client-side tool loops. When the agent calls a function you defined, the response includes a function_call output item with a call_id. Send a follow-up request with the matching call_id and the tool's result to continue the conversation.
Beyond model and input, several optional fields shape request behavior:
instructionsadds text to the system prompt alongside any system-role messagestoolsdefines client-side function tools with name, description, and JSON Schema parameterstool_choicefilters which tools the agent can callstreamenables SSE output (covered in the streaming section below)temperatureandtop_padjust sampling parametersmax_output_tokenssets a best-effort length cap on the responseuserenables session persistence across requestsprevious_response_idcontinues from a specific earlier response in the same session
The Gateway also supports custom headers for fine-grained control. x-openclaw-model overrides which backend model the agent uses for a single request. x-openclaw-session-key sets the session key explicitly. x-openclaw-message-channel provides a synthetic ingress context for requests that do not originate from a standard messaging surface.
How to Choose an Authentication Mode
The Gateway supports three authentication strategies. Your choice depends on the deployment model and how much you trust the network path between client and Gateway.
Shared-Secret Auth Configure the Gateway for token or password authentication and pass the secret in the Authorization: Bearer header:
curl http://127.0.0.1:18789/v1/models \
-H 'Authorization: Bearer my-gateway-token'
This grants full operator access with six default scopes: operator.admin, operator.approvals, operator.pairing, operator.read, operator.talk.secrets, and operator.write. The Gateway ignores the x-openclaw-scopes header in this mode, so every request gets identical permissions. This is the simplest option for single-user setups and local development.
Trusted Identity-Bearing HTTP
This mode works behind reverse proxies like Tailscale Serve that inject verified identity headers into requests. The Gateway reads caller identity from those proxy headers and applies permissions accordingly. When the caller includes an x-openclaw-scopes header, the Gateway honors it to narrow permissions below the default set.
One detail to watch: loopback connections (127.0.0.1) need explicit opt-in in the Gateway configuration. Without enabling loopback trust, local clients behind a trusted proxy will be rejected even though they are on the same machine.
Private-Ingress Open Auth
When open authentication is enabled, no header is required, and any client that can reach the Gateway gets access. The Gateway still honors x-openclaw-scopes if provided, but there is no identity verification. Only use this where network-level controls already restrict who can connect.
### SSH tunnel for remote access without exposing the port publicly
ssh -N -L 18789:127.0.0.1:18789 your-server
Narrowing Permissions per Request In the trusted proxy and open auth modes, the x-openclaw-scopes header lets callers restrict permissions for individual requests. A frontend application could send x-openclaw-scopes: operator.read to limit a request to read-only operations, even when the caller would normally have broader access. In shared-secret mode this header has no effect.
Persist OpenClaw agent output across sessions and restarts
Free 50GB workspace with Intelligence Mode auto-indexing for semantic search. No credit card needed. Connect through the Fastio MCP server for agent reads, writes, and team handoff.
Streaming Responses and Error Handling
Set stream: true in your request body to receive server-sent events instead of a single JSON response. The Gateway sets the Content-Type to text/event-stream and emits structured events as the agent works.
curl -N http://127.0.0.1:18789/v1/responses \
-H 'Authorization: Bearer YOUR_TOKEN' \
-H 'Content-Type: application/json' \
-d '{"model": "openclaw", "stream": true, "input": "Explain cron job syntax"}'
Each SSE message follows the format event: <type> plus data: <json>. The stream terminates with data: [DONE]. Events arrive in a predictable lifecycle order:
response.createdconfirms the response object existsresponse.in_progresssignals the agent is runningresponse.output_item.addedfires when a new output item startsresponse.content_part.addedmarks the start of a content chunkresponse.output_text.deltadelivers incremental text tokens (this is the event to parse for real-time display)response.output_text.donesignals a text segment is completeresponse.content_part.doneandresponse.output_item.doneclose their respective containersresponse.completedends a successful run
If the agent hits an error mid-stream, you receive response.failed instead of response.completed. Your client should handle both terminal events and clean up accordingly.
Non-Streaming Error Responses
When streaming is off, errors return standard HTTP status codes with a JSON body:
{
"error": {
"message": "Missing or invalid authentication",
"type": "invalid_request_error"
}
}
Status 400 means a malformed request body. Status 401 means missing or invalid credentials. Status 405 means you sent the wrong HTTP method. Use the error.type field for programmatic handling rather than parsing the message string, which may change between Gateway versions.
URL Fetching Security
When you include URL-based images or files in your input, the Gateway fetches them server-side. DNS resolution validation and private IP blocking prevent SSRF attacks by default. Redirects are capped at 3 hops with a 10-second timeout per fetch. The Gateway configuration supports URL allowlists and the option to disable URL fetching entirely for tighter control.
Sessions, Automation, and Persistent Storage
Session Routing
By default, each POST /v1/responses call is stateless. The Gateway generates a fresh session key, runs the agent, and discards context after responding. To maintain conversation state across requests, include a user field with a stable identifier string. The Gateway derives a deterministic session key from this value, so all requests sharing the same user string route to one conversation thread.
For explicit control, the x-openclaw-session-key header sets the session key directly. And previous_response_id continues from a specific earlier response, which is useful when you need to branch or replay conversations.
Scheduling Tasks with Cron The Gateway includes a built-in cron system for recurring agent tasks. Job definitions persist across Gateway restarts. Through the WebSocket protocol, cron.add creates a new scheduled job, cron.update modifies its schedule or parameters, cron.remove deletes it, and cron.run triggers an immediate execution outside the normal schedule.
Each cron job runs in its own isolated session, keeping scheduled work separate from interactive conversations. Inspect run history through cron.runs to confirm your automation is executing on time and producing the expected output.
Event Hooks
Hooks fire when specific events happen inside the Gateway: a message arrives, a session compacts, the Gateway restarts, or a command executes. Each hook lives in its own directory with a HOOK.md metadata file and a handler.ts implementation. Five hooks ship pre-installed, including session-memory (saves the last 15 messages to workspace memory) and boot-md (runs startup instructions on launch).
The Gateway loads hooks from four locations in precedence order: bundled, plugin, managed, and workspace-local. Check the official Gateway documentation for hook directory paths and management commands.
Where to Put Agent Output
The Gateway handles conversation state and task execution, but it does not provide long-term file storage or team-level access controls for sharing output. If your agents produce reports, extracted data, or processed files, that output needs somewhere durable to land.
For single-machine setups, writing to the local filesystem works fine. S3 or GCS handles bulk storage if you already run cloud infrastructure. For workflows where agents build something that a human needs to review or download, Fastio provides shared workspaces with a free tier: 50GB of storage, included credits per month, and no credit card required. Agents connect through the Fastio MCP server or REST API. Intelligence Mode auto-indexes uploaded files for semantic search, so other agents or team members can query stored documents without managing a separate vector database.
For OpenClaw deployments running cron-scheduled tasks, persistent storage outside the Gateway means output survives restarts and session cleanup. Setup details for connecting OpenClaw workspaces to Fastio are at /storage-for-openclaw/.
Frequently Asked Questions
Does OpenClaw have an API?
Yes. The OpenClaw Gateway exposes an OpenResponses-compatible HTTP REST API with five core endpoints for agent interaction, model listing, embeddings, and chat completions. A WebSocket protocol adds session management, cron scheduling, hook automation, and skill management.
How do I authenticate with the OpenClaw API?
The Gateway supports three modes. Shared-secret auth passes a token or password as a Bearer header and grants full operator access. Trusted identity-bearing HTTP works behind reverse proxies like Tailscale Serve that inject verified identity headers. Private-ingress open auth requires no header at all, relying on network-level controls like VPN or SSH tunnels to restrict access.
What endpoints does the OpenClaw Gateway expose?
Five HTTP REST endpoints: POST /v1/responses for agent interaction, GET /v1/models and GET /v1/models/{id} for model discovery, POST /v1/embeddings for vector generation, and POST /v1/chat/completions for OpenAI-compatible chat. The WebSocket protocol extends this with methods across status, sessions, messages, cron, hooks, and skills categories.
Can I stream responses from the OpenClaw API?
Yes. Set stream to true in your request body. The Gateway returns server-sent events with incremental text tokens via the response.output_text.delta event type, plus lifecycle events for tracking response state. The stream ends with a data: [DONE] message.
How do I enable the /v1/responses endpoint?
Enable it through the Gateway configuration file. This endpoint is disabled by default. Once enabled, it runs on the same port as the rest of the Gateway, so there is no additional service to deploy.
What file types can I send to the OpenClaw API?
Images in JPEG, PNG, GIF, WebP, HEIC, or HEIF format up to 10MB, and files in text, markdown, HTML, CSV, JSON, or PDF format up to 5MB. Both accept base64-encoded data or URLs. PDFs go through text extraction first, with fallback to page rasterization when extracted text is insufficient.
Related Resources
Persist OpenClaw agent output across sessions and restarts
Free 50GB workspace with Intelligence Mode auto-indexing for semantic search. No credit card needed. Connect through the Fastio MCP server for agent reads, writes, and team handoff.