IoT Gateway Management API

Complete REST API for managing IoT gateways, devices, alerts, and AI-powered diagnostics. All endpoints return JSON and require Bearer token authentication (except login).

22 Total Endpoints
JWT Auth Method
1000 Req/Hour Limit
Base URL
https://api.iotgateway.io/api/v1
Note: All requests must be made over HTTPS. HTTP requests will be redirected to HTTPS automatically. Include the Authorization: Bearer <token> header on all authenticated endpoints.
Response Format
{
  "success": true,
  "data": { ... },
  "meta": {
    "total": 42,
    "page": 1,
    "per_page": 20,
    "timestamp": "2024-11-15T10:30:00Z"
  }
}
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or expired token",
    "details": null
  },
  "meta": {
    "timestamp": "2024-11-15T10:30:00Z"
  }
}
Authentication
1
Call POST /auth/login with your credentials to receive a JWT access token and refresh token.
2
Include the token as Authorization: Bearer <access_token> in all subsequent requests.
3
Access tokens expire in 15 minutes. Use POST /auth/refresh with the refresh token to get a new access token.
4
Call DELETE /auth/logout to invalidate the session and revoke tokens.
POST /api/v1/auth/login Authenticate user

Authenticate with username and password. Returns a JWT access token (15min TTL) and a refresh token (7 days TTL). No authorization header required.

Request Body
FieldTypeRequiredDescription
usernamestringRequiredUser's login username or email
passwordstringRequiredUser's password (min 8 characters)
remember_mebooleanOptionalExtend refresh token to 30 days
{
  "username": "admin@iotgateway.io",
  "password": "SecurePass@123",
  "remember_me": false
}
{
  "success": true,
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4...",
    "token_type": "Bearer",
    "expires_in": 900,
    "user": {
      "id": "usr_8f4a2b1c",
      "username": "admin@iotgateway.io",
      "role": "admin",
      "last_login": "2024-11-15T09:00:00Z"
    }
  }
}
curl -X POST https://api.iotgateway.io/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "admin@iotgateway.io",
    "password": "SecurePass@123"
  }'
import requests

url = "https://api.iotgateway.io/api/v1/auth/login"
payload = {
    "username": "admin@iotgateway.io",
    "password": "SecurePass@123",
    "remember_me": False
}

response = requests.post(url, json=payload)
data = response.json()
access_token = data["data"]["access_token"]
print(f"Token: {access_token[:20]}...")
const response = await fetch('https://api.iotgateway.io/api/v1/auth/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    username: 'admin@iotgateway.io',
    password: 'SecurePass@123',
    remember_me: false
  })
});
const { data } = await response.json();
localStorage.setItem('access_token', data.access_token);
POST /api/v1/auth/refresh Refresh JWT token

Exchange a valid refresh token for a new access token. The old access token is immediately revoked.

Request Body
FieldTypeRequiredDescription
refresh_tokenstringRequiredThe refresh token from the login response
{ "refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4..." }
{
  "success": true,
  "data": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "token_type": "Bearer",
    "expires_in": 900
  }
}
curl -X POST https://api.iotgateway.io/api/v1/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{"refresh_token": "dGhpcyBpcyBhIHJlZnJlc2ggdG9rZW4..."}'
import requests

response = requests.post(
    "https://api.iotgateway.io/api/v1/auth/refresh",
    json={"refresh_token": stored_refresh_token}
)
new_token = response.json()["data"]["access_token"]
const res = await fetch('/api/v1/auth/refresh', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ refresh_token: localStorage.getItem('refresh_token') })
});
const { data } = await res.json();
localStorage.setItem('access_token', data.access_token);
DELETE /api/v1/auth/logout Invalidate session

Revoke the current access token and associated refresh token. Requires Bearer token in the Authorization header.

No request body required. Pass the Bearer token in the Authorization header.

{ "success": true, "data": { "message": "Logged out successfully" } }
curl -X DELETE https://api.iotgateway.io/api/v1/auth/logout \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
requests.delete("https://api.iotgateway.io/api/v1/auth/logout",
    headers={"Authorization": f"Bearer {access_token}"})
