# Quickstart

**Preview 0.45** Available · Preview 0.45. The API can change before 1.0: see [Release phases](/docs/resources/release-phases/).

## Before you start

- A DevLab account with a team (organization <your organization>, team <your team>). Your team's API key is in [Your account](/account): <your key>. In the snippets it appears as `<your-api-key>`.
- Your environment's Engine URL is in the kit of a protocol, in [Your integration](/integration) (a protocol → **Kit** → `.env.example` → the `ENGINE_BASE` line; [where exactly](/docs/access/kit/#where-is-the-engine-url)): the kit gathers that protocol's client configuration, your backend's environment and a ready-to-run starter per mode ([Your kit](/docs/access/kit/)). The snippets call it `$ENGINE`.
- For the cURL path, `curl` and `jq` installed.
- For the SDK, Node.js 20.3 or later (`@neurologyca/capture-server` only runs on the server).
- Keep the API key on your server. Never put it in a page or an app.
- For the SDK, the **registry token** (`NODE_AUTH_TOKEN`): **Neurologyca gives it to you with your invitation**, through the same channel as the key; it is not in DevLab.

> Signed in with a team? Your organization and team appear on this page, and your API key is in [Your account](/account). The catalogue of your organization, with each protocol in the viewer, is in [Your integration](/integration).

What you can enrol people in depends on **your organization's contexts** (see [What is Engine 2](/docs/start/what-is/)). This quickstart uses **Measurement**: one position, one step, indicators without interpretation. Engine recommends a baseline before any protocol; the enrolment answers with `baselineWarning` but does not block, so this quickstart skips it.

What you get: one person measured with the camera or a video, and the indicators Engine returns, in your own page.

