Online
API Layerv2.1.0
REST Endpoints24+
WS Events7 types
MQTT Topics15 active

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.

Endpoints
24+
Auth
JWT Bearer
Timeout
30s
OpenAPI 3.1FastAPIPydantic v2asyncio

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.

Events/s
~15
Clients
50 max
Protocol
WS/13
WebSocketsasynciobroadcasttopic filter

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.

Topics
15+ active
QoS
0 / 1 / 2
LWT
enabled
MosquittoTLSRetainedLast-Will-Testament

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.

Algorithm
HS256
TTL
24h
Refresh
7d
JWTHMAC-SHA256RBACPIN auth

REST Endpoints · Base URL: http://localhost:8000

REST API Endpoints

All endpoints return JSON. Non-200 responses include { error, code, detail } schema.

MethodPathDescriptionAuthResponse
GET/api/v1/healthFull system health status, service states, uptimeNone200 HealthStatus
GET/api/v1/patient/{id}Patient profile, demographics, linked devicesBearer200 Patient
GET/api/v1/wearable/latestMost recent wearable reading for active patientBearer200 WearableReading
POST/api/v1/wearablePush raw wearable sensor data into the pipelineBearer201 Created
GET/api/v1/alerts?limit=20Paginated recent alert events, sorted by severityBearer200 Alert[]
POST/api/v1/alerts/{id}/acknowledgeMark an alert as acknowledged with optional noteBearer200 Alert
GET/api/v1/ai/statusAI engine status, loaded models, queue depthBearer200 AIStatus
POST/api/v1/ai/querySubmit a health query to the AI reasoning engineBearer200 AIResponse
GET/api/v1/sync/statusSync engine state, queue depth, last sync timestampBearer200 SyncStatus
POST/api/v1/emergency/triggerManually trigger emergency protocol (requires PIN)Bearer202 Accepted
GET/api/v1/home/devicesAll registered Home Assistant devices with stateBearer200 Device[]
POST/api/v1/home/commandSend a command to a specific home deviceBearer200 CommandResult

cURL Example

terminal
bash
# 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

auth.http
http
# 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>"
WebSocket Gatewayws://localhost:8000/ws/monitor — persistent bidirectional event stream
Connection live · 7 event types
Event TypeDirectionPayload SchemaDescription
wearable_updateServer→Client{ device_id, hr, spo2, temp, timestamp }Real-time vitals from wearable device, emitted every 2s
ai_decisionServer→Client{ decision_id, type, severity, reasoning, actions[] }AI engine decision output after health analysis
emergency_alertServer→Client{ alert_id, type, level, location, triggered_at }Critical safety event requiring immediate attention
sync_statusServer→Client{ state, queue_depth, last_sync, pending_records }Sync engine heartbeat and queue state update
device_stateServer→Client{ device_id, entity_id, state, attributes, changed_at }Home Assistant device state change broadcast
pingClient→Server{ ts: number }Client keepalive — server responds with pong
subscribeClient→Server{ topics: string[] }Subscribe to specific event streams by topic key

WebSocket Client · Python

ws_monitor.py
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 PatternQoSRetainPublisherPayload Schema
rafiq/wearable/{device_id}/heartrateQoS 1NoWearable{ bpm: int, quality: float, timestamp: str }
rafiq/wearable/{device_id}/spo2QoS 1NoWearable{ spo2: float, pi: float, timestamp: str }
rafiq/sensor/gas/{sensor_id}QoS 2NoESP32 MCU{ ppm: float, gas_type: str, alarm: bool }
rafiq/emergency/alertQoS 2YesCore Engine{ type: str, level: str, triggered_at: str }
rafiq/home/{room}/{device}/commandQoS 1NoCore Engine{ action: str, params: {}, request_id: str }
rafiq/ai/responseQoS 1NoAI Orchestrator{ query_id: str, decision: str, confidence: float }
rafiq/sync/statusQoS 0YesSync Engine{ state: str, queue_depth: int, last_sync: str }

MQTT Subscriber · paho-mqtt Python

mqtt_subscriber.py
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()
Rate Limits & ConstraintsApplied per client IP / token
REST Rate Limit500 req/minPer token
WS Max Clients50 concurrentLocal network
MQTT Max Payload256 KBPer message
AI Query Timeout30sHard cutoff
Auth Token TTL24hAccess token
Refresh Token TTL7 daysRefresh token
Max Body Size10 MBREST POST/PUT
WS Ping Interval30sKeepalive

Error Response Schema

error_response.json
json
# 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_codes.txt
bash
# 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