await fetch('/api/v1/auth/logout', {
  method: 'DELETE',
  headers: { 'Authorization': `Bearer ${token}` }
});
Gateways
GET /api/v1/gateways List all gateways

Returns a paginated list of all registered IoT gateways. Supports filtering by status, location, and protocol.

Query Parameters
ParameterTypeRequiredDescription
pageintegerOptionalPage number (default: 1)
per_pageintegerOptionalResults per page (default: 20, max: 100)
statusstringOptionalFilter by status: online, offline, warning
locationstringOptionalFilter by location name (partial match)
protocolstringOptionalFilter by protocol: MQTT, CoAP, HTTP
{
  "success": true,
  "data": [
    {
      "id": "gw_a1b2c3d4",
      "name": "Gateway-Alpha",
      "location": "Floor 1 - Server Room",
      "ip_address": "192.168.1.100",
      "protocol": "MQTT",
      "status": "online",
      "firmware": "v2.4.1",
      "device_count": 24,
      "uptime": 99.8,
      "last_seen": "2024-11-15T10:28:00Z"
    }
  ],
  "meta": { "total": 8, "page": 1, "per_page": 20 }
}
curl -X GET "https://api.iotgateway.io/api/v1/gateways?status=online&page=1" \
  -H "Authorization: Bearer YOUR_TOKEN"
import requests

gateways = requests.get(
    "https://api.iotgateway.io/api/v1/gateways",
    headers={"Authorization": f"Bearer {token}"},
    params={"status": "online", "page": 1, "per_page": 20}
).json()
for gw in gateways["data"]:
    print(f"{gw['name']} - {gw['status']}")
const params = new URLSearchParams({ status: 'online', page: 1 });
const res = await fetch(`/api/v1/gateways?${params}`, {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { data } = await res.json();
console.log(`Found ${data.length} gateways`);
GET /api/v1/gateways/{id} Get gateway by ID

Retrieve detailed information for a specific gateway including real-time metrics, connected devices count, and configuration details.

Path Parameters
ParameterTypeRequiredDescription
idstringRequiredGateway unique identifier (e.g. gw_a1b2c3d4)
{
  "success": true,
  "data": {
    "id": "gw_a1b2c3d4",
    "name": "Gateway-Alpha",
    "location": "Floor 1 - Server Room",
    "ip_address": "192.168.1.100",
    "mac_address": "AA:BB:CC:DD:EE:FF",
    "protocol": "MQTT",
    "status": "online",
    "firmware": "v2.4.1",
    "cpu_usage": 42.3,
    "memory_usage": 68.1,
    "device_count": 24,
    "uptime_seconds": 864000,
    "config": {
      "mqtt_broker": "broker.iotgateway.io:1883",
      "poll_interval": 30,
      "encryption": "TLS1.3"
    },
    "created_at": "2023-06-01T00:00:00Z",
    "last_seen": "2024-11-15T10:28:00Z"
  }
}
curl -X GET https://api.iotgateway.io/api/v1/gateways/gw_a1b2c3d4 \
  -H "Authorization: Bearer YOUR_TOKEN"
gw = requests.get(
    "https://api.iotgateway.io/api/v1/gateways/gw_a1b2c3d4",
    headers={"Authorization": f"Bearer {token}"}
).json()["data"]
print(f"CPU: {gw['cpu_usage']}%")
const res = await fetch('/api/v1/gateways/gw_a1b2c3d4', {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { data } = await res.json();
console.log('Gateway status:', data.status);
PUT /api/v1/gateways/{id}/config Update gateway config

Update the configuration of a specific gateway. Changes are applied within 30 seconds. Only fields provided in the request body will be updated.

Path Parameters
ParameterTypeRequiredDescription
idstringRequiredGateway unique identifier
Request Body
FieldTypeRequiredDescription
mqtt_brokerstringOptionalMQTT broker address (host:port)
poll_intervalintegerOptionalDevice poll interval in seconds (5–3600)
encryptionstringOptionalTLS version: TLS1.2 or TLS1.3
log_levelstringOptionalLog verbosity: debug, info, warn, error
{
  "mqtt_broker": "new-broker.iotgateway.io:1883",
  "poll_interval": 60,
  "encryption": "TLS1.3",
  "log_level": "info"
}
{
  "success": true,
  "data": {
    "id": "gw_a1b2c3d4",
    "config": {
      "mqtt_broker": "new-broker.iotgateway.io:1883",
      "poll_interval": 60,
      "encryption": "TLS1.3",
      "log_level": "info"
    },
    "updated_at": "2024-11-15T10:30:00Z",
    "apply_status": "pending"
  }
}
curl -X PUT https://api.iotgateway.io/api/v1/gateways/gw_a1b2c3d4/config \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"poll_interval": 60, "log_level": "info"}'
response = requests.put(
    "https://api.iotgateway.io/api/v1/gateways/gw_a1b2c3d4/config",
    headers={"Authorization": f"Bearer {token}"},
    json={"poll_interval": 60, "log_level": "info"}
)
print(response.json()["data"]["apply_status"])
const res = await fetch('/api/v1/gateways/gw_a1b2c3d4/config', {
  method: 'PUT',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ poll_interval: 60, log_level: 'info' })
});
POST /api/v1/gateways/{id}/restart Restart gateway

Trigger a remote restart of the specified gateway. The gateway will go offline briefly (typically 30–60 seconds) before coming back online.

Path Parameters
ParameterTypeRequiredDescription
idstringRequiredGateway unique identifier
Optional Request Body
FieldTypeRequiredDescription
reasonstringOptionalReason for restart (logged to audit trail)
delay_secondsintegerOptionalDelay before restart (0–300 seconds, default 0)
{
  "success": true,
  "data": {
    "message": "Restart command sent",
    "gateway_id": "gw_a1b2c3d4",
    "estimated_downtime": 45,
    "job_id": "job_7x9m2k1p"
  }
}
curl -X POST https://api.iotgateway.io/api/v1/gateways/gw_a1b2c3d4/restart \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"reason": "Applying firmware update", "delay_seconds": 10}'
requests.post(
    "https://api.iotgateway.io/api/v1/gateways/gw_a1b2c3d4/restart",
    headers={"Authorization": f"Bearer {token}"},
    json={"reason": "Manual restart", "delay_seconds": 0}
)
await fetch('/api/v1/gateways/gw_a1b2c3d4/restart', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ reason: 'Config update applied' })
});
GET /api/v1/gateways/{id}/devices List devices on gateway