> Fastest: in [Your integration](/integration), open a protocol → **Kit** → **Download .zip** with **Include my key**, then `npm install && npm start`. You measure in a few minutes ([Your kit](/docs/access/kit/#the-starters)). The tabs below build the same thing by hand.

## Choose your path

### SDK

#### 1. Configure the registry

In a new folder for the quickstart, create `.npmrc` with:

```ini
@neurologyca:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}
```

Then set the registry token in your shell, before installing:

```bash
export NODE_AUTH_TOKEN="<your-registry-token>"
```

In PowerShell:

```powershell
$env:NODE_AUTH_TOKEN = "<your-registry-token>"
```

#### 2. Install

```bash
npm init -y && npm pkg set type=module
npm install @neurologyca/capture@0.45.0 @neurologyca/capture-server@0.20.1 esbuild
```

#### 3. Your backend

It creates one person, enrols them in Measurement and proxies the browser's calls with your key. The browser never carries a token. Do not deploy it: it has no session, so anyone who opens it would capture with your key through its proxy.

Save `server.mjs`, `index.html` and `page.js` in that folder. `server.mjs` serves `index.html` from there and the bundle from `public/page.js`, which step 5 creates.

```js title="server.mjs"
// Your backend for the quickstart (Node 20.3+). It creates one person, enrols them in Measurement and proxies the
// browser's calls to Engine with your key, which only lives here.
//   ENGINE_BASE=<your Engine URL> ENGINE_API_KEY=<your key> node server.mjs
import http from 'node:http'
import { readFile } from 'node:fs/promises'
import { createEngineAdmin, createTokenSource, createEngineProxy, ownsAll } from '@neurologyca/capture-server'
import { toNodeListener } from '@neurologyca/capture-server/node'

const { ENGINE_BASE, ENGINE_API_KEY, PORT = '3000' } = process.env
if (!ENGINE_BASE || !ENGINE_API_KEY) throw new Error('Set ENGINE_BASE (your environment\'s Engine URL, in your kit) and ENGINE_API_KEY')

// 1. One person and their enrolment. In your app: your signed-in user, and the pair saved in your database.
const admin = createEngineAdmin({ baseUrl: ENGINE_BASE, apiKey: ENGINE_API_KEY })
const measurement = (await admin.listProtocolLibrary()).find((p) => p.name === 'Measurement' && p.status === 'published')
if (!measurement) {
  console.error('Your environment does not offer the Measurement protocol yet. Ask Neurologyca, or use the cURL tab with another protocol.')
  process.exit(1)
}
const { externalId } = await admin.createUser({ name: 'quickstart-user' }) // the package generates an opaque UUID
const { userProtocolId } = await admin.enrol(externalId, measurement.pid)
const next = await admin.getNextPosition(userProtocolId)
if (!next) throw new Error('The enrolment has no position to capture')
const pair = { userProtocolId, protocolMechanicId: next.protocolMechanicId }
console.log(`Person ${externalId} enrolled in Measurement. Each start creates one: delete it when you are done (irreversible), with ENGINE_BASE and ENGINE_API_KEY set as for server.mjs:
  node --input-type=module -e "import { createEngineAdmin } from '@neurologyca/capture-server'; await createEngineAdmin({ baseUrl: process.env.ENGINE_BASE, apiKey: process.env.ENGINE_API_KEY }).deleteUser('${externalId}')"`)

// 2. The proxy: the browser calls /engine/* with no token and the proxy adds yours. ownsAll checks every id a route
// carries: here, only this person's enrolment.
const tokens = createTokenSource({ baseUrl: ENGINE_BASE, apiKey: ENGINE_API_KEY })
const engine = toNodeListener(createEngineProxy({
  baseUrl: ENGINE_BASE,
  tokens,
  mountPath: '/engine',
  authorize: async (_req, route) => ownsAll(route, {
    userProtocol: async (up) => up === pair.userProtocolId,
    user: async (userId) => userId === externalId,
  }),
}))

// 3. The page, its bundle and the pair.
const files = new Map([['/', ['index.html', 'text/html']], ['/page.js', ['public/page.js', 'text/javascript']]])
const server = http.createServer(async (req, res) => {
  const url = req.url ?? '/'
  if (url.startsWith('/engine/')) return engine(req, res) // before any body parser
  if (url === '/pair') {
    res.writeHead(200, { 'content-type': 'application/json' })
    return res.end(JSON.stringify(pair))
  }
  const file = files.get(url)
  if (!file) { res.writeHead(404); return res.end() }
  res.writeHead(200, { 'content-type': file[1] })
  res.end(await readFile(new URL(file[0], import.meta.url)))
})
server.listen(Number(PORT), () => {
  const { port } = /** @type {import('node:net').AddressInfo} */ (server.address())
  console.log(`Open http://localhost:${port}`)
})
```

#### 4. Your page

```html title="index.html"
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Quickstart: Measurement with the SDK</title>
<p><label>Optional, a video of yours with a face: <input id="file" type="file" accept="video/*"></label></p>
<video id="video" muted playsinline width="320"></video>
<p><button id="start">Start</button> <button id="cancel" disabled>Cancel</button></p>
<pre id="out"></pre>
<script type="module" src="/page.js"></script>
</html>
```

```js title="page.js"
// Your page: a short Measurement capture with the SDK, from the camera or from a video file of yours.
// Bundle it for the browser: npx esbuild page.js --bundle --format=esm --outfile=public/page.js
import { createProtocolClient, classifyMediaError } from '@neurologyca/capture'

const out = /** @type {HTMLPreElement} */ (document.querySelector('#out'))
const video = /** @type {HTMLVideoElement} */ (document.querySelector('#video'))
const picker = /** @type {HTMLInputElement} */ (document.querySelector('#file'))
const cancel = /** @type {HTMLButtonElement} */ (document.querySelector('#cancel'))

// One client for the whole page, created when it loads and reused for every capture.
const client = createProtocolClient({
  baseUrl: '/engine', // your backend's proxy: the browser carries no token
  keepPrepared: true, // what prepare() loaded survives a capture: measure again without preparing in between
  taxonomy: { contextId: 'measurement' }, // Measurement: any value; required by the SDK, though Measurement does not send it (0.29.0)
  startup: { includeUserAgent: false }, // the startup report stays in the SDK: no user agent, and nothing is sent anywhere
  // The SDK's own words for each startup stage of a capture (userMessage), ready to show.
  onStartupStage: (e) => { if (e.kind === 'capture' && e.userMessage) out.textContent = e.userMessage },
  onWarning: (w) => console.warn(w.code, w.message),
  onError: (e) => { out.textContent = `${e.code}: ${e.message}` }, // a failure mid-capture (a 409, a lost session): its cause
})
// Prepare once, before the first click, so Start does not wait for the face model. It never calls Engine and asks for no
// permission. With keepPrepared the models stay between captures: no prepare() after one. It does not reject on a failed
// load (the capture then loads it itself). The SDK releases what it kept when the page goes away (pagehide): you do not
// listen for it. Call client.release() only when you drop the client, or between one person and the next.
const prepare = () => { client.prepare().catch((e) => console.warn(e.code, e.message)) }
prepare()

