Skip to Content
PalpableDocs
For developers

Palpable WebSocket API (project API)

The Palpable project WebSocket API — discover a project's socket, connect with a pk_ project key, subscribe to live readings, variables and board status, set variables and run part commands. Messages, error codes and close codes.

Every project has a live WebSocket API. Your app can read the project's readings, variables and board status as they change, set a variable the project's script listens for, and run a part's command.

Get a key

Open the project in the Palpable app, open its settings (the gear), and choose Manage API.

Press New key, then Copy. The key starts with pk_ and is shown once.

Press Copy ID to copy the Project ID. Your app needs both.

A new key can only read. To let it also set variables, run part commands and use the camera, switch on Can control on its row. Its permissions are then ["read", "write"].

A key opens only the project it was made in. See API keys and connections to rename or revoke one.

Keep the key on a server or in a .env file, never in a web page or a prompt. More on keys in API keys and connections.

1. Discover the socket

GET https://palpable.technology/api/projects/{projectId}/connect
Authorization: Bearer pk_…
200 OK
{
  "wsUrl": "wss://agent.palpable.technology/session/…/ctx/3f9c…e21",
  "projectId": "3f9c…e21",
  "permissions": ["read", "write"]
}
FieldType
wsUrlstringWhere the project's socket is. It carries no credential.
projectIdstringThe project you asked for.
permissionsstring[]["read"] or ["read", "write"]. Information only: the socket checks the key again.

Use wsUrl exactly as given. Its host and path depend on the account, and differ on staging and development servers, so don't build it yourself.

StatusBody errorMeaning
401Missing or invalid credentialNo Authorization: Bearer header, or the token is not a key.
403API key is not valid for this projectAny key that can't open this project: unknown, revoked, or made in another project. They all get the same answer.
502Failed to resolve connectionPalpable could not find the socket. Try again.

A web page on any site can call /connect and saved readings directly, from the browser. Give a page a view-only key only: anyone who opens it can read the key. A key with Can control on belongs on your server, and the page asks your server.

2. Open the socket

Add the same key as token:

{wsUrl}?token=pk_…

The socket checks the key again. If it refuses, the socket opens and closes at once with code 4401, or 4403 when the project isn't served at that address. See Close codes.

The project's socket runs while Palpable is running for the account, which is always the case while one of its boards is online. If no board is online and nobody has the app open, the connection can be refused. Reconnect with a back-off.

3. Subscribe

Nothing is sent until you subscribe. Choose the channels you need:

{ "type": "subscribe", "channels": ["sensors", "variables", "status"] }
ChannelWhat arrives
sensorssensor_data for every reading from the project's boards. Camera motion and brightness also arrive here, and camera_event.
variablesvariable_state when the project's script shares values.
statusdevice_status when a board connects or disconnects or its parts change, and purpose when the project's purpose changes.
eventsbehavior_event for camera events (event is camera:<name>).

The answer is subscribed with all the channels you are now on, then a snapshot of the current state. Each subscribe sends a fresh snapshot.

Only the project's own boards reach its socket. A project with no boards gets an empty snapshot and nothing else.

Messages you send

typeFieldsNeedsAnswer
subscribechannels: string[]readsubscribed, then snapshot
unsubscribechannels: string[]readsubscribed
set_variablename: string, value: anywritenothing on success; error NO_BOARD if no board got it
invoke_commandmoduleId: string, command: string, params?: objectwritecommand_result, or error NO_BOARD / COMMAND_REFUSED
ping—readpong
camera_snapshot_requestcameraIdwritea camera_event with snapshot_ready
camera_stream_requestcameraId, offer (SDP)writecamera_stream_answer
camera_ice_candidatecameraId, candidatewritecamera_ice_candidate

set_variable

{ "type": "set_variable", "name": "waterNow", "value": true }

The variable goes to the project's connected boards. It does something only if the project's script reacts to it (p.onVariableChange('waterNow', …)). Ask PAL to add that to the script.

Nothing confirms a set_variable that reached a board. If none of the project's boards is connected, you get an error with code NO_BOARD. To see the new value, watch variable_state, if the script shares it.

invoke_command

Runs one of a part's commands, the same as the part's controls in the app. moduleId is the part's catalogue id, and command and params are that part's own. The catalogue's safety limits apply.

Turn a relay on
{ "type": "invoke_command", "moduleId": "qwiic-relay", "command": "on" }
Set every pixel to blue
{ "type": "invoke_command", "moduleId": "modulino-pixels", "command": "setAll", "params": { "r": 0, "g": 0, "b": 255 } }
Answer
{ "type": "command_result", "moduleId": "qwiic-relay", "command": "on", "boards": 1 }