Returns all IoT devices connected to the specified gateway, with their current status and latest sensor readings.

Path Parameters
ParameterTypeRequiredDescription
idstringRequiredGateway unique identifier
{
  "success": true,
  "data": [
    {
      "id": "dev_x1y2z3",
      "name": "TempSensor-01",
      "type": "temperature",
      "status": "online",
      "battery": 87,
      "last_reading": { "value": 23.4, "unit": "°C" },
      "last_seen": "2024-11-15T10:29:00Z"
    }
  ],
  "meta": { "total": 24 }
}
curl https://api.iotgateway.io/api/v1/gateways/gw_a1b2c3d4/devices \
  -H "Authorization: Bearer YOUR_TOKEN"
const res = await fetch('/api/v1/gateways/gw_a1b2c3d4/devices', {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { data } = await res.json();
Devices
GET /api/v1/devices List all IoT devices

Returns a paginated list of all IoT devices across all gateways. Filter by device type, gateway, or status.

Query Parameters
ParameterTypeRequiredDescription
gateway_idstringOptionalFilter devices by gateway ID
typestringOptionaltemperature, humidity, motion, pressure, camera
statusstringOptionalonline, offline, low_battery
pageintegerOptionalPage number
{
  "success": true,
  "data": [
    {
      "id": "dev_x1y2z3",
      "name": "TempSensor-01",
      "type": "temperature",
      "gateway_id": "gw_a1b2c3d4",
      "status": "online",
      "battery": 87,
      "firmware": "v1.2.0",
      "last_reading": { "value": 23.4, "unit": "°C", "timestamp": "2024-11-15T10:29:00Z" }
    }
  ],
  "meta": { "total": 142, "page": 1, "per_page": 20 }
}
curl "https://api.iotgateway.io/api/v1/devices?type=temperature&status=online" \
  -H "Authorization: Bearer YOUR_TOKEN"
devices = requests.get(
    "https://api.iotgateway.io/api/v1/devices",
    headers={"Authorization": f"Bearer {token}"},
    params={"type": "temperature", "status": "online"}
).json()["data"]
const res = await fetch('/api/v1/devices?type=temperature&status=online', {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { data, meta } = await res.json();
console.log(`${meta.total} devices found`);
GET /api/v1/devices/{id} Get device details

Retrieve complete details for a specific IoT device including historical reading summary and alert history.

{
  "success": true,
  "data": {
    "id": "dev_x1y2z3",
    "name": "TempSensor-01",
    "type": "temperature",
    "gateway_id": "gw_a1b2c3d4",
    "status": "online",
    "battery": 87,
    "firmware": "v1.2.0",
    "location": "Server Room A",
    "thresholds": { "min": 15.0, "max": 35.0 },
    "last_reading": { "value": 23.4, "unit": "°C", "timestamp": "2024-11-15T10:29:00Z" },
    "stats_24h": { "min": 21.1, "max": 25.8, "avg": 23.2 },
    "active_alerts": 0,
    "created_at": "2023-08-10T00:00:00Z"
  }
}
curl https://api.iotgateway.io/api/v1/devices/dev_x1y2z3 \
  -H "Authorization: Bearer YOUR_TOKEN"
const res = await fetch('/api/v1/devices/dev_x1y2z3', {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { data } = await res.json();
PUT /api/v1/devices/{id} Update device

Update device metadata such as name, location, and alert thresholds.

Request Body
FieldTypeRequiredDescription
namestringOptionalDevice display name
locationstringOptionalPhysical location description
thresholdsobjectOptionalAlert thresholds with min and max values
{
  "name": "TempSensor-01-Renamed",
  "location": "Server Room B",
  "thresholds": { "min": 10.0, "max": 40.0 }
}
{
  "success": true,
  "data": {
    "id": "dev_x1y2z3",
    "name": "TempSensor-01-Renamed",
    "location": "Server Room B",
    "thresholds": { "min": 10.0, "max": 40.0 },
    "updated_at": "2024-11-15T10:35:00Z"
  }
}
curl -X PUT https://api.iotgateway.io/api/v1/devices/dev_x1y2z3 \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"name": "TempSensor-01-Renamed", "thresholds": {"min": 10, "max": 40}}'
await fetch('/api/v1/devices/dev_x1y2z3', {
  method: 'PUT',
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'New Name', thresholds: { min: 10, max: 40 } })
});
DELETE /api/v1/devices/{id} Delete device

Permanently remove a device from the system. All associated historical data and alerts will also be deleted. This action cannot be undone.

{ "success": true, "data": { "message": "Device deleted successfully", "id": "dev_x1y2z3" } }
curl -X DELETE https://api.iotgateway.io/api/v1/devices/dev_x1y2z3 \
  -H "Authorization: Bearer YOUR_TOKEN"
await fetch('/api/v1/devices/dev_x1y2z3', {
  method: 'DELETE',
  headers: { 'Authorization': `Bearer ${token}` }
});
Alerts
GET /api/v1/alerts List all alerts

Returns a list of all system alerts. Filterable by severity, status (acknowledged/unacknowledged), and date range.

Query Parameters
ParameterTypeRequiredDescription
severitystringOptionalcritical, warning, info
acknowledgedbooleanOptionalFilter by acknowledged state
fromstringOptionalStart date ISO 8601 (e.g. 2024-11-01T00:00:00Z)
tostringOptionalEnd date ISO 8601
{
  "success": true,
  "data": [
    {
      "id": "alert_9f8e7d6c",
      "severity": "critical",
      "type": "threshold_exceeded",
      "message": "Temperature exceeded 35°C on TempSensor-01",
      "device_id": "dev_x1y2z3",
      "gateway_id": "gw_a1b2c3d4",
      "acknowledged": false,
      "created_at": "2024-11-15T08:15:00Z"
    }
  ],
  "meta": { "total": 17, "unacknowledged": 5 }
}
curl "https://api.iotgateway.io/api/v1/alerts?severity=critical&acknowledged=false" \
  -H "Authorization: Bearer YOUR_TOKEN"
const res = await fetch('/api/v1/alerts?severity=critical&acknowledged=false', {
  headers: { 'Authorization': `Bearer ${token}` }
});
POST /api/v1/alerts/acknowledge Acknowledge alerts

Acknowledge one or more alerts, marking them as seen. Optionally add a resolution note.

Request Body
FieldTypeRequiredDescription
alert_idsstring[]RequiredArray of alert IDs to acknowledge
notestringOptionalResolution note or comment
{
  "alert_ids": ["alert_9f8e7d6c", "alert_1a2b3c4d"],
  "note": "Investigated — HVAC adjusted to resolve high temp"
}
{
  "success": true,
  "data": {
    "acknowledged": 2,
    "failed": 0,
    "acknowledged_at": "2024-11-15T10:45:00Z"
  }
}
curl -X POST https://api.iotgateway.io/api/v1/alerts/acknowledge \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"alert_ids": ["alert_9f8e7d6c"], "note": "Resolved"}'
await fetch('/api/v1/alerts/acknowledge', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ alert_ids: ['alert_9f8e7d6c'], note: 'Resolved' })
});
DELETE /api/v1/alerts/{id} Delete alert

Permanently delete a specific alert from the system. Requires admin role.

{ "success": true, "data": { "message": "Alert deleted", "id": "alert_9f8e7d6c" } }
curl -X DELETE https://api.iotgateway.io/api/v1/alerts/alert_9f8e7d6c \
  -H "Authorization: Bearer YOUR_TOKEN"
await fetch('/api/v1/alerts/alert_9f8e7d6c', {
  method: 'DELETE', headers: { 'Authorization': `Bearer ${token}` }
});
AI Agent AI-Powered
POST /api/v1/ai/diagnose Trigger AI diagnosis

Trigger an AI-powered diagnostic analysis on a gateway or device. The AI agent will analyze recent telemetry data, identify anomalies, and return a diagnosis report with recommended actions.

Request Body
FieldTypeRequiredDescription
target_typestringRequiredgateway or device
target_idstringRequiredID of the gateway or device to diagnose
lookback_hoursintegerOptionalHours of history to analyze (default: 24, max: 168)
deep_scanbooleanOptionalEnable deep pattern analysis (slower, more thorough)
{
  "target_type": "gateway",
  "target_id": "gw_a1b2c3d4",
  "lookback_hours": 48,
  "deep_scan": true
}
{
  "success": true,
  "data": {
    "diagnosis_id": "diag_m7n8p9q0",
    "target": { "type": "gateway", "id": "gw_a1b2c3d4" },
    "status": "completed",
    "health_score": 74,
    "anomalies": [
      {
        "type": "memory_leak",
        "severity": "warning",
        "description": "Memory usage increasing ~2% per hour over last 48h",
        "detected_at": "2024-11-15T06:00:00Z"
      }
    ],
    "recommendations": ["Schedule gateway restart within 24h", "Update firmware to v2.4.2"],
    "analyzed_at": "2024-11-15T10:30:00Z",
    "duration_ms": 3240
  }
}
curl -X POST https://api.iotgateway.io/api/v1/ai/diagnose \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"target_type":"gateway","target_id":"gw_a1b2c3d4","lookback_hours":48}'
result = requests.post(
    "https://api.iotgateway.io/api/v1/ai/diagnose",
    headers={"Authorization": f"Bearer {token}"},
    json={"target_type": "gateway", "target_id": "gw_a1b2c3d4", "lookback_hours": 48}
).json()
print(f"Health score: {result['data']['health_score']}")
const res = await fetch('/api/v1/ai/diagnose', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ target_type: 'gateway', target_id: 'gw_a1b2c3d4' })
});
const { data } = await res.json();
console.log(`Health: ${data.health_score}/100`);
GET /api/v1/ai/logs Get AI agent logs