document.querySelector('#start')?.addEventListener('click', async () => {
  out.textContent = 'Capturing…'
  // Cancel: before the capture starts, the signal cuts the start; once it runs, session.abort() ends it.
  const stopper = new AbortController()
  /** @type {Awaited<ReturnType<typeof client.captureProtocol>> | null} */
  let session = null
  cancel.disabled = false
  cancel.onclick = () => { stopper.abort(); void session?.abort().catch(() => { /* already over */ }) }
  try {
    // The pair comes from your backend (it enrolled the person), never from the browser.
    const { userProtocolId, protocolMechanicId } = await (await fetch('/pair')).json()
    const file = picker.files?.[0]
    video.srcObject = null // an earlier camera run left its stream here, and it would hide your video
    if (file) video.src = URL.createObjectURL(file) // a video of yours: give it its src BEFORE capturing
    session = await client.captureProtocol({
      captureId: crypto.randomUUID(), // yours: it joins this capture's warnings and startup report
      userProtocolId,
      protocolMechanicId,
      source: file ? { type: 'video', el: video } : { type: 'webcam' },
      signal: stopper.signal,
      // Your video: play it now (muted, so it plays on its own). The camera: show the SDK's preview in your <video>.
      onStarted: (preview) => { if (!file) video.srcObject = preview.srcObject; video.play().catch((e) => { out.textContent = String(e) }) },
      triggerAnalysis: false, // Measurement: nothing to interpret. SDK 0.29.0 skips it when Engine returns interpreted: false; keep it until yours does
    })
    const [step] = session.plan.steps // Measurement has one step, of 6 s or more
    if (file) video.currentTime = 0 // the SDK loaded its model meanwhile: rewind so no second of your file is lost
    await session.step(step.order).run({ durationMs: 15_000 }) // a shorter video ends it earlier
    const outcome = await session.stop()
    console.log(outcome)
    out.textContent = JSON.stringify(outcome, null, 2)
  } catch (e) {
    // classifyMediaError names the cause: insecure-context (not HTTPS or localhost), denied, no-device, in-use, no-frames…
    const err = /** @type {Error & { code?: string }} */ (e)
    out.textContent = stopper.signal.aborted ? 'Cancelled.' : `${classifyMediaError(e) ?? err.code ?? err.name}: ${err.message}`
    await session?.abort().catch(() => { /* already over */ })
  } finally {
    cancel.onclick = null
    cancel.disabled = true
  }
})
```

`taxonomy: { contextId: 'measurement' }` and `triggerAnalysis: false`: the `contextId` is still required, though Measurement does not send it. Since 0.29.0 the SDK skips the analysis on its own when Engine says `interpreted: false`; production does not return it yet, so keep `triggerAnalysis: false` ([Measurement only](/docs/guides/measurement/)).

The client is created once, when the page loads, and `client.prepare()` runs right away: it loads the face model while the person reads the page, so **Start** does not wait for it. `prepare()` never calls Engine, asks for no permission and does not reject when a download fails (the capture then loads what it needs). With `keepPrepared: true` what was loaded stays for the next capture of the same client, so there is no `prepare()` between captures: each one adopts what the previous one left (on Safari and iOS, only the face). The SDK releases it on its own when the page goes away; call `client.release()` only when you drop the client, or between one person and the next on the same device. `signal` is what Cancel uses: it cuts the start, and once the capture runs, `session.abort()` ends it. `captureId` is yours and joins the capture's warnings and its startup report. `startup: { includeUserAgent: false }` keeps the browser's user agent out of that report, which stays in the SDK: nothing sends it anywhere. `onStartupStage` gives the SDK's own text for each stage (`userMessage`), ready to show. More in [Prepare before Start](/docs/sdk/on-device/#prepare-before-start) and [The startup screen](/docs/sdk/on-device/#the-startup-screen); so that the startup goes unnoticed in your flow, [Load the models](/docs/guides/load-models/).

#### 5. Run it

```bash
npx esbuild page.js --bundle --format=esm --outfile=public/page.js
ENGINE_BASE="<engine base URL>" ENGINE_API_KEY="<your-api-key>" node server.mjs
```

In PowerShell, the second line is:

```powershell
$env:ENGINE_BASE = "<engine base URL>"; $env:ENGINE_API_KEY = "<your-api-key>"; node server.mjs
```

`ENGINE_BASE` is the same value as `$ENGINE`: your environment's Engine URL, which is in your kit ([where](/docs/access/kit/#where-is-the-engine-url)).

Open `http://localhost:3000` in Chrome, Edge or Safari (16.4+): the camera only opens on HTTPS or `localhost`. Press **Start** and allow the camera, or pick a video of yours with a face first. Press **Start** once, and to measure again restart `server.mjs`: the pair is one position, Engine refuses it once it is captured, and each start creates and enrols a new person. With the camera, the page shows the camera's preview (the SDK's, in your `<video>`); with a video, it plays it once the capture starts and rewinds it before the step, so no second of it is lost. To try it on your phone, see [Try it on your phone](/docs/sdk/on-device/#try-it-on-your-phone).