boards is how many of the project's boards the command was sent to.

Messages you receive

typeFields
subscribedchannels: string[]
snapshotsensors: { [moduleId]: value }, variables: { [name]: value }, status: { connected, modules, boards }, purpose?
sensor_datachannel: "sensors", moduleId, value, timestamp (ms since epoch)
variable_statechannel: "variables", variables: { [name]: value }
device_statuschannel: "status", connected, modules, boards?
purposechannel: "status", purpose (object or null)
behavior_eventchannel: "events", event, data?, timestamp
camera_eventchannel: "sensors", cameraId, event, value?, path?, timestamp
command_resultmoduleId, command, boards
pong—
noticecode: "LEGACY_ACCOUNT_KEY", message. Sent once, after the first snapshot, to a socket opened with an account key.
errorcode, message

sensor_data carries the reading's value only, with no unit or name. Match moduleId against the modules in status. A variable_state holds the variables one board just shared, not always all of them: merge it into what you have.

In status, connected is true when at least one of the project's boards is connected. modules lists { moduleId, name, address, deviceId? } and boards lists { deviceId, connected }. A snapshot may come without purpose when Palpable has not read it yet; keep what you already show.

Error codes

codeWhen
FORBIDDENA write with a key that can only read.
INVALID_MESSAGENot JSON, an unknown type, or invoke_command without moduleId and command.
NO_BOARDA write reached none of the project's boards: the project has none, or none is connected.
COMMAND_REFUSEDinvoke_command named a part or command the boards don't have, or the catalogue's limits refused it. The message says which.
REMOVEDA message type that no longer exists (trigger_behavior). The message says what to use instead.
KEY_REVOKEDThe key was revoked. The socket closes next.
KEY_EXPIREDThe key has expired. The socket closes next.
NOT_FOUND, INTERNALReserved for server faults.

Close codes

CodeReasonMeaning
4401API key revokedRevoked in Manage API. Happens at once, on every open socket using the key. Don't reconnect with it.
4401API key expiredThe key passed its expiry. Don't reconnect with it.
4401API key maker no longer has access to the projectThe person who made the key can no longer open the project. Don't reconnect with it.
4401API key requiredThe address had no token.
4401API key not valid for this projectThe key is unknown, revoked, or made in another project. Don't reconnect with it.
4403Project is not served hereThe project's socket moved. Ask /connect for a new wsUrl.
4500Server errorPalpable could not check the key. Reconnect after a moment.

The last four arrive straight after the socket opens.

A socket opened from a shared page, not with a key, can also close with 4401 Link turned off (the owner turned the link off, or it expired), 4429 Too many people are watching, or 4503 Cannot check link (Palpable could not check the link just then; try again in a moment). A key never gets these.

Any other close is a network or server event. Reconnect.

A complete example

Node.js 22 or later, which has WebSocket built in. The key and project id come from the environment.

.env
PALPABLE_PROJECT_ID=3f9c…e21
PALPABLE_KEY=pk_…
app.mjs — run with: node --env-file=.env app.mjs
const KEY = process.env.PALPABLE_KEY;
const PROJECT = process.env.PALPABLE_PROJECT_ID;

// 1. Where is the project's socket?
const res = await fetch(`https://palpable.technology/api/projects/${PROJECT}/connect`, {
  headers: { Authorization: `Bearer ${KEY}` },
});
const found = await res.json();
if (!res.ok) throw new Error(`connect answered ${res.status}: ${found.error}`);
const { wsUrl, permissions } = found;

// 2. Open it with the same key.
const ws = new WebSocket(`${wsUrl}?token=${encodeURIComponent(KEY)}`);

ws.onopen = () => {
  ws.send(JSON.stringify({ type: 'subscribe', channels: ['sensors', 'variables', 'status'] }));
};

// 3. A snapshot first, then every change.
ws.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  switch (msg.type) {
    case 'snapshot':
      console.log('now:', msg.sensors, msg.variables, 'board online:', msg.status.connected);
      // 4. Set a variable the project's script listens for. Needs a key that can control.
      if (permissions.includes('write')) {
        ws.send(JSON.stringify({ type: 'set_variable', name: 'waterNow', value: true }));
      }
      break;
    case 'sensor_data':
      console.log(new Date(msg.timestamp).toISOString(), msg.moduleId, msg.value);
      break;
    case 'variable_state':
      console.log('variables:', msg.variables);
      break;
    case 'device_status':
      console.log('board online:', msg.connected);
      break;
    case 'error':
      console.error(msg.code, msg.message);
      break;
  }
};

ws.onclose = (e) => console.log('closed', e.code, e.reason);

On this page