Retrieve the AI agent's activity logs including all diagnoses, chat interactions, and automated actions performed.

Query Parameters
ParameterTypeRequiredDescription
typestringOptionaldiagnosis, chat, action, recommendation
limitintegerOptionalNumber of log entries (default: 50, max: 500)
{
  "success": true,
  "data": [
    {
      "id": "log_4r5t6y7u",
      "type": "diagnosis",
      "summary": "Ran deep scan on gw_a1b2c3d4",
      "result": "warning",
      "duration_ms": 3240,
      "timestamp": "2024-11-15T10:30:00Z"
    },
    {
      "id": "log_8i9o0p1q",
      "type": "chat",
      "summary": "User asked about gateway health",
      "timestamp": "2024-11-15T09:45:00Z"
    }
  ]
}
curl "https://api.iotgateway.io/api/v1/ai/logs?type=diagnosis&limit=20" \
  -H "Authorization: Bearer YOUR_TOKEN"
const res = await fetch('/api/v1/ai/logs?type=diagnosis&limit=20', {
  headers: { 'Authorization': `Bearer ${token}` }
});
POST /api/v1/ai/chat Chat with AI agent

Send a natural language message to the AI agent. The agent has full context about your gateways, devices, and alerts, and can answer questions, run diagnostics, and take actions.