Expected output, in the page and in the console:

```json
{
  "status": "complete",
  "hcis": {
    "valence": "<number>",
    "arousal": "<number>",
    "Confusion": "<number>",
    "Stress_intens": "<number>",
    "…": "65 signals in total; this example shows 4"
  },
  "hcisByStep": {
    "1": {
      "valence": "<number>",
      "arousal": "<number>",
      "Confusion": "<number>",
      "Stress_intens": "<number>",
      "…": "65 signals in total; this example shows 4"
    }
  },
  "frameCount": 450,
  "interpretation": null,
  "structured": null
}
```

The values come from a person's face, so here they go without them; the names are the public indicators you get. The 65 signals are from a test capture with Measurement, which receives every public indicator; another context can receive fewer ([which ones](/docs/concepts/results/#human-context-indicators)). The result arrives seconds after the 15-second step ends: well under a minute from pressing Start.

No camera and no video? [See the example in the playground](/playground).

### cURL

#### 1. Get a token

```bash
export ENGINE="<engine base URL>"
export ENGINE_API_KEY="<your-api-key>"

TOKEN=$(curl -s -X POST "$ENGINE/token" \
  -H "Content-Type: application/json" \
  -d "{\"apiKey\":\"$ENGINE_API_KEY\"}" | jq -r .token)
```

Expected response:

```json
{ "token": "<jwt>", "expiresIn": 3600 }
```

#### 2. Create a user

Engine identifies people by an id you choose (`externalId`). Use an opaque id, never an email or a name. Each run creates a new person: `EXT` includes the time, so running the steps again creates another one. Step 8 deletes it.

```bash
EXT="quickstart-$(date +%s)"
curl -s -X POST "$ENGINE/users" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d "{\"externalId\":\"$EXT\",\"name\":\"quickstart-user\"}"
```

Expected response (shortened):

```json
{
  "externalId": "quickstart-1767225600",
  "name": "quickstart-user",
  "createdBy": "<your-credential-name>",
  "lastAccessAt": null
}
```

#### 3. See what your organization can use, then enrol

The catalogue is **your organization's**: Neurologyca assigns contexts to each organization, and these lists only contain protocols from those contexts. List your contexts and protocols first:

```bash
curl -s "$ENGINE/catalog/contexts" \
  -H "Authorization: Bearer $TOKEN" | jq '.[] | {name, taxonomy}'
curl -s "$ENGINE/catalog/protocols" \
  -H "Authorization: Bearer $TOKEN" | jq '.[] | {pid, name, status}'
```

Your lists will differ. In the test environment every organization sees **Baseline** and **Measurement**, which is universal there, for example:

```json
[
  {
    "pid": "00000000-0000-4000-8000-0147b17fe72c",
    "name": "Measurement",
    "status": "published"
  },
  {
    "pid": "00000000-0000-4000-8000-53ac3da6df87",
    "name": "Baseline",
    "status": "published"
  }
]
```

Filter by `status: published`: the catalogue also carries archived versions with the same name, and an archived one can still be enrolled with a notice, so without the filter you could enrol in the old one.

Each entry carries the `pid` you enrol with. Take the Measurement protocol and enrol the user:

```bash
# Measurement by default. To use another protocol, set PROTOCOL to its pid before running this block.
PROTOCOL=${PROTOCOL:-$(curl -s "$ENGINE/catalog/protocols" \
  -H "Authorization: Bearer $TOKEN" \
  | jq -r '.[] | select(.name=="Measurement" and .status=="published") | .pid')}

if [ -z "$PROTOCOL" ]; then
  echo "Your environment does not offer the Measurement protocol yet. Set PROTOCOL to a pid from the list above (except Baseline) and run this block again." >&2
  false
else
  UP=$(curl -s -X POST "$ENGINE/user-protocols" \
    -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
    -d "{\"user\":\"$EXT\",\"protocol\":\"$PROTOCOL\"}" | jq -r .userProtocolId)
  echo "UP=$UP"
fi
```

Engine answers like this (shortened); the block keeps only `userProtocolId`. The `baselineWarning` is the reminder about the baseline:

```json
{
  "status": "active",
  "protocol": {
    "name": "Measurement"
  },
  "baselineWarning": {
    "missing": true,
    "expired": false,
    "invalid": false,
    "message": "No baseline found for this user."
  }
}
```

If Measurement is not in your list (your environment does not offer it yet), this quickstart still works with **any protocol whose next position has a single step** (you check it in step 4), except Baseline, in which you do not enrol people (see [Baseline](/docs/concepts/baseline/)): send the sample as that step. If the mechanic has several steps, the session stays open until **each** step receives its own batches and its own `Final` (`step: N`); steps that declare `media` expect the `mediaId` you showed.

#### 4. Find the position to capture

```bash
PM=$(curl -s "$ENGINE/user-protocols/$UP" -H "Authorization: Bearer $TOKEN" \
  | jq -r .nextProtocolMechanic.protocolMechanicId)

curl -s "$ENGINE/user-protocols/$UP/mechanics/$PM" \
  -H "Authorization: Bearer $TOKEN" | jq '.mechanic.steps'
```

The sample capture covers **one** step, so check that the position has exactly one:

```json at="mechanic.steps"
[
  {
    "order": 1,
    "type": "measurement_free",
    "minTimeSeconds": 6
  }
]
```

#### 5. Send the capture

In production, Capture produces these frames in the browser. Here you send a sample: download [the sample capture](/docs/samples/sample-capture.json) (about 3 MB) into the folder where you run these commands. It is **synthetic**: a generic face mesh, nobody's face, so its indicators describe no one. It holds ten batches of 30 frames for step 1, numbered 1 to 10, the last one marked `Final`.

```bash
# The last batch is the Final. Engine aggregates the step when the Final arrives,
# so give the previous batch a few seconds to be processed.
LAST=$(jq 'length' sample-capture.json); i=0
jq -c '.[]' sample-capture.json | while read -r packet; do
  i=$((i + 1)); [ "$i" -eq "$LAST" ] && sleep 3
  echo "$packet" | jq --arg up "$UP" --arg pm "$PM" '. + {userProtocolId:$up, protocolMechanicId:$pm}' \
  | curl -s -X POST "$ENGINE/process-kpn-emo" \
      -H "Authorization: Bearer $TOKEN" \
      -H "Content-Type: application/json" \
      --data-binary @-
  echo
done
```

Each batch answers `202`. Send all ten in order, with a short pause before the `Final`: a gap or a missing `Final` leaves the step open.

```json
{
  "code": 202,
  "message": "KPN-EMO enqueued successfully, processing...",
  "status": "accepted",
  "framesReceived": 30,
  "framesWithoutFeaturesMeta": 0,
  "framesWithoutMediaTime": 30,
  "step": 1
}
```

#### 6. Read the results

Results are ready when the session completes (a few seconds with this sample). Until then the response is empty, so poll, for up to three minutes:

```bash
for _ in $(seq 1 60); do
  curl -s "$ENGINE/results/$UP/$PM" -H "Authorization: Bearer $TOKEN" \
    | jq -e '(.rawResults["1"] // {}) | del(.stepType) | length > 0' >/dev/null 2>&1 && break
  sleep 3
done
curl -s "$ENGINE/results/$UP/$PM" -H "Authorization: Bearer $TOKEN" | jq '{aggResults}'
```

Expected response, shortened to four indicators (the real one has many more signals):

```json
{
  "aggResults": {
    "1": {
      "mean": {
        "valence": 6.751,
        "arousal": 69.775,
        "Confusion": 14.618,
        "Stress_intens": 54.195
      }
    }
  }
}
```

`rawResults` holds the same indicators for every frame.

