Skip to main content
Integration

REST API driver integration

Per-project drivers poll or receive webhooks from vendor REST APIs and ingest into Open IoT Hub as IoT telemetry or People Counting footfall. This reference covers configuration, authentication, limitations, and management HTTP APIs.

Looking for session cookies, /api/v1 device APIs, and error envelopes? See the IoT Hub REST API overview.

Per-project REST API drivers poll or receive webhooks from vendor HTTP APIs and ingest data into CONTEXUS Open IoT Hub using one of two paths:

Ingest kind Destination Typical use
iot_scalar iot_device_data + discovered devices Sensors, meters, environmental points
pcount_traffic pcount_traffic_intervals → People Counting Footfall UI Mall / retail footfall APIs

This document is the operator and integrator reference for configuring drivers, authentication, poll windows, and HTTP management APIs. It is not the generic IoT Hub session API (/api/v1); see platform REST API docs for admin automation.

Known limitations (read before production)

  • Footfall + webhook: Webhooks only run the IoT scalar path today. pcount_traffic drivers must use polling, not mode: webhook.
  • Unsigned webhooks: If webhookSecret is unset, POST /api/restapi/webhook/:driverId accepts payloads with only a rate limit (60/min). Set a secret in production.
  • Shop → area mapping: Demo mapping in TRAFFIC_SITE_AREA_BY_SHOP covers only shops 115 and 89. Rows without areaId and unknown shopId are dropped (rowsUpserted may be 0 despite HTTP 200).
  • Polling interval PATCH: Changing pollingInterval while enabled does not reschedule the timer until disable/re-enable or app restart.
  • POST/body: Schema columns httpMethod, body, and custom headers exist; the poll executor currently always GET with auth-derived headers only.

1. Overview

  • Two ingest kinds: iot_scalar (telemetry) and pcount_traffic (footfall intervals).
  • Modes: polling (scheduled + manual) and webhook (push, IoT path only).
  • Boot behavior: On startup, the server calls resumeEnabledPolling so drivers with enabled: true and mode: polling resume their timers without manual action.

Code anchors (Open IoT Hub deployment): server/modules/restapi/restApiService.ts, shared/restIngestConfig.ts, shared/schemas/restapi.ts.


2. Architecture

[RestApiSourcesTab / API] --> restapi_drivers (PostgreSQL)
                                      |
                    +-----------------+------------------+
                    v                 v                  v
            RestApiService      processWebhook      fetchPublic (SSRF guard)
               .pollNow              |
                    |                 |
         +----------+----------+      +--> extractGroupedRestDevices --> iot_scalar
         v                     v           (webhook + poll IoT path)
   iot_scalar            pcount_traffic
         |                     |
         v                     v
  iot_device_data       pcount_traffic_intervals
  + discovered devices         |
                               v
                    Footfall UI (GET /api/pcount/traffic/summary)

Primary database tables

Table Role
restapi_drivers Driver config: URL, auth, ingest_kind, ingest_config, poll mode, errors
restapi_discovered_devices Staging devices from JSON before operator confirm
restapi_devices Confirmed REST devices linked to mappings
pcount_traffic / pcount_traffic_intervals Footfall fact and interval aggregates

Do not conflate: People Counting Footfall uses this REST ingest path. Space occupancy in IoT may use a separate sampler—document and test the path your deployment uses.


3. Permissions

Project-scoped operations require an authenticated session with appropriate capability flags:

Capability Used for
restapi-drivers CRUD drivers, test, poll
restapi-devices List/confirm discovered devices
pcount (edit) POST /api/pcount/traffic/ingest historical backfill

Many routes accept ?projectId= to scope to a tenant project.


4. Driver configuration

Core fields (restapi_drivers)

Field Description
url Vendor endpoint template (may include placeholders)
json_path JSONPath (or equivalent) to the array/object of readings
ingest_kind iot_scalar or pcount_traffic
ingest_config JSON validated by restDriverIngestConfigSchema
mode polling or webhook
pollingInterval Seconds between polls (polling mode)
enabled Whether polling is active
webhookSecret HMAC secret for inbound webhooks

URL placeholders

Expanded at poll time via expandRestApiUrl / buildPollRequestUrl:

Token Meaning
{{fromDate}}, {{toDate}} ISO window from pollWindow
{{fromYmd}}, {{toYmd}} Date-only variants
{{today}} Current date in project timezone
Custom e.g. {{shopId}} from variantDefaults or ingest config

pollWindow modes (restPollWindow.ts)

Mode Behavior
realtime Short rolling window for near-live data
historical Backfill-style range
single_day One calendar day
custom Explicit from/to in config

pollVariants + variantDefaults

Fan out multiple HTTP requests per poll cycle (e.g. zone types, sensor types). Each variant can supply context keys used in URL templates and footfall mapping (variantContext.countZoneType).


5. Authentication

Configured per driver in auth JSON; resolved in shared/restApiAuth.ts:

Type Notes
customer_login Session/token from vendor login URL; cached per process
oauth2 Client credentials or password grant; token cache
api_key Header or query placement per config
bearer Static bearer token
basic HTTP Basic

Credentials are stored encrypted or masked in API responses—never log raw secrets. Outbound requests use fetchPublic with SSRF protections.


6. Ingest kind: iot_scalar

  1. Poll or webhook returns JSON; parser extracts rows at json_path.
  2. Discovery: New external IDs appear in restapi_discovered_devices.
  3. Confirm: Operator confirms devices and sets fieldMappings to semantic/canonical keys.
  4. Writes: Values land in iot_device_data.

Device ID format: restapi:{driverId}:{externalId}

Connection metadata: connectionId may truncate driver.id to 36 characters when writing IoT rows.

Webhooks use processWebhook → extractGroupedRestDevices → processDevice (same ingest path as poll for IoT).


7. Ingest kind: pcount_traffic

  • JSON rows are coerced and mapped via mapFootfallRowFromJson (shared/pcountTrafficRest.ts).
  • Default field map assumes A1-shaped vendor JSON; override with footfallFields in ingest_config.
  • Area resolution: Prefer payload areaId; else footfallAreaId / areaNameFallback; else shop → area via TRAFFIC_SITE_AREA_BY_SHOP and resolveTrafficSpaceCode (shared/trafficMapping.ts).
  • Poll only: processWebhook does not write footfall. Use mode: polling for footfall drivers.
  • Downstream: People Counting Footfall tab reads GET /api/pcount/traffic/summary.

Historical backfill: Use POST /api/pcount/traffic/ingest with { driverId, mode: "historical" } rather than assuming POST /api/restapi/drivers/:id/poll honors a historical mode in the body (manual poll uses the driver’s configured pollWindow).


8. HTTP API reference

Base path on the hub host (e.g. https://openiot.contexus.io). Append ?projectId=<uuid> where required.

Drivers

Method Path Description
GET /api/restapi/drivers List drivers
POST /api/restapi/drivers Create driver
PATCH /api/restapi/drivers/:id Update (see limitation on pollingInterval)
DELETE /api/restapi/drivers/:id Remove driver
POST /api/restapi/drivers/:id/test Test connection (may omit full poll URL token expansion)
POST /api/restapi/drivers/:id/poll Trigger immediate poll

Discovered devices

Method Path Description
GET /api/restapi/discovered-devices List pending
POST /api/restapi/discovered-devices Refresh discovery
POST /api/restapi/discovered-devices/confirm Confirm + mappings

Webhook (IoT ingest)

POST /api/restapi/webhook/:driverId
  • Header: x-webhook-signature or Authorization — raw hex HMAC of body with webhookSecret (no sha256= prefix).
  • Rate limit: 60 requests/minute per driver when configured.

Footfall ingest

POST /api/pcount/traffic/ingest
Content-Type: application/json

{ "driverId": "<uuid>", "mode": "historical" }

Requires pcount edit permission.


9. Operations

Task How
Manual poll UI Poll now or POST .../drivers/:id/poll
Historical footfall POST /api/pcount/traffic/ingest
Connection test POST .../drivers/:id/test — note URL may differ from production poll URLs with date tokens
After driver delete Run cursor_scripts/relink_restapi_devices.mjs if orphan device links
Demo seed cursor_scripts/seed_0032_demo_mall_rest_drivers.mjs (project 0032)
SSRF All outbound vendor calls via fetchPublic guard
Monitoring lastError, lastFetchAt, driver raw events in admin UI

Multi-instance deployments: in-memory pollInFlight and token caches are per process—duplicate polls possible across replicas.


10. New vendor checklist

  1. Choose ingest kind: IoT telemetry vs footfall (never footfall + webhook).
  2. Document vendor JSON shape; set json_path and field maps / footfallFields.
  3. Shop/area strategy: Provide areaId in payload, configure spaces + footfallAreaId, or extend shop→area mapping—verify rows are not dropped.
  4. Configure auth type and test with Test connection, then Poll now.
  5. Confirm rowsUpserted / interval counts in DB or Footfall UI, not only HTTP 200.
  6. Set webhookSecret if using webhooks for IoT.
  7. Run unit tests where available: tests/unit/restApiUrl.test.ts, restPollWindow.test.ts, pcountTrafficRest.test.ts.

11. Appendix: demo mall (project 0032)

Operational runbook for seeded mall REST footfall drivers (when present in your tree):

  • cursor_scripts/REST_FOOTFALL_DEMO_DRIVERS.md — step-by-step demo driver setup
  • cursor_scripts/seed_0032_demo_mall_rest_drivers.mjs — seed script

E2E parity reference: tests/e2e/demoMallRestParity.test.ts (URL expansion).


Related documentation

  • IoT Hub session / v1 API overview: /docs/api on the marketing site
  • Protocol drivers (BACnet, MQTT, etc.): /docs/protocols/*