Documentation
Project Context API

Project Context API

A real-time WebSocket API for one project: its live sensor readings, its variables, its events and the state of its boards, plus a way to send values back to the project's scripts.

Use it for dashboards, integrations and display previews. Each connection is for one project and sees only that project's boards.

⚠️

An API key is a password for your project. Keep it in a .env file on a server you control. Never paste it into a chat, an AI prompt, a web page or browser code, and never commit it to git. If a key leaks, revoke it in the app: every connection using it closes within a second or two.

Quick Start

1. Create a key for the project

In the Palpable app, open the project, then ⋯ (project menu) → Access → Apps → Add an app. Give it a name and choose what it can do (more in API Keys):

In the appPermissionsWhat it can do
Can view["read"]Receive the project's readings, variables, events and status
Can control["read", "write"]Also set variables, run module commands and request camera frames

The key is shown once. Copy it into your .env file:

# .env
PALPABLE_PROJECT_ID=550e8400-e29b-41d4-a716-446655440000
PALPABLE_API_KEY=pk_…

2. Discover the WebSocket URL

// Node / a server — never in browser code.
const projectId = process.env.PALPABLE_PROJECT_ID
const apiKey = process.env.PALPABLE_API_KEY
 
const res = await fetch(`https://palpable.technology/api/projects/${projectId}/connect`, {
  headers: { Authorization: `Bearer ${apiKey}` },
})
if (!res.ok) throw new Error(`connect: ${res.status} ${(await res.json()).error}`)
const { wsUrl, permissions } = await res.json()

Response:

{
  "wsUrl": "wss://agent.palpable.technology/session/{ownerId}/ctx/{projectId}",
  "projectId": "550e8400-...",
  "permissions": ["read"]
}
StatusMeaning
200The key opens this project
401No credential, or not one at all
403The key does not open this project — it is for another project, revoked, expired or unknown. error says which

A legacy account key (see below) also gets "legacy": true and a notice explaining what to do.

3. Connect and subscribe

Open wsUrl with your key as the token query parameter:

import WebSocket from 'ws'
 
const ws = new WebSocket(`${wsUrl}?token=${apiKey}`)
 
ws.on('open', () => {
  ws.send(JSON.stringify({ type: 'subscribe', channels: ['sensors', 'variables', 'events', 'status'] }))
})
ws.on('message', (data) => {
  const msg = JSON.parse(data)
  console.log(msg.type, msg)
})
ws.on('close', (code, reason) => console.log('closed', code, reason.toString()))

What a connection sees

A project's boards are the ones assigned to it in the app (⋯ → Manage devices). A connection for the project receives readings, variables, events and status from those boards only, and anything it sends reaches those boards only — never another project's, even one of your own.

  • A board that belongs to two of your projects is seen by both.
  • A project with no boards receives nothing; its status.boards is [], and a write is answered with a NO_BOARD error.
  • status.connected is true when at least one of the project's boards is connected.

Channels

