Docs

Chapter 06

App API (REST)

How the mobile app, the operator console and your own systems talk to the Nook backend: sign-in, the routes to list and open compartments, assignments, webhooks, and the error codes every client must handle.

Draft specification, version 1. This is the contract between the mobile app, the operator console and the Nook backend. It is written to be implemented: nothing here exists in production yet. The backend translates these calls into the signed MQTT commands described in the Cabinet API.

Overview

Request path
App or console  ──HTTPS──▶  Nook backend  ──MQTT/TLS──▶  Cabinet
                ◀── JSON ──                ◀── events ──

Conventions

TopicRule
Base URLhttps://api.nooklocker.es/v1. HTTPS only, TLS 1.2 or newer.
FormatJSON in and out, UTF-8, Content-Type: application/json. Field names in camelCase.
DatesISO 8601 in UTC, for example 2026-11-24T18:42:07Z.
IdentifiersOpaque strings with a prefix: mem_… member, cab_… cabinet, asg_… assignment, unl_… unlock, evt_… event. Compartments are numbered from 1.
IdempotencyEvery POST that changes something accepts an Idempotency-Key header (a UUID). The same key within 24 h returns the first response instead of acting twice.
PaginationCursor based: ?limit=50&cursor=…. Responses carry nextCursor, null on the last page. limit is 1 to 100, 50 by default.
VersioningBreaking changes get a new prefix (/v2). Adding fields is not a breaking change: clients must ignore unknown fields.
Request idEvery response carries X-Request-Id. Quote it when you contact support.

Authentication

Members and operators sign in with a one-time code sent by email or SMS. No password is stored. The backend returns a short access token and a long refresh token.

CallerCredentialHeader
Member, operatorAccess token (JWT, 15 min) and refresh token (opaque, 30 days, rotated on every use)Authorization: Bearer <accessToken>
IntegrationAPI key created in the console, scoped to one organisation, revocableAuthorization: Bearer nk_live_…

POST /auth/code: send a sign-in code

HTTP
POST /v1/auth/code
Content-Type: application/json

{ "email": "lea@example.com" }
202 Accepted
{ "challengeId": "chl_8f3a1c", "channel": "email", "expiresAt": "2026-11-24T18:52:07Z" }

Use phone instead of email for SMS. The answer is the same whether or not the address is known, so the endpoint cannot be used to find members. Limited to 5 requests per address per hour.

POST /auth/verify: exchange the code for tokens

Request
{ "challengeId": "chl_8f3a1c", "code": "482915" }
200 OK
{
  "accessToken": "eyJhbGciOiJFZERTQSIs…",
  "accessTokenExpiresAt": "2026-11-24T19:07:30Z",
  "refreshToken": "rt_2b9f…",
  "member": { "id": "mem_42", "name": "Léa Martin", "role": "member" }
}

A code is 6 digits, valid 10 minutes, and blocked after 5 wrong tries.

POST /auth/refresh and POST /auth/logout

POST /auth/refresh
{ "refreshToken": "rt_2b9f…" }

/auth/refresh returns a new pair of tokens and invalidates the old refresh token. If an old refresh token is used again, the whole session is revoked: it was probably stolen. /auth/logout revokes the refresh token and answers 204.

Member endpoints (mobile app)

GET /me

200 OK
{
  "id": "mem_42", "name": "Léa Martin", "email": "lea@example.com",
  "role": "member", "organisation": { "id": "org_7", "name": "Hôtel des Arts" }
}

GET /lockers: the compartments assigned to me

200 OK
{
  "data": [
    {
      "assignmentId": "asg_311",
      "cabinet": { "id": "cab_001", "name": "Lobby", "model": "nook-locker-100", "online": true },
      "locker": 17,
      "door": "closed",
      "validFrom": "2026-11-24T15:00:00Z",
      "validUntil": "2026-11-27T11:00:00Z",
      "canOpen": true
    }
  ],
  "nextCursor": null
}

door is open, closed or unknown (cabinet offline or lock board not answering). canOpen is false outside the validity window.