Request Body
FieldTypeRequiredDescription
messagestringRequiredNatural language question or command
session_idstringOptionalConversation session ID for context continuity
contextobjectOptionalAdditional context (e.g. {"focus_gateway": "gw_a1b2c3d4"})
{
  "message": "Why is Gateway-Alpha showing high memory usage?",
  "session_id": "sess_abc123",
  "context": { "focus_gateway": "gw_a1b2c3d4" }
}
{
  "success": true,
  "data": {
    "reply": "Gateway-Alpha is experiencing a gradual memory leak. Memory has grown from 62% to 78% over the past 48 hours, increasing approximately 2% per hour. I recommend scheduling a restart within the next 24 hours. Would you like me to schedule the restart automatically?",
    "session_id": "sess_abc123",
    "actions_taken": [],
    "confidence": 0.92,
    "sources": ["diagnosis_diag_m7n8p9q0", "telemetry_last_48h"]
  }
}
curl -X POST https://api.iotgateway.io/api/v1/ai/chat \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message": "What is the health status of all gateways?"}'
response = requests.post(
    "https://api.iotgateway.io/api/v1/ai/chat",
    headers={"Authorization": f"Bearer {token}"},
    json={"message": "Are there any critical alerts right now?", "session_id": session_id}
).json()
print(response["data"]["reply"])
const res = await fetch('/api/v1/ai/chat', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ message: 'Summarize all critical alerts', session_id: sessionId })
});
const { data } = await res.json();
console.log(data.reply);
GET /api/v1/ai/recommendations Get AI recommendations