#### 7. Optional: an interpretation

Measurement returns indicators, not an interpretation: asking `POST /analyze` for a Measurement capture returns `409` (`PROTOCOL_NOT_ANALYSED`), because Measurement is never interpreted. An interpretation needs a protocol from a context with a taxonomy: you send its taxonomy with `POST /user-protocols/{userProtocolId}/{protocolMechanicId}/context` before the frames, and either set `triggerAnalysis: true` on the `Final` batch or call `POST /analyze` afterwards. [Integration paths](/docs/start/paths/) and your context's guide cover it.

#### 8. Clean up

Each run leaves a person, their enrolment and their results in your organization. Delete them when you are done: `DELETE /users/{externalId}` removes the person and all their data (captures, sessions, enrolments, baseline and consents). It is irreversible, and the body must repeat the `externalId` in `confirm`.

```bash
curl -s -X DELETE "$ENGINE/users/$EXT" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"confirm\":\"$EXT\"}"
```

Expected response (the counts depend on what you captured):

```json
{
  "deleted": "quickstart-1767225600",
  "counts": {
    "frames": 120,
    "sessions": 1,
    "userProtocols": 1,
    "subjectStates": 1,
    "consents": 1,
    "thresholds": 0,
    "policies": 0
  }
}
```

To measure the same person again, do not create it again: a `POST /users` with the same `externalId` answers `409`. Keep the person and open a new enrolment with `POST /user-protocols` (a position is captured once, so a new measurement needs a new enrolment). A `read_all` credential can only delete the people it created.

### Python

This code runs on your server: the API key never reaches the browser. It needs Python 3.8+ and `requests` (`pip install requests`), chosen over the standard `urllib` because it sends JSON and headers in one call. The seven blocks are one script, `quickstart.py`, run in the folder where you download [the sample capture](/docs/samples/sample-capture.json):

```bash
ENGINE_BASE="<engine base URL>" ENGINE_API_KEY="<your-api-key>" python quickstart.py
```

#### 1. Get a token

```python
import json, os, sys, time
import requests

# Your environment's Engine URL is in your kit (ENGINE_BASE: the cURL tab calls it $ENGINE). The API key stays on your server.
ENGINE = os.environ["ENGINE_BASE"]
API_KEY = os.environ["ENGINE_API_KEY"]

r = requests.post(f"{ENGINE}/token", json={"apiKey": API_KEY})
r.raise_for_status()
token = r.json()["token"]
auth = {"Authorization": f"Bearer {token}"}
```

The response is the same as in the cURL tab: `token` and `expiresIn` (seconds).

#### 2. Create a user

Use an opaque id (`externalId`), never an email or a name. Each run creates a new person: `ext` includes the time, so running the script again creates another one. Step 7 deletes it.

```python
ext = f"quickstart-{int(time.time())}"
r = requests.post(f"{ENGINE}/users", headers=auth, json={"externalId": ext, "name": "quickstart-user"})
r.raise_for_status()
print(r.status_code, r.json())
```

#### 3. See what your organization can use, then enrol

The catalogue is your organization's, as in the cURL tab. If Measurement is not in it, set `PROTOCOL` to the pid of a protocol whose next position has a single step (never Baseline).

```python
# Your organization's catalogue. Measurement by default; to use another protocol, set PROTOCOL to its pid.
protocols = requests.get(f"{ENGINE}/catalog/protocols", headers=auth).json()
for p in protocols:
    print(p["pid"], p["name"], p["status"])
protocol = os.environ.get("PROTOCOL") or next(
    (p["pid"] for p in protocols if p["name"] == "Measurement" and p["status"] == "published"), None
)
if not protocol:
    sys.exit("Your environment does not offer the Measurement protocol yet. Set PROTOCOL to a pid from the list above (except Baseline).")
r = requests.post(f"{ENGINE}/user-protocols", headers=auth, json={"user": ext, "protocol": protocol})
r.raise_for_status()
up = r.json()["userProtocolId"]
```

#### 4. Find the position to capture

The sample covers one step, so the script checks that the position has exactly one.

```python
pm = requests.get(f"{ENGINE}/user-protocols/{up}", headers=auth).json()["nextProtocolMechanic"]["protocolMechanicId"]
steps = requests.get(f"{ENGINE}/user-protocols/{up}/mechanics/{pm}", headers=auth).json()["mechanic"]["steps"]
if len(steps) != 1:
    sys.exit(f"This position has {len(steps)} steps and the sample covers one: use a position with a single step.")
```