POST /lockers/{assignmentId}/open: open my compartment

The app opens an assignment, not a raw compartment number, so it can never ask for a compartment it was not given.

HTTP
POST /v1/lockers/asg_311/open
Authorization: Bearer eyJhbGciOiJFZERTQSIs…
Idempotency-Key: 4b7d6a1e-9c3f-4f0e-8d55-2a71c0e9b310

The backend signs the command, publishes it and waits up to 8 seconds for the cabinet's event/unlock.

200 OK: the cabinet answered
{
  "id": "unl_9a0c",
  "status": "opened",
  "locker": 17,
  "cabinetId": "cab_001",
  "doorOpen": true,
  "requestedAt": "2026-11-24T18:42:07Z",
  "completedAt": "2026-11-24T18:42:08Z"
}

status is one of:

Refusals and cabinet problems come back as errors, see Errors.

GET /unlocks/{id}

Returns the same object as above. Final statuses are opened, released and failed (with an error object); pending means the cabinet has not answered yet.

POST /lockers/{assignmentId}/offline-tokens: Bluetooth tokens for offline use

Request
{ "count": 3 }
201 Created
{
  "data": [
    { "token": "v1.eyJjYWIiOiJjYWItMDAx…", "nonce": "9f2c4e7a", "validFrom": "2026-11-24T15:00:00Z", "validUntil": "2026-11-27T11:00:00Z" }
  ],
  "ble": { "name": "Nook-cab-001", "service": "6e6f6f6b-0001-4c6f-636b-657200000000" }
}

The app stores the tokens in the device's secure storage (Keychain, Keystore) and uses one only when the online open fails with cabinet_offline. A token never outlives the assignment, and at most 7 days. count is 1 to 5; the app tops up as tokens are used.

GET /activity: my history

200 OK
{
  "data": [
    { "id": "evt_5512", "type": "unlock.succeeded", "cabinetId": "cab_001", "locker": 17, "source": "app", "at": "2026-11-24T18:42:08Z" },
    { "id": "evt_5513", "type": "door.closed", "cabinetId": "cab_001", "locker": 17, "at": "2026-11-24T18:42:31Z" }
  ],
  "nextCursor": "c_evt_5511"
}

Operator endpoints (console and integrations)

Reserved to the operator role and to API keys. Every call is limited to the caller's organisation.

Method and pathPurpose
GET /cabinetsList cabinets with online, power state and free compartments
GET /cabinets/{id}Full status: last heartbeat, boards, battery, open doors, pending events
GET /cabinets/{id}/doorsState of every door, from the last doors message
POST /cabinets/{id}/syncAsk the cabinet for a fresh state (sends cmd/sync). 202.
POST /cabinets/{id}/lockers/{n}/openOpen any compartment, for staff. Requires a reason in the body; it is logged.
GET /members, POST /membersList or invite members (name and email or phone). The invite sends a sign-in link.
DELETE /members/{id}Remove a member. Their assignments end at once and their offline tokens stop being issued.
GET /assignments, POST /assignmentsList or create an assignment: who gets which compartment, and when
PATCH /assignments/{id}Change the dates or move to another compartment
DELETE /assignments/{id}End an assignment now
GET /eventsAudit log, filterable by cabinetId, locker, memberId, type, from, to
GET /webhooks, POST /webhooks, DELETE /webhooks/{id}Manage webhook endpoints

POST /assignments

Request
{
  "memberId": "mem_42",
  "cabinetId": "cab_001",
  "locker": 17,
  "validFrom": "2026-11-24T15:00:00Z",
  "validUntil": "2026-11-27T11:00:00Z",
  "notify": true
}
201 Created
{ "id": "asg_311", "memberId": "mem_42", "cabinetId": "cab_001", "locker": 17,
  "validFrom": "2026-11-24T15:00:00Z", "validUntil": "2026-11-27T11:00:00Z", "status": "scheduled" }

Omit locker to let the backend pick a free compartment. validUntil can be null for an open-ended assignment. A compartment cannot have two overlapping assignments: that returns 409 locker_taken. With notify, the member receives a push notification or an email.

