# Palpable WebSocket API (project API) (https://docs.palpable.technology/docs/developers/project-api)

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 [#get-a-key]

<Steps>
<Step>
Open the project in the Palpable app, open its settings (the gear), and choose **Manage API**.
</Step>

<Step>
Press **New key**, then **Copy**. The key starts with `pk_` and is shown once.
</Step>

<Step>
Press **Copy ID** to copy the **Project ID**. Your app needs both.
</Step>

<Step>
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"]`.
</Step>
</Steps>

A key opens only the project it was made in. See [API keys and connections](/docs/developers/api-keys) 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](/docs/developers/api-keys).

## 1. Discover the socket [#1-discover-the-socket]

```http
GET https://palpable.technology/api/projects/{projectId}/connect
Authorization: Bearer pk_…
```

```json title="200 OK"
{
  "wsUrl": "wss://agent.palpable.technology/session/…/ctx/3f9c…e21",
  "projectId": "3f9c…e21",
  "permissions": ["read", "write"]
}
```

| Field | Type | |
| --- | --- | --- |
| `wsUrl` | string | Where the project's socket is. It carries no credential. |
| `projectId` | string | The project you asked for. |
| `permissions` | string[] | `["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.

| Status | Body `error` | Meaning |
| --- | --- | --- |
| `401` | `Missing or invalid credential` | No `Authorization: Bearer` header, or the token is not a key. |
| `403` | `API key is not valid for this project` | Any key that can't open this project: unknown, revoked, or made in another project. They all get the same answer. |
| `502` | `Failed to resolve connection` | Palpable could not find the socket. Try again. |

A web page on any site can call `/connect` and [saved readings](/docs/developers/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 [#2-open-the-socket]

Add the same key as `token`:

```txt
{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](#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 [#3-subscribe]

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

```json
{ "type": "subscribe", "channels": ["sensors", "variables", "status"] }
```

| Channel | What arrives |
| --- | --- |
| `sensors` | `sensor_data` for every reading from the project's boards. Camera motion and brightness also arrive here, and `camera_event`. |
| `variables` | `variable_state` when the project's script shares values. |
| `status` | `device_status` when a board connects or disconnects or its parts change, and `purpose` when the project's purpose changes. |
| `events` | `behavior_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 [#messages-you-send]

| `type` | Fields | Needs | Answer |
| --- | --- | --- | --- |
| `subscribe` | `channels`: string[] | read | `subscribed`, then `snapshot` |
| `unsubscribe` | `channels`: string[] | read | `subscribed` |
| `set_variable` | `name`: string, `value`: any | write | nothing on success; `error` `NO_BOARD` if no board got it |
| `invoke_command` | `moduleId`: string, `command`: string, `params`?: object | write | `command_result`, or `error` `NO_BOARD` / `COMMAND_REFUSED` |
| `ping` | — | read | `pong` |
| `camera_snapshot_request` | `cameraId` | write | a `camera_event` with `snapshot_ready` |
| `camera_stream_request` | `cameraId`, `offer` (SDP) | write | `camera_stream_answer` |
| `camera_ice_candidate` | `cameraId`, `candidate` | write | `camera_ice_candidate` |

### set_variable [#set_variable]

```json
{ "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 [#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.

```json title="Turn a relay on"
{ "type": "invoke_command", "moduleId": "qwiic-relay", "command": "on" }
```

```json title="Set every pixel to blue"
{ "type": "invoke_command", "moduleId": "modulino-pixels", "command": "setAll", "params": { "r": 0, "g": 0, "b": 255 } }
```

```json title="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 [#messages-you-receive]

| `type` | Fields |
| --- | --- |
| `subscribed` | `channels`: string[] |
| `snapshot` | `sensors`: `{ [moduleId]: value }`, `variables`: `{ [name]: value }`, `status`: `{ connected, modules, boards }`, `purpose`? |
| `sensor_data` | `channel: "sensors"`, `moduleId`, `value`, `timestamp` (ms since epoch) |
| `variable_state` | `channel: "variables"`, `variables`: `{ [name]: value }` |
| `device_status` | `channel: "status"`, `connected`, `modules`, `boards`? |
| `purpose` | `channel: "status"`, `purpose` (object or `null`) |
| `behavior_event` | `channel: "events"`, `event`, `data`?, `timestamp` |
| `camera_event` | `channel: "sensors"`, `cameraId`, `event`, `value`?, `path`?, `timestamp` |
| `command_result` | `moduleId`, `command`, `boards` |
| `pong` | — |
| `notice` | `code: "LEGACY_ACCOUNT_KEY"`, `message`. Sent once, after the first snapshot, to a socket opened with an account key. |
| `error` | `code`, `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 [#error-codes]

| `code` | When |
| --- | --- |
| `FORBIDDEN` | A write with a key that can only read. |
| `INVALID_MESSAGE` | Not JSON, an unknown `type`, or `invoke_command` without `moduleId` and `command`. |
| `NO_BOARD` | A write reached none of the project's boards: the project has none, or none is connected. |
| `COMMAND_REFUSED` | `invoke_command` named a part or command the boards don't have, or the catalogue's limits refused it. The message says which. |
| `REMOVED` | A message type that no longer exists (`trigger_behavior`). The message says what to use instead. |
| `KEY_REVOKED` | The key was revoked. The socket closes next. |
| `KEY_EXPIRED` | The key has expired. The socket closes next. |
| `NOT_FOUND`, `INTERNAL` | Reserved for server faults. |

### Close codes [#close-codes]

| Code | Reason | Meaning |
| --- | --- | --- |
| `4401` | `API key revoked` | Revoked in **Manage API**. Happens at once, on every open socket using the key. Don't reconnect with it. |
| `4401` | `API key expired` | The key passed its expiry. Don't reconnect with it. |
| `4401` | `API key maker no longer has access to the project` | The person who made the key can no longer open the project. Don't reconnect with it. |
| `4401` | `API key required` | The address had no `token`. |
| `4401` | `API key not valid for this project` | The key is unknown, revoked, or made in another project. Don't reconnect with it. |
| `4403` | `Project is not served here` | The project's socket moved. Ask `/connect` for a new `wsUrl`. |
| `4500` | `Server error` | Palpable 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 [#a-complete-example]

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

```bash title=".env"
PALPABLE_PROJECT_ID=3f9c…e21
PALPABLE_KEY=pk_…
```

```js title="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);
```