#### 5. Send the capture

Ten batches in order, with a short pause before the `Final`: each one answers `202`.

```python
# The sample capture, downloaded next to this script: ten batches of step 1, the last one Final.
with open("sample-capture.json") as f:
    packets = json.load(f)
for i, packet in enumerate(packets):
    if i == len(packets) - 1:
        time.sleep(3)  # Engine aggregates the step when the Final arrives: give the previous batch a few seconds
    r = requests.post(f"{ENGINE}/process-kpn-emo", headers=auth, json={**packet, "userProtocolId": up, "protocolMechanicId": pm})
    r.raise_for_status()
    print(r.status_code, r.json()["framesReceived"])
```

#### 6. Read the results

```python
# Ready when the session completes; until then the answer is empty, so poll for up to three minutes.
for _ in range(60):
    results = requests.get(f"{ENGINE}/results/{up}/{pm}", headers=auth).json()
    step1 = (results.get("rawResults") or {}).get("1") or {}
    if any(k != "stepType" for k in step1):
        break
    time.sleep(3)
print(json.dumps({"aggResults": results.get("aggResults")}, indent=2))
```

The answer is the same as in the cURL tab: `aggResults` per step, and `rawResults` with the same indicators for every frame. Measurement is not interpreted: for an interpretation, see step 7 of the cURL tab.

#### 7. Clean up

Delete the person and all their data (irreversible; `confirm` repeats the `externalId`).

```python
# Clean up: delete the person and all their data (irreversible; "confirm" repeats the externalId).
r = requests.delete(f"{ENGINE}/users/{ext}", headers=auth, json={"confirm": ext})
r.raise_for_status()
print(r.status_code, r.json()["counts"])
```

To measure the same person again, do not call `POST /users` a second time with the same `externalId` (it answers `409`): keep the person and open a new enrolment with `POST /user-protocols`.

## What can go wrong

Some mistakes answer with an error; others answer `2xx` and only show up later.

- A camera or video error in the page: `classifyMediaError` names its cause. `insecure-context`: not on HTTPS or `localhost`. `denied`: the camera permission was refused. `no-device` or `in-use`: no camera, or another app holds it. `no-frames` (`CaptureStartError`): the camera opened but gave no usable frame, or your video was paused or had already ended.
- `E_RESULTS_TIMEOUT`: not a loss; read the results later with the same pair (see [Results in your backend](/docs/sdk/results-backend/)).
- A `403` from `/engine/…`: the proxy's `ownsAll` refused an id that is not this person's.

| What you see | Why |
| --- | --- |
| `npm install` answers `401`/`404` for `@neurologyca/…` | `NODE_AUTH_TOKEN` is missing or wrong in this shell ([Install](/docs/start/install/)) |
| The capture stops at the face model (`CaptureStartError`, `stage: 'face-model'`) | Your network blocks cdn.jsdelivr.net or storage.googleapis.com: allow them or self-host the models ([Load the models](/docs/guides/load-models/)) |
| `401` with an empty body (and `WWW-Authenticate: Bearer`) | Missing or expired token. Mint a new one with `POST /token` |
| `401 { "code": 401, "message": "Invalid credentials." }` on `/token` | The API key is wrong, revoked or expired, or your organization is suspended (the same answer in every case) |
| `404 { "code": 404, "message": "Not found." }` | An id that does not exist or is not yours; Engine does not say which |
| `409 POSITION_ALREADY_COMPLETED` | That position already has a completed capture. To measure again, enrol again |
| `202` with `framesWithoutFeaturesMeta` above 0 | Frames without `featuresMeta` give no valence or arousal |
| `202` with `framesWithoutMediaTime` equal to the batch total | Normal if you send no `mediaTimeMs` (where a stimulus player was, optional per frame). Information, not an error |
| `202` for every batch, but results stay empty | A gap in the batch numbers, a missing `Final`, or a mechanic with more steps than you sent |

More in [Declared limits](/docs/concepts/limits/).

## Next

[Integration paths](/docs/start/paths/): Which way to integrate and where it is processed, with the measured numbers.

[On-device (real time)](/docs/sdk/on-device/)

[Measurement only](/docs/guides/measurement/)

[Results in your backend](/docs/sdk/results-backend/)