Retrieve the latest AI-generated optimization recommendations for your IoT infrastructure. Updated every 6 hours.

{
  "success": true,
  "data": {
    "generated_at": "2024-11-15T06:00:00Z",
    "recommendations": [
      {
        "id": "rec_001",
        "priority": "high",
        "category": "maintenance",
        "title": "Restart Gateway-Alpha",
        "description": "Memory usage trending upward. Schedule restart to prevent service disruption.",
        "affected_resource": "gw_a1b2c3d4",
        "estimated_impact": "Prevents potential outage affecting 24 devices"
      },
      {
        "id": "rec_002",
        "priority": "medium",
        "category": "optimization",
        "title": "Increase poll interval on low-activity devices",
        "description": "12 devices have had no events in 7 days. Increasing poll interval saves bandwidth.",
        "estimated_impact": "~23% reduction in MQTT traffic"
      }
    ]
  }
}
curl https://api.iotgateway.io/api/v1/ai/recommendations \
  -H "Authorization: Bearer YOUR_TOKEN"
const res = await fetch('/api/v1/ai/recommendations', {
  headers: { 'Authorization': `Bearer ${token}` }
});
const { data } = await res.json();
data.recommendations.forEach(r => console.log(`[${r.priority}] ${r.title}`));
Analytics
GET /api/v1/analytics/traffic Get traffic analytics