ChannelWhat arrives
sensorssensor_data readings, and camera_event frames
variablesvariable_state — values the project's scripts publish with p.setVariable
eventsbehavior_event frames (today: camera events such as camera:motion)
statusdevice_status (the project's boards and their modules) and purpose

You receive only the channels you subscribed to.

WebSocket Protocol

Client to server

subscribe / unsubscribe

{ "type": "subscribe", "channels": ["sensors", "variables"] }
{ "type": "unsubscribe", "channels": ["events"] }

subscribe answers with subscribed and then a snapshot of the current state.

set_variable

Set a variable on the project's boards. Requires write. The project's scripts receive it in p.onVariableChange (see Sending a command to a script).

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

invoke_command

Run one module command on the project's boards — the same command a script or the app's controls would send, checked against the module's safety limits. Requires write.

{ "type": "invoke_command", "moduleId": "qwiic-relay", "command": "on" }
{ "type": "invoke_command", "moduleId": "modulino-pixels", "command": "set_color", "params": { "r": 255, "g": 0, "b": 0 } }

Answered with command_result, or with an error (NO_BOARD, or COMMAND_REFUSED with the reason).

camera_snapshot_request / camera_stream_request / camera_ice_candidate

Ask the project's board for a camera snapshot, or negotiate a WebRTC stream. Requires write.

{ "type": "camera_snapshot_request", "cameraId": "cam0" }
{ "type": "camera_stream_request", "cameraId": "cam0", "offer": "<SDP offer>" }
{ "type": "camera_ice_candidate", "cameraId": "cam0", "candidate": "<ICE candidate>" }

ping

{ "type": "ping" }

Answered with { "type": "pong" }.

Removed: trigger_behavior

trigger_behavior was removed: behaviors are retired, and projects run scripts. The server answers it with an error whose code is REMOVED. Set a variable instead and react to it in the script.

Server to client

snapshot

{
  "type": "snapshot",
  "sensors": { "modulino-knob": { "encoder": 42 } },
  "variables": { "score": 10 },
  "status": {
    "connected": true,
    "modules": [
      { "moduleId": "modulino-knob", "name": "Modulino Knob", "address": 58, "deviceId": "7c1e…" }
    ],
    "boards": [{ "deviceId": "7c1e…", "connected": true }]
  },
  "purpose": { "subject": "tomatoes", "source": "inferred", "assumption": "…", "ranges": { "temperature": { "min": 18, "max": 29, "unit": "°C" } }, "updatedAt": "2026-09-17T08:00:00.000Z" }
}

purpose is null when the project has no purpose yet, and is left out when the server has not read the project yet — keep whatever you already show.

sensor_data

{ "type": "sensor_data", "channel": "sensors", "moduleId": "modulino-knob", "value": { "encoder": 42 }, "timestamp": 1709142000000 }

variable_state

{ "type": "variable_state", "channel": "variables", "variables": { "score": 10 } }

behavior_event

An event on the events channel. Today these are camera events.

{ "type": "behavior_event", "channel": "events", "event": "camera:motion", "data": { "cameraId": "cam0", "value": 0.4 }, "timestamp": 1709142000000 }

camera_event

{ "type": "camera_event", "channel": "sensors", "cameraId": "cam0", "event": "snapshot_ready", "path": "…", "timestamp": 1709142000000 }

device_status

The project's boards changed: one connected or disconnected, or its modules changed.

{ "type": "device_status", "channel": "status", "connected": true, "modules": [ … ], "boards": [{ "deviceId": "7c1e…", "connected": true }] }

purpose

{ "type": "purpose", "channel": "status", "purpose": { "subject": "tomatoes", … } }

command_result

{ "type": "command_result", "moduleId": "qwiic-relay", "command": "on", "boards": 1 }

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

notice

Something to know that is not an error. LEGACY_ACCOUNT_KEY: the connection uses an old account key (see Account keys).

{ "type": "notice", "code": "LEGACY_ACCOUNT_KEY", "message": "This is an account key. …" }

error

{ "type": "error", "code": "FORBIDDEN", "message": "Permission denied: write access required" }
CodeMeaning
FORBIDDENThe key cannot write (a Can view key, or a legacy account key)
INVALID_MESSAGENot JSON, or an unknown message type
NO_BOARDThe write reached none of the project's boards (none assigned, or none connected)
COMMAND_REFUSEDinvoke_command was refused: unknown module or command, or a safety limit
REMOVEDA message type that no longer exists (trigger_behavior)
KEY_REVOKEDThe key was revoked. Sent just before the server closes the connection
KEY_EXPIREDThe key expired. Sent just before the server closes the connection
NOT_FOUND, INTERNALReserved

Close codes

CodeReasonWhat to do
4401API key revokedStop reconnecting; create a new key in the app
4401API key expiredStop reconnecting; create a new key in the app

A connection whose handshake is refused gets an HTTP 401 (no token) or 403 (the key does not open this project) instead of a WebSocket.

Sending a command to a script

There is no separate command channel: a script listens for a variable. The script on the board:

// Runs on the board. Fires whenever the variable changes — from the app, PAL, another script,
// or a Project Context connection's set_variable.
p.onVariableChange('light_on', (on) => {
  p.write('qwiic-relay', on ? 'on' : 'off')
})

Your integration:

ws.send(JSON.stringify({ type: 'set_variable', name: 'light_on', value: true }))

For a one-off command rather than a state, use a counter or a timestamp so the same command can be sent twice: { "type": "set_variable", "name": "doorbell", "value": Date.now() }.

Authentication

Key format

pk_ + 64 lowercase hex characters      (67 characters in all)

The app shows the first 10 characters (pk_a1b2c3d) so you can tell keys apart. Only a SHA-256 hash of the key is stored; it cannot be shown again or recovered.

Revoking

Revoke a key in the app: ⋯ → Access, then remove the app under Apps. Every open connection using it receives a KEY_REVOKED error and is closed with 4401 within a second or two, and the key is refused on /connect and on the WebSocket from then on.

Expiry

A key can carry an expiry. An expired key is refused on /connect and on the WebSocket, and an open connection is closed with 4401 API key expired on its next frame.

Account keys (legacy)

Keys under Settings → Developer → API keys are account keys: one key for every project you own. Since 17 October 2026 they connect read-only, whatever they were made with, and each connection gets a LEGACY_ACCOUNT_KEY notice. Create a key in each project instead and revoke the account key.

Examples

Live dashboard (Node)

import WebSocket from 'ws'
 
const { PALPABLE_PROJECT_ID: projectId, PALPABLE_API_KEY: apiKey } = process.env
 
const res = await fetch(`https://palpable.technology/api/projects/${projectId}/connect`, {
  headers: { Authorization: `Bearer ${apiKey}` },
})
const { wsUrl } = await res.json()
const ws = new WebSocket(`${wsUrl}?token=${apiKey}`)
 
ws.on('open', () => ws.send(JSON.stringify({ type: 'subscribe', channels: ['sensors', 'variables', 'status'] })))
ws.on('message', (data) => {
  const msg = JSON.parse(data)
  switch (msg.type) {
    case 'snapshot':
      console.log('now:', msg.sensors, msg.variables, msg.status.connected ? 'online' : 'offline')
      break
    case 'sensor_data':
      console.log(`${msg.moduleId}:`, msg.value)
      break
    case 'variable_state':
      console.log('variables:', msg.variables)
      break
    case 'device_status':
      console.log(msg.connected ? 'a board is online' : 'no board online')
      break
    case 'error':
      console.error(msg.code, msg.message)
      break
  }
})
ws.on('close', (code, reason) => {
  if (code === 4401) console.error(`stopped: ${reason}`) // revoked or expired — do not reconnect
})

Logging readings (Python)

import asyncio, json, os, httpx, websockets
 
async def log_sensors():
    project_id = os.environ["PALPABLE_PROJECT_ID"]
    api_key = os.environ["PALPABLE_API_KEY"]
    async with httpx.AsyncClient() as client:
        res = await client.get(
            f"https://palpable.technology/api/projects/{project_id}/connect",
            headers={"Authorization": f"Bearer {api_key}"},
        )
        res.raise_for_status()
        ws_url = res.json()["wsUrl"]
 
    async with websockets.connect(f"{ws_url}?token={api_key}") as ws:
        await ws.send(json.dumps({"type": "subscribe", "channels": ["sensors"]}))
        async for message in ws:
            msg = json.loads(message)
            if msg["type"] == "sensor_data":
                print(f"[{msg['timestamp']}] {msg['moduleId']}: {msg['value']}")
 
asyncio.run(log_sensors())

Display preview

Palpable's display preview page can stream a project's live values:

https://agent.palpable.technology/session/{ownerId}/display/{displayId}/preview?projectId={projectId}&token=pk_…

That URL contains the key. Open it only on your own machine, with a Can view key, and never embed it in a page other people can load.