API Reference
RAFIQ API Layer
Complete interface documentation for all three API surfaces: REST HTTP endpoints, WebSocket real-time event streams, and MQTT IoT message topics. All interfaces operate locally and function without internet connectivity.
API Surfaces · 4 gateways
REST API Gateway
FastAPI · HTTP/1.1 · JSON · Port 8000
Full CRUD REST interface for all RAFIQ resources. Supports JSON request/response, pagination, filtering, and streaming. JWT authenticated. Rate limited to 500 req/min per client.
WebSocket Gateway
WS · Async push · Event bus
Persistent bidirectional connection for real-time events. Multiplexes all system events over a single socket with topic-based subscription filtering. Handles up to 50 concurrent clients.
MQTT Broker
Mosquitto 2.0 · Port 1883 · QoS 0/1/2
Local MQTT broker for all IoT device communication. Handles wearable telemetry, gas sensor data, emergency signals, and home device commands with QoS guarantees and retained messages.
Authentication
JWT · HS256 · 24h TTL
PIN-based patient authentication that issues short-lived JWT access tokens and long-lived refresh tokens. All API calls except /health require a valid Bearer token. Tokens embed patient ID and role.
REST Endpoints · Base URL: http://localhost:8000
REST API Endpoints
All endpoints return JSON. Non-200 responses include { error, code, detail } schema.
| Method | Path | Description | Auth | Response |
|---|---|---|---|---|
| GET | /api/v1/health | Full system health status, service states, uptime | None | 200 HealthStatus |
| GET | /api/v1/patient/{id} | Patient profile, demographics, linked devices | Bearer | 200 Patient |
| GET | /api/v1/wearable/latest | Most recent wearable reading for active patient | Bearer | 200 WearableReading |
| POST | /api/v1/wearable | Push raw wearable sensor data into the pipeline | Bearer | 201 Created |
| GET | /api/v1/alerts?limit=20 | Paginated recent alert events, sorted by severity | Bearer | 200 Alert[] |
| POST | /api/v1/alerts/{id}/acknowledge | Mark an alert as acknowledged with optional note | Bearer | 200 Alert |
| GET | /api/v1/ai/status | AI engine status, loaded models, queue depth | Bearer | 200 AIStatus |
| POST | /api/v1/ai/query | Submit a health query to the AI reasoning engine | Bearer | 200 AIResponse |
| GET | /api/v1/sync/status | Sync engine state, queue depth, last sync timestamp | Bearer | 200 SyncStatus |
| POST | /api/v1/emergency/trigger | Manually trigger emergency protocol (requires PIN) | Bearer | 202 Accepted |
| GET | /api/v1/home/devices | All registered Home Assistant devices with state | Bearer | 200 Device[] |
| POST | /api/v1/home/command | Send a command to a specific home device | Bearer | 200 CommandResult |
cURL Example
# Authenticate and query AI engine
TOKEN=$(curl -s -X POST http://localhost:8000/api/v1/auth/token \
-H "Content-Type: application/json" \
-d '{"patient_id": "pt-001", "pin": "1234"}' | jq -r .access_token)
# POST to AI query endpoint
curl -s -X POST http://localhost:8000/api/v1/ai/query \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{
"query": "Patient HR 118 bpm, SpO2 93%, temp 38.5°C. Assess urgency.",
"context": "elderly_patient",
"stream": false
}' | jq .
# Get latest wearable reading
curl -s http://localhost:8000/api/v1/wearable/latest \
-H "Authorization: Bearer $TOKEN" | jq .Authentication Header
# JWT Bearer Token — included in all protected API requests
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
# Token payload structure
{
"sub": "pt-001", # Patient ID
"role": "patient", # Role: patient | caregiver | admin
"iat": 1716000000, # Issued at (Unix timestamp)
"exp": 1716086400, # Expires at (+24h)
"device_ids": ["wb-a1b2"] # Authorized wearable devices
}
# Token refresh — POST /api/v1/auth/refresh
curl -X POST http://localhost:8000/api/v1/auth/refresh \
-H "Authorization: Bearer <refresh_token>"| Event Type | Direction | Payload Schema | Description |
|---|---|---|---|
| wearable_update | Server→Client | { device_id, hr, spo2, temp, timestamp } | Real-time vitals from wearable device, emitted every 2s |
| ai_decision | Server→Client | { decision_id, type, severity, reasoning, actions[] } | AI engine decision output after health analysis |
| emergency_alert | Server→Client | { alert_id, type, level, location, triggered_at } | Critical safety event requiring immediate attention |
| sync_status | Server→Client | { state, queue_depth, last_sync, pending_records } | Sync engine heartbeat and queue state update |
| device_state | Server→Client | { device_id, entity_id, state, attributes, changed_at } | Home Assistant device state change broadcast |
| ping | Client→Server | { ts: number } | Client keepalive — server responds with pong |
| subscribe | Client→Server | { topics: string[] } | Subscribe to specific event streams by topic key |
WebSocket Client · Python
import asyncio
import json
import websockets
async def monitor_rafiq():
uri = "ws://localhost:8000/ws/monitor"
async with websockets.connect(uri) as ws:
# Subscribe to specific event streams
await ws.send(json.dumps({
"event": "subscribe",
"topics": ["wearable_update", "ai_decision", "emergency_alert"]
}))
print("Connected to RAFIQ WebSocket monitor")
async for message in ws:
data = json.loads(message)
event_type = data.get("event")
if event_type == "wearable_update":
print(f"[VITALS] HR={data['payload']['hr']} SpO2={data['payload']['spo2']}")
elif event_type == "ai_decision":
severity = data['payload']['severity']
print(f"[AI] Severity={severity}: {data['payload']['reasoning'][:80]}")
elif event_type == "emergency_alert":
print(f"[EMERGENCY] {data['payload']['type']} — {data['payload']['level']}")
# Send periodic keepalive
await ws.send(json.dumps({"event": "ping", "ts": asyncio.get_event_loop().time()}))
asyncio.run(monitor_rafiq())MQTT Topics · Broker: localhost:1883
MQTT Topic Map
All topics use UTF-8 JSON payloads. Wildcards: + (single level), # (multi-level)
| Topic Pattern | QoS | Retain | Publisher | Payload Schema |
|---|---|---|---|---|
| rafiq/wearable/{device_id}/heartrate | QoS 1 | No | Wearable | { bpm: int, quality: float, timestamp: str } |
| rafiq/wearable/{device_id}/spo2 | QoS 1 | No | Wearable | { spo2: float, pi: float, timestamp: str } |
| rafiq/sensor/gas/{sensor_id} | QoS 2 | No | ESP32 MCU | { ppm: float, gas_type: str, alarm: bool } |
| rafiq/emergency/alert | QoS 2 | Yes | Core Engine | { type: str, level: str, triggered_at: str } |
| rafiq/home/{room}/{device}/command | QoS 1 | No | Core Engine | { action: str, params: {}, request_id: str } |
| rafiq/ai/response | QoS 1 | No | AI Orchestrator | { query_id: str, decision: str, confidence: float } |
| rafiq/sync/status | QoS 0 | Yes | Sync Engine | { state: str, queue_depth: int, last_sync: str } |
MQTT Subscriber · paho-mqtt Python
import paho.mqtt.client as mqtt
import json
BROKER_HOST = "localhost"
BROKER_PORT = 1883
def on_connect(client, userdata, flags, rc):
print(f"Connected to MQTT broker (rc={rc})")
# Subscribe to all wearable data and emergency alerts
client.subscribe("rafiq/wearable/#", qos=1)
client.subscribe("rafiq/emergency/alert", qos=2)
client.subscribe("rafiq/ai/response", qos=1)
client.subscribe("rafiq/sync/status", qos=0)
def on_message(client, userdata, msg):
topic = msg.topic
try:
payload = json.loads(msg.payload.decode())
except json.JSONDecodeError:
payload = msg.payload.decode()
if "heartrate" in topic:
print(f"[HR] {topic.split('/')[2]}: {payload['bpm']} bpm")
elif "spo2" in topic:
print(f"[SpO2] {topic.split('/')[2]}: {payload['spo2']}%")
elif topic == "rafiq/emergency/alert":
print(f"[ALERT] {payload['type']} — Level: {payload['level']}")
elif topic == "rafiq/ai/response":
print(f"[AI] Query {payload['query_id']}: {payload['decision']}")
client = mqtt.Client(client_id="rafiq-monitor", protocol=mqtt.MQTTv5)
client.on_connect = on_connect
client.on_message = on_message
client.connect(BROKER_HOST, BROKER_PORT, keepalive=60)
client.loop_forever()Error Response Schema
# Standard error envelope
{
"error": "UNAUTHORIZED",
"code": 401,
"detail": "Token expired or invalid signature",
"request_id": "req_xK9mN2pL",
"timestamp": "2025-05-21T10:23:01Z"
}
# Validation error (422)
{
"error": "VALIDATION_ERROR",
"code": 422,
"detail": [
{ "field": "hr", "msg": "must be between 20 and 250" }
]
}# HTTP Status Code Reference
200 OK — Successful GET / POST response
201 Created — Resource created (POST /wearable)
202 Accepted — Async operation started (emergency trigger)
400 Bad Request — Invalid request body / params
401 Unauthorized — Missing or expired JWT token
403 Forbidden — Token lacks required role/scope
404 Not Found — Resource does not exist
422 Unprocessable — Schema validation failure
429 Rate Limited — Exceeded 500 req/min limit
500 Server Error — Internal error (check logs)
503 Unavailable — Service temporarily degraded