Retrieve network traffic analytics for all gateways. Data is aggregated by hour, day, or week.

Query Parameters
ParameterTypeRequiredDescription
intervalstringOptionalhour, day, week (default: day)
gateway_idstringOptionalScope to specific gateway
daysintegerOptionalNumber of days back (default: 7, max: 90)
{
  "success": true,
  "data": {
    "interval": "day",
    "total_messages": 1847293,
    "total_bytes": 4831920128,
    "series": [
      { "timestamp": "2024-11-09", "messages": 248320, "bytes_in": 621024128, "bytes_out": 42084352 },
      { "timestamp": "2024-11-10", "messages": 261840, "bytes_in": 654320640, "bytes_out": 44839936 }
    ]
  }
}
curl "https://api.iotgateway.io/api/v1/analytics/traffic?interval=day&days=7" \
  -H "Authorization: Bearer YOUR_TOKEN"
const res = await fetch('/api/v1/analytics/traffic?interval=day&days=7', {
  headers: { 'Authorization': `Bearer ${token}` }
});
GET /api/v1/analytics/devices Device analytics

Returns device statistics including online/offline ratios, battery distribution, type breakdown, and activity trends.

{
  "success": true,
  "data": {
    "total": 142,
    "online": 131,
    "offline": 8,
    "low_battery": 3,
    "by_type": {
      "temperature": 48,
      "humidity": 36,
      "motion": 24,
      "pressure": 18,
      "camera": 16
    },
    "avg_battery": 74.2,
    "online_rate_trend": [98.1, 97.8, 92.3, 97.2]
  }
}
curl https://api.iotgateway.io/api/v1/analytics/devices \
  -H "Authorization: Bearer YOUR_TOKEN"
const { data } = await fetch('/api/v1/analytics/devices', {
  headers: { 'Authorization': `Bearer ${token}` }
}).then(r => r.json());
console.log(`Online rate: ${(data.online/data.total*100).toFixed(1)}%`);
GET /api/v1/analytics/alerts Alert analytics

Returns alert statistics including frequency trends, severity distribution, and MTTA (Mean Time To Acknowledge).

{
  "success": true,
  "data": {
    "total_7d": 89,
    "by_severity": { "critical": 12, "warning": 45, "info": 32 },
    "acknowledged_rate": 0.87,
    "mtta_minutes": 8.4,
    "top_sources": [
      { "device_id": "dev_x1y2z3", "name": "TempSensor-01", "count": 14 }
    ]
  }
}
curl https://api.iotgateway.io/api/v1/analytics/alerts \
  -H "Authorization: Bearer YOUR_TOKEN"
const { data } = await fetch('/api/v1/analytics/alerts', {
  headers: { 'Authorization': `Bearer ${token}` }
}).then(r => r.json());
console.log(`MTTA: ${data.mtta_minutes} min`);
GET /api/v1/analytics/performance Performance metrics

Retrieve system-wide performance metrics including API latency, gateway CPU/memory trends, and message processing throughput.

Query Parameters
ParameterTypeRequiredDescription
metricstringOptionalall, latency, throughput, resource
daysintegerOptionalDays of data (default: 7)
{
  "success": true,
  "data": {
    "api_latency": {
      "p50_ms": 42,
      "p95_ms": 187,
      "p99_ms": 412
    },
    "throughput": {
      "avg_messages_per_second": 214,
      "peak_messages_per_second": 891
    },
    "gateway_resources": {
      "avg_cpu": 38.4,
      "avg_memory": 61.2,
      "max_cpu": 87.3,
      "max_memory": 78.1
    },
    "uptime_percent": 99.94
  }
}
curl "https://api.iotgateway.io/api/v1/analytics/performance?metric=all" \
  -H "Authorization: Bearer YOUR_TOKEN"
const { data } = await fetch('/api/v1/analytics/performance?metric=all', {
  headers: { 'Authorization': `Bearer ${token}` }
}).then(r => r.json());
console.log(`p95 latency: ${data.api_latency.p95_ms}ms`);