Webhooks

Integrations can receive events instead of polling. The backend sends a POST with a JSON body to each registered URL and expects a 2xx within 5 seconds. Failed deliveries are retried with backoff for 24 hours.

Event typeWhen
unlock.succeeded, unlock.failedAfter every unlock attempt, online or Bluetooth
door.opened, door.closedDoor movements
door.forced, door.left_openSecurity alerts
cabinet.offline, cabinet.onlineConnection lost (Last Will) or restored
cabinet.on_battery, cabinet.power_restored, cabinet.low_batteryPower events
cabinet.faultA lock board stopped or started answering
assignment.started, assignment.endedStart and end of an assignment window
Delivery
POST https://your-system.example.com/nook
Content-Type: application/json
Nook-Event-Id: evt_5512
Nook-Signature: t=1764009728,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd

{ "id": "evt_5512", "type": "unlock.succeeded", "at": "2026-11-24T18:42:08Z",
  "data": { "cabinetId": "cab_001", "locker": 17, "memberId": "mem_42", "source": "app", "doorOpen": true } }

Check the signature before trusting the body: v1 = HMAC-SHA256(webhookSecret, "{t}.{raw body}"), and refuse deliveries older than 5 minutes. Use Nook-Event-Id to ignore duplicates.

Verifying a webhook (Node.js)
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verify(rawBody, header, secret) {
  const { t, v1 } = Object.fromEntries(header.split(',').map((kv) => kv.split('=')));
  if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
  return timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
}

Errors

Every error has the same shape. code is stable and meant for programs; message is for people and may change.

Error body
{
  "error": {
    "code": "cabinet_offline",
    "message": "The cabinet is not connected. Use Bluetooth to open your locker.",
    "status": 503,
    "requestId": "req_7c1e9b",
    "details": { "cabinetId": "cab_001", "lastSeenAt": "2026-11-24T18:31:55Z" }
  }
}
HTTPCodeMeaning
400invalid_requestMalformed JSON or a missing field. details.fields lists them.
401unauthenticatedMissing or invalid token
401token_expiredAccess token expired: call /auth/refresh and retry
401invalid_codeWrong or expired sign-in code. details.attemptsLeft says how many tries remain.
403forbiddenThe caller's role does not allow this action
403assignment_not_activeOutside the assignment's validity window. details.validFrom, details.validUntil.
404not_foundUnknown resource, or not in the caller's organisation
409locker_takenThe compartment already has an assignment for that period
409idempotency_conflictSame Idempotency-Key with a different body
422validation_failedWell-formed but invalid values, such as validUntil before validFrom
429rate_limitedToo many requests. Wait for the number of seconds in Retry-After.
502cabinet_refusedThe cabinet refused the command. details.reason carries its reason, for example expired or too many requests.
502lock_board_unreachableThe cabinet answered but the lock board did not (board N did not answer)
503cabinet_offlineNo heartbeat for more than 90 s. The app should offer Bluetooth.
504cabinet_timeoutThe command was sent but no answer came within 20 s. The door may have opened: check GET /unlocks/{id} later.
500internal_errorUnexpected server error. Safe to retry with the same Idempotency-Key.

Rate limits

ScopeLimit
Sign-in codes5 per address per hour, 5 wrong tries per code
Open a compartment10 per member per minute. The cabinet adds its own limit of one unlock per compartment every 2 s.
Other member calls120 per member per minute
Integrations600 per API key per minute

Responses carry RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset.

What the backend does on an open

  1. Authenticate the caller and load the assignment.
  2. Check that the assignment belongs to the caller and is active, and that the cabinet sent a heartbeat in the last 90 s.
  3. Store an unlock row with status pending and a new requestId.
  4. Sign the command with the cabinet's secret (sign_command in nook/security.py), with exp 30 s ahead, and publish it on cabinet/{id}/cmd/open with QoS 1.
  5. Match the incoming event/unlock by requestId, update the row, answer the app and send the webhooks.
  6. Write every step to the audit log, including refusals.