Getting Started
Apinator provides WebSocket infrastructure for adding realtime features to any application. Publish events from your server, receive them instantly on connected clients.
The architecture is simple: your backend publishes events through the REST API using HMAC-signed requests, and clients subscribe to channels over WebSocket connections. Apinator handles fan-out, reconnection, and presence tracking.
You don't need a backend to see it work. The steps below get an event into your own client in about two minutes, using a public channel and the dashboard. Server code and channel auth come after that.
Your First Event
1. Get your app key and cluster. Open your app in the Apinator dashboard and copy its app key (it starts with app_) and its cluster: us or eu, the region the app was created in (new apps default to us). The app key is safe to put in client code; you won't need the secret yet.
2. Subscribe from a client. Install the client SDK and run the snippet below in any frontend: a Vite app, a framework component or a plain page with a bundler. my-channel is a public channel, so there is no auth endpoint and no server to set up.
3. Send a test event. Click the Send test event button on your app's Overview page in the dashboard. It publishes my-event to my-channel, and your client prints it.
No project at hand? Open https://apinator.io/try/?key=YOUR_APP_KEY&cluster=us in any browser, on your phone too. It runs the same client SDK and lists every event that arrives on my-channel.
If the cluster is wrong, the connection is refused straight away (close code 4010) with a message naming your app's cluster, logged to the browser console as [apinator] This app is in the "eu" region but connected to "us"…. Set cluster to the one it names. An unknown or mistyped key is refused the same way (code 4001), with a message saying what is wrong with it.
npm install @apinator/client Install import { Apinator } from '@apinator/client'
const client = new Apinator({
appKey: 'YOUR_APP_KEY', // from your app in the dashboard, starts with app_
cluster: 'us' // or 'eu': the cluster your app is in
})
client.connect()
client.subscribe('my-channel').bind('my-event', (data) => {
console.log('Received:', data)
})Publish From Your Server
Once the test event arrives, publish your own. Server SDKs sign each request with your app secret, so this code runs on your server, never in the browser. Copy the app ID, key and secret from the same app in the dashboard.
Save the first version as publish.mjs and run node publish.mjs (Node.js 18 or later). The .mjs extension is what allows import and top-level await. In a CommonJS file (a plain .js file without "type": "module" in package.json), use the second version. Either way, the client from the previous step prints the event.
The Overview page in the dashboard also has Copy signed curl: a ready-signed curl command for the same test event, for publishing from a terminal.
npm install @apinator/server Install import { Apinator } from '@apinator/server'
const apinator = new Apinator({
appId: 'YOUR_APP_ID',
key: 'YOUR_APP_KEY',
secret: 'YOUR_APP_SECRET', // keep it out of client code and git
cluster: 'us'
})
await apinator.trigger({
name: 'my-event',
channel: 'my-channel',
data: JSON.stringify({ message: 'Hello from my server' })
})
console.log('Published')const { Apinator } = require('@apinator/server')
const apinator = new Apinator({
appId: 'YOUR_APP_ID',
key: 'YOUR_APP_KEY',
secret: 'YOUR_APP_SECRET',
cluster: 'us'
})
async function main() {
await apinator.trigger({
name: 'my-event',
channel: 'my-channel',
data: JSON.stringify({ message: 'Hello from my server' })
})
console.log('Published')
}
main().catch((err) => {
console.error(err)
process.exitCode = 1
})Next: Private Channels
Public channels are open to anyone who has your app key, which is fine for live scores or a status feed. For anything per user, use a private channel (name starts with private-) or a presence channel (presence-). The client then asks your server to sign each subscription, so this is the step where you add an auth endpoint.
Point the client at that endpoint with authEndpoint. The endpoint signs the socket ID and channel name with your app secret; Channel Authorization has the full flow.
const client = new Apinator({
appKey: 'YOUR_APP_KEY',
cluster: 'us',
authEndpoint: '/api/realtime/auth'
})
client.connect()
client.subscribe('private-user-123').bind('new-alert', (data) => {
console.log('Received:', data)
})// POST /api/realtime/auth (apinator is the server client from the previous step)
const auth = apinator.authenticateChannel(
req.body.socket_id,
req.body.channel_name
)
res.json(auth)Installation
Install the client SDK in your frontend application and a server SDK in your backend. The client SDK connects via WebSocket; server SDKs sign API requests with HMAC.
npm install @apinator/client Client (Browser) npm install @apinator/server Server (Node.js) pip install apinator-server Server (Python) go get github.com/apinator-io/sdk-go Server (Go) Channels
Channels are the primary mechanism for organizing realtime messages. Clients subscribe to channels, and servers publish events to them. There are three channel types, each with different authorization and features. Public, private, and presence channels can also be cache channels, which remember their last event.
The channel type is determined by the name prefix. Keep channel names short and URL-safe (letters, digits, hyphens, underscores, dots) so they round-trip cleanly through the channel query endpoints.
| Type | Prefix | Auth Required | Use Case |
|---|---|---|---|
| Public | (none) | No | Broadcast data visible to all users |
| Private | private- | Yes | Restricted data for authorized users |
| Presence | presence- | Yes | Track who is online in a channel |
| Cache | cache- | No | Late subscribers get the last event |
| Private cache | private-cache- | Yes | Late subscribers get the last event, restricted to authorized users |
| Presence cache | presence-cache- | Yes | Presence tracking, and late subscribers get the last event |
Public Channels
Public channels require no authorization. Any connected client can subscribe. Use them for broadcasting publicly visible data such as live scores, stock tickers, or site-wide notifications.
const channel = client.subscribe('live-scores')
channel.bind('score-update', (data) => {
console.log(data.team, data.score)
})Private Channels
Private channels require server-side authorization before a client can subscribe. The client SDK sends an authorization request to your auth endpoint, which returns an HMAC signature if the user is permitted.
Prefix the channel name with private- to create a private channel.
const client = new Apinator({
appKey: 'your-app-key',
cluster: 'us',
authEndpoint: '/api/realtime/auth'
})
const channel = client.subscribe('private-user-123')// POST /api/realtime/auth
const auth = client.authenticateChannel(
req.body.socket_id,
req.body.channel_name
)
res.json(auth)Presence Channels
Presence channels extend private channels with member tracking. When a user subscribes, their identity is shared with other members. Presence channels track who is currently online and fire events when members join or leave.
Prefix the channel name with presence-. The auth endpoint must include channel_data containing the user's identity.
const auth = client.authenticateChannel(
req.body.socket_id,
req.body.channel_name,
JSON.stringify({
user_id: 'user-123',
user_info: { name: 'Alice' }
})
)Cache Channels
A cache channel remembers the last event published to it. When a client subscribes, it receives that event straight after the subscription succeeds, so a client that connects late still sees the latest state. Use them when an event can fire before the client is listening: a background job that finishes while the user is being redirected, the current status of an order, or the latest value of a live counter.
Prefix the channel name with cache- for a public cache channel, or private-cache- for one that needs channel authorization. Use presence-cache- for a presence channel that also caches. Private and presence cache channels use the same auth endpoint and signature as other private and presence channels, with nothing extra to set up. On a presence cache channel, member join and leave events are never cached, so the cached event is always one your app sent.
Only the most recent event is kept, not a history. Each publish replaces it, and it expires 30 minutes after the last publish. Client events sent on a private or presence cache channel are cached too. If nothing is cached, the client just receives no event, so keep a fallback (such as a status API call) for when the cache has expired.
Bind your handlers right after calling subscribe(). The cached event is delivered as soon as the subscription succeeds.
// Background job finishes, possibly before the browser has subscribed
await client.trigger({
name: 'job-finished',
channel: `private-cache-job-${jobId}`,
data: JSON.stringify({ status: 'done', posts: 12 })
})// After the redirect: receives the cached event even if the job already finished
const channel = client.subscribe(`private-cache-job-${jobId}`)
channel.bind('job-finished', (data) => {
showResult(data)
})Events
Events are the messages delivered through channels. Each event has a name and a data payload (JSON string). There are three categories of events: server events (published by your backend), client events (sent between clients), and system events (emitted by Apinator).
Server Events
Server events are published from your backend via the REST API. Avoid names starting with realtime: (reserved for system events) or client- (reserved for client events), because client SDKs route those prefixes differently. The data payload is a JSON string; the whole REST request body is capped at 1 MB.
await client.trigger({
name: 'new-message',
channel: 'chat-room',
data: JSON.stringify({ user: 'Alice', text: 'Hello, world!' })
})channel.bind('new-message', (data) => {
console.log(data.user, data.text)
})Client Events
Client events are sent directly from one client to others on the same channel, without going through your server. They must be on private or presence channels, and the event name must start with client-.
Client events are useful for features like typing indicators where server round-trips add unnecessary latency.
Client events are enabled by default and can be switched off per app under Settings in the console. They are not delivered to the sender, only to other subscribers on the channel.
channel.trigger('client-typing', {
user: 'Alice'
})System Events
System events are emitted by Apinator and prefixed with realtime:. The prefix is reserved for them, so do not publish events with it yourself. Use them to react to connection state and subscription lifecycle changes.
A realtime:subscription_error payload has the shape { type, error, status }. The JS and Swift clients also emit a local state_change event when the connection state changes (see Connection State below).
| Event | Description |
|---|---|
| realtime:subscription_succeeded | Subscription to a channel was authorized and completed |
| realtime:subscription_error | Subscription to a channel failed (auth rejected) |
| realtime:member_added | A new member joined a presence channel |
| realtime:member_removed | A member left a presence channel |
| realtime:connection_established | WebSocket connection was established; payload contains socket_id and activity_timeout |
| realtime:error | Connection-level error; payload contains a numeric code and a message |
Presence
Presence lets you track which users are currently subscribed to a channel. It is built on top of presence channels and provides member lists, join/leave events, and multi-tab deduplication.
Subscribing
Subscribe to a presence channel the same way as a private channel. The auth endpoint must return channel_data with a unique user_id and a user_info object.
For presence- names, subscribe() returns a PresenceChannel, which adds getMembers(), getMember(userId), memberCount, and me. In TypeScript, cast the result: client.subscribe('presence-room') as PresenceChannel.
const room = client.subscribe('presence-room')
room.bind('realtime:subscription_succeeded', () => {
console.log('Online:', room.memberCount)
for (const member of room.getMembers()) {
console.log(member.user_id, member.user_info)
}
console.log('Me:', room.me)
})Member Tracking
The member list is available after the realtime:subscription_succeeded event fires. Its payload is a snapshot of the form { presence: { count, ids, hash } }, where hash maps each user_id to its user_info. The client SDKs keep this snapshot up to date and expose each member as { user_id, user_info }.
Apinator handles multi-tab deduplication automatically. If a user opens multiple tabs, they appear as a single member. The member_removed event only fires when all of a user's connections leave.
Presence Events
Presence channels emit join and leave events so you can update your UI in real time. The realtime:member_added payload carries the full { user_id, user_info }; realtime:member_removed carries only { user_id }.
// payload: { user_id, user_info }
room.bind('realtime:member_added', (member) => {
console.log('Joined:', member.user_info.name)
})
// payload: { user_id } — look the user up before they leave if you need user_info
room.bind('realtime:member_removed', (member) => {
console.log('Left:', member.user_id)
})Server API
The Apinator server API is a REST API authenticated with HMAC-SHA256 signed requests. All requests must include the X-Realtime-Key, X-Realtime-Timestamp, and X-Realtime-Signature headers. The server SDKs handle signing automatically.
The base URL is https://ws-{cluster}.apinator.io, where {cluster} is the region your app was created in (us or eu). The same host serves the WebSocket endpoint over wss://. Requests for an app that lives in another region are rejected with HTTP 421 and a message naming the correct region.
Publish Events
Publish an event to one or more channels. The data payload is a JSON string; the whole request body is capped at 1 MB. A successful publish returns HTTP 200 with an empty JSON object.
| Field | Type | Description |
|---|---|---|
| channel | string | Target channel name |
| name | string | Event name (avoid the reserved realtime: and client- prefixes) |
| data | string | JSON-encoded payload (request body max 1 MB) |
| channels | string[] | Multiple channels (alternative to channel, max 100) |
| socket_id | string | Optional: exclude this connection from receiving the event |
POST /apps/{app_id}/events
Content-Type: application/json
{
"channel": "notifications",
"name": "new-alert",
"data": "{\"title\":\"Hello\"}"
}Channel Queries
Query channels that currently have at least one subscriber on this app, with their type and subscriber count. Useful for building admin dashboards or monitoring.
Use filter_by_prefix to filter channels by name prefix. Legacy prefix is removed and returns an error. Querying a single channel that has no subscribers returns HTTP 404.
GET /apps/{app_id}/channels?filter_by_prefix=private-
# Response
{
"channels": [
{ "name": "private-orders", "type": "private", "subscription_count": 42 }
]
}GET /apps/{app_id}/channels/{channel_name}
# Response (404 if nobody is subscribed)
{
"name": "private-orders",
"type": "private",
"subscription_count": 42
}Channel Auth Endpoint
If you would rather not sign channel auth in your own code, the data plane can do it for you. Send the socket_id and channel_name (plus channel_data for presence channels) with a normally signed API request and relay the response to your client.
Public channels are rejected with HTTP 400 because they need no auth. The server SDKs do the same computation locally with authenticateChannel, which avoids the extra round trip.
POST /apps/{app_id}/auth
Content-Type: application/json
{
"socket_id": "12345.67890",
"channel_name": "presence-room",
"channel_data": "{\"user_id\":\"123\",\"user_info\":{\"name\":\"Alice\"}}"
}
# Response
{
"auth": "app-key:hmac-signature",
"channel_data": "{\"user_id\":\"123\",\"user_info\":{\"name\":\"Alice\"}}"
}Contracts
Apinator is contract-first. OpenAPI and AsyncAPI files are the canonical source for SDK behavior, HTTP payloads, and WebSocket protocol expectations.
Breaking contract cleanup is active on current v1 endpoints: RFC 7807 error bodies, canonical path-only signing, and strict filter_by_prefix query behavior.
Contract Endpoints
These endpoints serve the machine-readable JSON contracts used by SDK developers and CI gates.
| Endpoint | Contract |
|---|---|
/api/v1/specs/asyncapi/realtime.json | AsyncAPI 2.6 realtime WebSocket contract |
/api/v1/specs/openapi/dataplane.json | OpenAPI 3 contract for the data plane HTTP API (publish, auth, channel queries) |
/documentation/sdk-authoring/ | SDK authoring rules and breaking contract notes |
Breaking Rules
RFC 7807 required: all REST API error responses use application/problem+json with type, title, status, and detail. Rejected WebSocket upgrades answer in plain text.
Channel query rule: only filter_by_prefix is valid for listing channels. Legacy prefix is not accepted.
Signing rule: HMAC request signatures are computed using canonical path only. Query strings are never part of the signature input.
SDK Conformance
Handwritten SDKs (Node, Python, Go, PHP) must conform to shared fixture vectors for request signing, channel auth, and webhook signatures. Error parsing is tested in each SDK's own suite.
See the dedicated SDK authoring guide for required behavior, test vectors, and CI gate expectations: SDK Authoring Guide.
JavaScript SDK
The JavaScript client SDK connects to Apinator via WebSocket from browsers. It handles automatic reconnection with exponential backoff, channel subscription management, and auth token negotiation.
Installation
Install via npm, yarn, or pnpm. Works with any bundler (webpack, Vite, esbuild, Rollup).
npm install @apinator/client npm Usage
Create a client instance, connect, then subscribe to channels and bind event handlers.
| Option | Type | Description |
|---|---|---|
| appKey | string | Your application key (required) |
| cluster | string | Region cluster: us, eu (required) |
| authEndpoint | string | URL for private/presence channel auth |
| authHeaders | object | Extra headers sent with auth requests |
| authEncoding | 'json' | 'form' | Auth request body encoding; form matches pusher-js (default: json) |
| activityTimeout | number | Seconds without server messages before pinging (default: server value, 120) |
| pongTimeout | number | Seconds to wait for a ping reply before reconnecting (default: 30) |
| enableReconnect | boolean | Enable auto-reconnect (default: true) |
| maxReconnectAttempts | number | Max consecutive reconnect attempts (default: unlimited) |
import { Apinator } from '@apinator/client'
const client = new Apinator({
appKey: 'your-app-key',
cluster: 'us',
authEndpoint: '/api/realtime/auth'
})
client.connect()
// Public channel
const alerts = client.subscribe('alerts')
alerts.bind('new-alert', (data) => showAlert(data))
// Private channel
const inbox = client.subscribe('private-inbox-123')
// Presence channel
const room = client.subscribe('presence-room')
room.bind('realtime:member_added', (m) => addUser(m))
// Disconnect
client.disconnect()Connection State
The client reconnects automatically with exponential backoff. Bind state_change on the client to react to the lifecycle: initialized → connecting → connected → disconnected / unavailable. unavailable means maxReconnectAttempts was exhausted.
client.socketId is available once connected and is what your auth endpoint signs. client.unsubscribe(name) leaves a channel and drops its bindings; subscriptions are restored automatically after a reconnect.
client.bind('state_change', ({ previous, current }) => {
console.log(`${previous} -> ${current}`)
})
client.connect()
console.log(client.state, client.socketId)
client.unsubscribe('alerts')Node.js SDK
The Node.js server SDK provides event publishing, channel authorization, and channel queries. Zero dependencies — uses Node.js built-in crypto and fetch (Node 18+).
Installation
Requires Node.js 18 or later.
npm install @apinator/server Install Usage
Initialize with your credentials, then use the client to publish events and sign channel auth.
import { Apinator } from '@apinator/server'
const client = new Apinator({
appId: 'your-app-id',
key: 'your-key',
secret: 'your-secret',
cluster: 'us'
})
// Publish an event
await client.trigger({
name: 'message',
channel: 'chat',
data: JSON.stringify({ text: 'Hello' })
})
// Authenticate a private channel
const auth = client.authenticateChannel(socketId, channelName)
// Query channels
const channels = await client.getChannels('private-')
const chat = await client.getChannel('chat')
console.log(chat.subscription_count)Python SDK
The Python server SDK provides event publishing, channel authorization, and channel queries. Zero dependencies — uses only the standard library. Requires Python 3.10+.
Installation
Install from PyPI.
pip install apinator-server Install Usage
Initialize the client and use it to publish events or authenticate channels.
from apinator import Apinator
client = Apinator(
app_id='your-app-id',
key='your-key',
secret='your-secret',
cluster='us'
)
# Publish an event
client.trigger('message', '{"text": "Hello"}', channel='chat')
# Authenticate a private channel
auth = client.authenticate_channel(socket_id, channel_name)
# Query channels
channels = client.get_channels(prefix='private-')
info = client.get_channel('chat')Go SDK
The Go server SDK provides event publishing, channel authorization, and channel queries. Zero dependencies — uses only the standard library. Requires Go 1.21+ and uses the functional options pattern.
Installation
Install with go get.
go get github.com/apinator-io/sdk-go Install Usage
Create a client with app credentials and cluster, then trigger events and authenticate channels.
import apinator "github.com/apinator-io/sdk-go"
client := apinator.NewClient(
"your-app-id",
"your-key",
"your-secret",
"us",
)
// Publish an event
err := client.Trigger(ctx, apinator.TriggerParams{
Name: "message",
Channel: "chat",
Data: "{\"text\":\"Hello\"}",
})
// Authenticate a channel
auth := client.AuthenticateChannel(socketID, channelName, nil)PHP SDK
The PHP server SDK provides event publishing, channel authorization, and channel queries. Zero dependencies, PHP 8.1+, with PSR-4 autoloading.
Installation
Install via Composer.
composer require apinator/apinator-php Install Usage
Create an Apinator instance with your app credentials and cluster, then publish events.
use Apinator\Apinator;
$client = new Apinator(
appId: 'your-app-id',
key: 'your-key',
secret: 'your-secret',
cluster: 'us'
);
// Publish an event
$client->trigger('message', '{"text": "Hello"}', channel: 'chat');
// Authenticate a channel
$auth = $client->authenticateChannel($socketId, $channelName);Swift SDK
The Swift client SDK connects to Apinator via WebSocket from iOS and macOS apps. It uses URLSessionWebSocketTask and supports iOS 13+ / macOS 10.15+. Distributed via Swift Package Manager.
Installation
Add the package via SPM in Xcode or your Package.swift.
.package(url: "https://github.com/apinator-io/sdk-swift", from: "1.0.0")Usage
Create a client, connect, then subscribe to channels.
import ApinatorSDK
let client = Apinator(options: RealtimeOptions(
appKey: "your-app-key",
cluster: "us",
authEndpoint: "https://your-server.com/api/realtime/auth"
))
client.connect()
let channel = client.subscribe("notifications")
channel.bind("new-alert") { data in
print("Received: \(data)")
}MCP Server
@apinator/mcp is a Model Context Protocol server for Apinator. It lets an AI coding agent (Claude Code, Claude Desktop, Cursor and other MCP clients) publish events, inspect channels, watch live traffic and set up webhooks on your app, so it can build and debug realtime features end to end.
Besides the tools below, the server exposes two resources, apinator://docs/llms.txt (this site's docs index) and apinator://reference/protocol (frames, system events, error codes, channel types and the auth signature), and an add-realtime-feature prompt that walks the agent through choosing channels, wiring the server and client SDKs, verifying the result with watch_channel, and adding a webhook receiver when the backend needs one.
Installation
Requires Node.js 18 or later. You need your app's ID, key, secret and cluster from the Apinator console.
With Claude Code, register the server from the command line:
claude mcp add apinator \
-e APINATOR_APP_ID=your-app-id \
-e APINATOR_KEY=your-key \
-e APINATOR_SECRET=your-secret \
-e APINATOR_CLUSTER=eu \
-- npx -y @apinator/mcp Claude Code {
"mcpServers": {
"apinator": {
"command": "npx",
"args": ["-y", "@apinator/mcp"],
"env": {
"APINATOR_APP_ID": "your-app-id",
"APINATOR_KEY": "your-key",
"APINATOR_SECRET": "your-secret",
"APINATOR_CLUSTER": "eu"
}
}
}
}Environment Variables
The server reads its configuration from environment variables, passed with -e in Claude Code or under env in the JSON config.
The server checks these variables at startup and exits with a message naming anything missing or malformed.
| Variable | Required | Description |
|---|---|---|
APINATOR_APP_ID | yes | App ID |
APINATOR_KEY | yes | API key |
APINATOR_SECRET | yes | API secret. Used to sign requests; never returned by any tool |
APINATOR_CLUSTER | yes | Region the app was created in, e.g. eu or us |
APINATOR_READ_ONLY | no | 1 removes publish_event and the webhook write tools, so the agent can only observe |
APINATOR_API_URL | no | REST base URL of a local or self-hosted data plane (default https://ws-{cluster}.apinator.io) |
APINATOR_WS_URL | no | WebSocket base URL of a local or self-hosted data plane (default wss://ws-{cluster}.apinator.io) |
APINATOR_CONTROL_URL | no | Base URL of a local or self-hosted control plane, used by the webhook tools (default https://api.apinator.io) |
Tools
list_channels, get_channel, sign_channel_auth, watch_channel, list_webhooks and list_webhook_deliveries are annotated readOnlyHint, so clients can auto-approve them; delete_webhook is annotated destructiveHint.
A typical end-to-end check an agent runs: start watch_channel on a channel, trigger the code path that publishes (or call publish_event), and compare the payload with what the client expects. On cache- channels the last event is replayed to new subscribers, so a watch started after a publish still receives it.
The webhook tools manage this app's webhook endpoints on the control plane, signed with the same app key and secret. A typical setup: add a POST route that verifies the raw body with verifyWebhook and returns 2xx, call add_webhook with its public URL, store the returned secret as APINATOR_WEBHOOK_SECRET, then test_webhook. Webhook URLs must be reachable from the internet; private and loopback addresses are refused, so expose a local dev server with a tunnel (cloudflared, ngrok). Secret rotation and delivery retries stay in the console.
| Tool | What it does |
|---|---|
publish_event | Publish an event to a channel, or up to 100 channels. data can be an object or array (sent as JSON) or a string. Optional socket_id excludes the sender. realtime: event names are rejected. Not available in read-only mode. |
list_channels | Active channels (with at least one subscriber) and their subscriber counts, optionally filtered by prefix. |
get_channel | One channel's subscriber count, or active: false when nobody is subscribed. |
sign_channel_auth | The auth (and channel_data) your auth endpoint should return for a private- or presence- subscription. Handy for testing an auth flow or debugging a signature mismatch. |
watch_channel | Connects over WebSocket, subscribes (signing private/presence auth itself), and collects events for seconds (default 10, max 60). Keeps up to max_events (default 50, max 200); until_events returns early. Sends MCP progress notifications every 5 seconds, so clients that reset their timeout on progress can wait out a long watch. On presence channels the watcher joins as a member, which other subscribers will see. |
list_webhooks | The app's webhook endpoints (max 10): id, URL, events and whether each is enabled. Signing secrets are never listed. |
add_webhook | Register an endpoint url for events (channel_occupied, channel_vacated, member_added, member_removed). Returns its whsec_ signing secret, shown only this once, for the app's environment. Refuses a URL that is already registered. Not available in read-only mode. |
edit_webhook | Change an endpoint's url, events or enabled. The secret stays the same. Not available in read-only mode. |
delete_webhook | Delete an endpoint. Not available in read-only mode. |
test_webhook | Send one signed webhook.test event now and report the receiver's HTTP status and timing. Not available in read-only mode. |
list_webhook_deliveries | Recent deliveries to one endpoint (status, attempts, last error), optionally filtered by status. |
Read-only Mode
publish_event reaches every subscriber of the channel. Set APINATOR_READ_ONLY=1 for an agent that should only look, or use a separate app for development. In read-only mode publish_event and the webhook write tools (add_webhook, edit_webhook, delete_webhook, test_webhook) are not registered at all; the other tools keep working.
The app secret can manage the app's webhooks. Anyone holding it can point an endpoint at their own URL and receive channel names and presence user_ids from then on, so treat it like any server secret. It cannot read an existing endpoint's signing secret (only add_webhook returns one, once), so it cannot forge deliveries to a receiver you already set up.
The secret stays in the server process. Tool results and errors are scrubbed of it, and API error bodies are shortened to a one-line message.
sign_channel_auth produces valid subscription signatures for any channel name, in read-only mode too. Only give the server to agents you would trust with your app's auth endpoint.
claude mcp add apinator \
-e APINATOR_READ_ONLY=1 \
-e APINATOR_APP_ID=your-app-id \
-e APINATOR_KEY=your-key \
-e APINATOR_SECRET=your-secret \
-e APINATOR_CLUSTER=eu \
-- npx -y @apinator/mcp Read-only (Claude Code) Authentication
Apinator uses HMAC-SHA256 for all authentication. There are two authentication contexts: API request signing (server-to-Apinator) and channel authorization (client subscription to private/presence channels).
API Request Signing
Every API request from your server must include three headers. The server SDKs generate these automatically.
The signature is computed over a string containing the timestamp, HTTP method, canonical path (without query string), and an MD5 hash of the request body.
Send requests to the regional host your app belongs to. The data plane answers HTTP 421 when an app from another region is addressed, and HTTP 401 for a missing or invalid signature. All error bodies are RFC 7807 application/problem+json.
| Header | Description |
|---|---|
| X-Realtime-Key | Your application API key |
| X-Realtime-Timestamp | Unix timestamp (seconds). Must be within 300s of server time. |
| X-Realtime-Signature | HMAC-SHA256 hex digest of the signature string |
body_md5 = len(body) == 0 ? "" : hex(md5(body))
canonical_path = path_without_query(request_url)
sig_string = "{timestamp}\n{METHOD}\n{canonical_path}\n{body_md5}"
signature = hex(hmac_sha256(secret, sig_string))Channel Authorization
When a client subscribes to a private or presence channel, it sends an auth request to your endpoint. Your server validates the user and returns an HMAC signature.
For private channels, the signature input is {socket_id}:{channel_name}. For presence channels, append :{channel_data} where channel_data is a JSON string with a user_id string and a user_info object, both of which the JS and Swift clients require.
The channel_data field is only required for presence channels. Omit it for private channels.
{
"auth": "app-key:hmac-signature",
"channel_data": "{\"user_id\":\"123\",\"user_info\":{\"name\":\"Alice\"}}"
}Data Handling
Apinator relays events. It does not keep a message history. The data of an event you publish through the REST API, or of a client event sent from a browser, is delivered to the clients subscribed at that moment and then dropped. It is not written to a database, and server logs never contain event data. A client that is offline when an event is sent does not receive it later. If you need a history, save each event in your own database when your server publishes it.
A few things are kept for a short time, in the Redis store of the region your app was created in: eu is Nuremberg, Germany, and us is Ashburn, Virginia. Redis writes a snapshot of its memory to that server’s disk about once a minute, so these items can also be in the snapshot until they expire. Each of them is listed below.
Webhook deliveries are the one exception: they are stored in Apinator’s central database rather than in the regional Redis store, so that failed deliveries can be retried and the console can show delivery history. They hold the webhook body (event name, channel name, and the user_id for presence events), never the data of events you publish.
Channel names are not treated as private: they appear in server logs and in channel queries. Use an opaque ID in a channel name (private-order-8f3a2c) rather than an email address or other personal data. The data field is relayed exactly as you send it, so to keep a payload unreadable outside your own systems, encrypt it before you publish.
| What | What is kept | How long |
|---|---|---|
| Cache channels | The last event published to each cache-, private-cache- or presence-cache- channel, including its data | Replaced by every publish. Deleted 30 minutes after the last publish. |
| Presence channels | The user_id and user_info your auth endpoint returns for each member | While the member is subscribed. Removed when they leave. If the server holding their connection fails, removed about a minute later, or once the region is back up if no other server was running. |
| Server logs | App IDs, channel names and error details. Never event data. | Up to 30 days |
| Webhook deliveries | For each delivery to an endpoint: the webhook body, the number of attempts and the last error | Kept for 7 days |
| Usage records | Message and connection counts per app. Never content. | Up to 12 months |
Webhooks
Webhooks tell your server about activity in your app: a channel gets its first subscriber or loses its last one, or a user joins or leaves a presence channel. Apinator sends each event as a signed HTTP POST to the endpoints you configure. Webhooks are available on all plans.
To add an endpoint, open your app in the console, go to the Webhooks tab and click Add endpoint. Enter an HTTPS or HTTP URL and choose which events to send to it. An app can have up to 10 endpoints. Each endpoint has its own signing secret, which starts with whsec_; the console shows it and can rotate it. You can edit an endpoint later, or disable it without deleting it.
Click Send test on an endpoint to send it a webhook.test event, which checks that the URL is reachable and that your signature check passes. Changes to an endpoint’s configuration take effect within about 15 seconds.
A coding agent can also set endpoints up for you through the MCP server: add_webhook, edit_webhook, delete_webhook and test_webhook do the same as the console, signed with the app’s key and secret.
Endpoint URLs must resolve to public IP addresses. A URL that resolves to a private or loopback address, such as localhost, 127.0.0.1 or 192.168.1.10, is rejected.
Events
An endpoint receives only the events selected for it. Occupancy events follow the whole channel, not one server: channel_occupied is sent once when the channel goes from no subscribers to one, wherever that subscriber is connected. Member events follow users, not connections, so a user with several tabs open on a presence channel produces one member_added and one member_removed.
Respond with a 2xx status to events you do not handle, including webhook.test. Any other response counts as a failure and is retried.
| Event | Sent when |
|---|---|
channel_occupied | The first subscriber joins a channel, anywhere in the cluster. |
channel_vacated | The last subscriber leaves a channel. |
member_added | A user joins a presence channel: the first connection for that user_id. More tabs or devices for the same user do not send it again. |
member_removed | A user’s last connection leaves a presence channel, including when it disconnects or times out. |
webhook.test | You click Send test on the endpoint in the console. |
Request Format
Each request is a POST with Content-Type: application/json and carries exactly one event. The body is a JSON object with the fields below. user_id is only present on member_added and member_removed.
| Field | Description |
|---|---|
id | Unique ID of the event. It stays the same when a delivery is retried, so use it to skip events you have already handled. |
event | The event name, such as member_added. |
app_id | The ID of the app the event belongs to. |
channel | The channel the event happened on. |
user_id | The presence member’s user_id, as your auth endpoint returned it. Only on member events. |
time_ms | When the event happened, in Unix milliseconds. Use it to put events back in order. |
{
"id": "6f1c…",
"event": "member_added",
"app_id": "…",
"channel": "presence-room",
"user_id": "42",
"time_ms": 1760000000000
}Verifying Signatures
Check the signature of every request before you act on it. Requests are signed with the endpoint’s webhook secret (whsec_…), not with your app’s API secret. The signature is an HMAC-SHA256 of the X-Realtime-Timestamp value, a dot, and the raw request body.
Verify against the raw body bytes exactly as they arrived. Parsing the JSON and serializing it again changes the bytes, and the signature will no longer match, so read the raw body before any JSON body parser runs. Reject requests whose timestamp is more than 5 minutes old, so a captured request cannot be replayed later. The server SDK helpers do both checks when you pass a maximum age of 300 seconds.
The Node.js, Python and Go helpers return false for a missing header, a stale timestamp or a wrong signature. The PHP helper Webhook::verify throws a ValidationException for a missing header or a stale timestamp, and returns false for a wrong signature, so handle both outcomes.
Keep each endpoint’s secret in an environment variable such as APINATOR_WEBHOOK_SECRET. The secret is per endpoint, so a server that receives from two endpoints must check each request against the right one. After you rotate a secret in the console, update it on your server.
| Header | Description |
|---|---|
| X-Realtime-Signature | sha256= followed by the hex HMAC-SHA256 of {timestamp}.{raw_body}, keyed with the webhook secret |
| X-Realtime-Timestamp | Unix timestamp (seconds) at which the request was signed |
| X-Realtime-Event | The event name, such as member_added |
| X-Realtime-Delivery-ID | ID of this endpoint’s delivery of the event. The same on every retry. |
input = "{X-Realtime-Timestamp}.{raw_body}"
signature = hex(hmac_sha256(webhook_secret, input))
header = "sha256=" + signatureimport express from 'express'
import { verifyWebhook } from '@apinator/server'
const app = express()
// express.raw() keeps the exact bytes that were signed; do not use express.json() on this route
app.post('/webhooks/apinator', express.raw({ type: 'application/json' }), (req, res) => {
const rawBody = req.body.toString('utf8')
if (!verifyWebhook(process.env.APINATOR_WEBHOOK_SECRET, req.headers, rawBody, 300)) {
return res.status(401).send('Invalid signature')
}
const event = JSON.parse(rawBody)
// Skip event.id if already handled, then act on event.event
res.sendStatus(204)
})import json
import os
from flask import Flask, request
from apinator import verify_webhook
app = Flask(__name__)
@app.post("/webhooks/apinator")
def apinator_webhook():
raw_body = request.get_data(as_text=True)
secret = os.environ["APINATOR_WEBHOOK_SECRET"]
if not verify_webhook(secret, dict(request.headers), raw_body, max_age=300):
return "Invalid signature", 401
event = json.loads(raw_body)
# Skip event["id"] if already handled, then act on event["event"]
return "", 204import (
"encoding/json"
"io"
"net/http"
"os"
"time"
apinator "github.com/apinator-io/sdk-go"
)
func apinatorWebhook(w http.ResponseWriter, r *http.Request) {
// Read the raw body before decoding it
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "cannot read body", http.StatusBadRequest)
return
}
secret := os.Getenv("APINATOR_WEBHOOK_SECRET")
if !apinator.VerifyWebhook(secret, r.Header, body, 5*time.Minute) {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
var event map[string]any
if err := json.Unmarshal(body, &event); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
// Skip event["id"] if already handled, then act on event["event"]
w.WriteHeader(http.StatusNoContent)
}use Apinator\Errors\ValidationException;
use Apinator\Webhook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::post('/webhooks/apinator', function (Request $request) {
$rawBody = $request->getContent();
$headers = [
'X-Realtime-Signature' => $request->header('X-Realtime-Signature'),
'X-Realtime-Timestamp' => $request->header('X-Realtime-Timestamp'),
];
try {
// Throws on a missing header or a stale timestamp; returns false on a wrong signature
$valid = Webhook::verify(config('services.apinator.webhook_secret'), $headers, $rawBody, 300);
} catch (ValidationException $e) {
$valid = false;
}
if (!$valid) {
return response('Invalid signature', 401);
}
$event = json_decode($rawBody, true);
// Skip $event['id'] if already handled, then act on $event['event']
return response()->noContent();
});Delivery and Retries
A delivery succeeds when your endpoint returns any 2xx status within 10 seconds. Anything else is a failure: another status, a timeout, a connection error, or a redirect. Redirects are not followed, so a 3xx response also counts as failed. Return quickly and do slow work afterwards, for example in a background job.
A failed delivery is retried, up to 7 attempts in all, on the schedule below. Each delay varies by up to 20% either way. After the seventh attempt, about 9 hours after the first, the delivery is marked failed. You can retry a failed delivery from the console, which makes one more attempt.
Delivery is at least once, so the same event can reach your endpoint more than once, for example when your server handled it but the response did not arrive in time. Make your handler idempotent: record the id of each event you process and skip any you have already seen. X-Realtime-Delivery-ID works too, per endpoint.
Events are not guaranteed to arrive in order. A retried channel_occupied can arrive after the channel_vacated that followed it. Order events by time_ms, and ignore one that is older than the last event you applied for that channel or member.
The console shows each endpoint’s deliveries from the last 7 days.
| Attempt | Sent |
|---|---|
| 1 | Immediately |
| 2 | About 10 seconds after attempt 1 |
| 3 | About 1 minute after attempt 2 |
| 4 | About 5 minutes after attempt 3 |
| 5 | About 30 minutes after attempt 4 |
| 6 | About 2 hours after attempt 5 |
| 7 | About 6 hours after attempt 6 |
Limits
Every app runs on the free plan with the limits below. Concurrent connections and message size are enforced by the data plane: a connection beyond the cap is refused with HTTP 429 at the upgrade (or closed with code 1013 if it loses a race for the last slot), and a WebSocket message from a client over 256 KB closes the connection with code 1009. REST API request bodies are capped at 1 MB. The remaining figures are the plan allowances; if you expect to exceed them, get in touch.
Free Tier Limits
Apinator has a single free tier. The following limits apply per application.
The data plane does not currently return X-RateLimit-* headers; publish requests are accepted as long as the signature is valid and the app is enabled.
| Resource | Limit |
|---|---|
| Concurrent connections | 500 |
| Messages per day | 500,000 |
| Client events per second | 500 |
| Max WebSocket message size (client to server) | 256 KB |
| Max REST request body | 1 MB |
| Max channels | 100 |
| Max presence members per channel | 500 |