Skip to content

Latest commit

 

History

History
706 lines (495 loc) · 14.1 KB

File metadata and controls

706 lines (495 loc) · 14.1 KB

API Reference

Complete reference for all TerraFerma API endpoints. The platform exposes 67 API routes organized into domain-specific groups.


Table of Contents


Authentication

All authenticated endpoints require a valid session. The v1 API endpoints use API key authentication via the authorize middleware.

POST /api/auth/register

Create a new user account.

Request Body:

{
  "email": "user@example.com",
  "password": "securePassword123",
  "name": "Mario Rossi"
}

Response: 201 Created

{
  "user": { "id": "usr-...", "email": "user@example.com", "name": "Mario Rossi" },
  "session": { "token": "..." }
}

POST /api/auth/login

Authenticate and create a session.

Request Body:

{
  "email": "user@example.com",
  "password": "securePassword123"
}

Response: 200 OK

{
  "user": { "id": "usr-...", "email": "...", "role": "admin" },
  "session": { "token": "...", "expiresAt": "..." }
}

GET /api/auth/session

Get the current authenticated session.

Response: 200 OK

{
  "user": { "id": "usr-...", "email": "...", "role": "...", "organizationId": "..." },
  "authenticated": true
}

Health & Status

GET /api/health

System health check. Returns database and bus status.

Response: 200 OK

{
  "status": "ok",
  "checks": {
    "database": { "status": "ok", "message": "Database reachable" },
    "bus": { "status": "ok", "message": "Bus operational", "details": { "totalPublished": 42, "errors": 0 } }
  },
  "version": "0.1.0",
  "uptime": 3600.5,
  "timestamp": "2026-05-13T09:30:00.000Z"
}

Status Codes:

  • 200 — Healthy (ok or degraded)
  • 503 — Unhealthy

GET /api/observability

Get error and performance statistics from the Sentry buffer.

Response: 200 OK

{
  "errors": { "total": 5, "byModule": { "bus": 2, "arpae": 3 }, "bySeverity": { "error": 5 } },
  "performance": { "totalRequests": 150, "avgDurationMs": 45, "p95DurationMs": 120, "errorRate": 0.02 },
  "recentErrors": [...]
}

ARPAE Data Pipeline

GET /api/arpae/stations

List all monitored hydrometric stations.

Response: 200 OK

{
  "stations": [
    {
      "id": "montone-forli",
      "name": "Montone a Forlì",
      "river": "Montone",
      "basin": "Montone-Rabbi",
      "latitude": 44.2225,
      "longitude": 12.0408
    }
  ]
}

GET /api/arpae/monitoring

Get current monitoring data including river levels, rainfall, and soil conditions.

Response: 200 OK

{
  "snapshot": {
    "hydrometric": { "montone-forli": [{ "level": 2.1, "timestamp": "..." }] },
    "rainfall": { "montone-forli": { "last24h": 38 } },
    "soilSaturation": { "montone-forli": { "percentage": 68 } }
  },
  "pipelineStatus": {
    "lastFetch": "...",
    "totalFetches": 96,
    "demoMode": false
  }
}

GET /api/arpae/stream

Server-sent events stream of real-time ARPAE readings.

Response: text/event-stream

GET|POST /api/arpae/pipeline

  • GET — Get pipeline status and statistics
  • POST — Trigger a manual pipeline ingestion cycle

GET /api/cron/arpae

Cron endpoint for scheduled ARPAE data fetch. Requires CRON_SECRET authorization.

Headers: Authorization: Bearer <CRON_SECRET>


Alerts

GET /api/alerts

List all alerts (historical + operational).

Response: 200 OK

{
  "alerts": [
    {
      "id": "preallerta-rabbi-2026-05",
      "title": "Preallerta Rabbi in salita verso soglia arancione",
      "severity": "moderata",
      "status": "attiva",
      "date": "13 mag 2026",
      "affectedAreas": ["Predappio", "Forlì sud"]
    }
  ]
}

GET|POST /api/alerts/preferences

  • GET — Retrieve alert preferences for the current user
  • POST — Update alert preferences (channels, thresholds, stations)

GET|POST /api/alerts/engine

  • GET — Get current alert engine state and active rules
  • POST — Manually trigger alert evaluation for a station

GET|POST /api/alert-correlation

  • GET — List active correlated alerts (multi-signal compound events)
  • POST — Submit signals for correlation analysis

Billing

POST /api/billing/checkout

Create a Stripe checkout session for subscription upgrade.

Request Body:

{
  "tier": "professional",
  "organizationId": "org-..."
}

Response: 200 OK

{
  "url": "https://checkout.stripe.com/...",
  "sessionId": "cs_..."
}

POST /api/billing/portal

Create a Stripe customer portal session for subscription management.

Response: 200 OK

{
  "url": "https://billing.stripe.com/..."
}

GET /api/billing/status

Get current subscription and billing status.

Response: 200 OK

{
  "tier": "professional",
  "status": "active",
  "currentPeriodEnd": "2026-06-13T00:00:00Z",
  "usage": { "queriesUsed": 42, "queriesLimit": 500 }
}

POST /api/billing/webhook

Stripe webhook handler. Processes checkout.session.completed, invoice.paid, customer.subscription.updated, and customer.subscription.deleted events.

Headers: stripe-signature: <webhook_signature>


Compliance

GET /api/compliance/tasks

List compliance tasks for the current user/organization.

Response: 200 OK

{
  "tasks": [
    {
      "id": "task-...",
      "title": "Aggiornare piano emergenza",
      "category": "emergency_planning",
      "priority": "high",
      "status": "pending",
      "dueDate": "2026-06-01"
    }
  ]
}

GET /api/compliance/obligations

List regulatory obligations applicable to the organization's properties.

GET|POST /api/compliance-orchestrator

  • GET — Get orchestrator configuration and action history
  • POST — Execute compliance orchestration (auto-apply changes, create tasks)

GET /api/regulatory

Get regulatory change feed and monitoring source status.


Insurance

GET|POST /api/insurance/claims

  • GET — List insurance claims for the organization
  • POST — Create a new insurance claim

POST Request Body:

{
  "propertyId": "prop-...",
  "damageType": "Apparecchiature elettriche",
  "estimatedValue": 9200,
  "eventDate": "2024-03-14",
  "description": "Flood damage to electrical equipment"
}

GET|POST /api/insurance/parametric

  • GET — List parametric insurance policies and triggers
  • POST — Create or activate a parametric policy

GET /api/insurance/report

Generate a comprehensive insurance report for the organization.

POST /api/damage-reports

Submit a damage report.

Request Body:

{
  "site": "Magazzino via Emilia Ovest",
  "damageType": "Danno a scorte",
  "estimatedValue": 18500,
  "eventDate": "2023-05-17",
  "notes": "Flood damage to warehouse inventory"
}

Municipal & Emergency

GET /api/municipal

Get municipal dashboard data including infrastructure assets and citizen communications.

GET|POST /api/municipal/evacuation

  • GET — List evacuation plans and zones
  • POST — Create or activate an evacuation plan

GET /api/events

Get the flood event feed.

Response: 200 OK

{
  "events": [
    {
      "id": "evt-...",
      "title": "Piena del Montone",
      "state": "active",
      "severity": "warning",
      "affectedBasins": ["Montone-Rabbi"],
      "detectedAt": "..."
    }
  ]
}

Prediction & Intelligence

GET /api/prediction

Get current flood predictions for all monitored stations.

Response: 200 OK

{
  "predictions": [
    {
      "stationId": "montone-forli",
      "stationName": "Montone a Forlì",
      "overallRisk": "moderato",
      "confidence": 78,
      "probability6h": 15,
      "probability12h": 32,
      "probability24h": 48
    }
  ]
}

GET|POST /api/backtesting

  • GET — List backtest runs and their results
  • POST — Create and execute a new backtest run

GET /api/backtesting/[runId]

Get detailed results for a specific backtest run including precision, recall, F1 score, and confusion matrix.

GET|POST /api/cascade

  • GET — List cascade simulation results
  • POST — Run a new cascade simulation scenario

POST /api/cascade/compare

Compare multiple cascade scenarios side-by-side.

Request Body:

{
  "scenarioIds": ["scenario-montone-4.5", "scenario-ronco-3.8"]
}

GET /api/dashboard-intelligence

Get role-specific dashboard intelligence data (business, municipal, or insurer view).

Query Parameters:

  • rolebusiness | municipal | insurer (default: business)

Portfolio & Financial

GET /api/portfolio

Get portfolio risk summary across all properties.

GET /api/pricing

Get premium pricing information.

GET /api/impact

Get impact assessment data for recent events.

GET /api/marketplace

Get insurer marketplace listings and premium comparisons.

GET|POST /api/onboarding

  • GET — Get current onboarding state
  • POST — Update onboarding progress

GET /api/bcp

Get business continuity plans for the organization.

GET /api/pnrr

Get PNRR projects, bandi (calls), and grant applications.


Sensors & Watershed

GET /api/iot

Get IoT device fleet data including readings and alerts.

GET /api/federated-sensors

Get federated sensor network data from partner organizations.

GET /api/watershed

Get watershed topology and cascade alert data.

GET /api/rivers

Get river monitoring records with current levels and trends.


Data Exchange & Evidence

GET /api/data-exchange

Get data sharing agreements and exchange history.

GET|POST /api/evidence-chain

  • GET — List evidence items and packages
  • POST — Collect evidence for an event

Platform Services

GET /api/bus

Get Risk Intelligence Bus status, statistics, and recent event log.

Response: 200 OK

{
  "stats": {
    "totalPublished": 142,
    "totalDelivered": 138,
    "totalDropped": 0,
    "errors": 4,
    "subscriberCount": 20,
    "eventTypes": 30,
    "logSize": 142
  },
  "recentEvents": [...]
}

GET|POST /api/webhooks

  • GET — List registered webhooks
  • POST — Register a new webhook

POST Request Body:

{
  "url": "https://example.com/webhook",
  "eventTypes": ["alert.triggered", "prediction.generated"]
}

Push Notifications

POST /api/push/subscribe

Subscribe a device for web push notifications.

Request Body:

{
  "subscription": {
    "endpoint": "https://fcm.googleapis.com/...",
    "keys": { "p256dh": "...", "auth": "..." }
  }
}

DELETE /api/push/subscribe

Unsubscribe a device from push notifications.

POST /api/push/send

Send a push notification (admin only).


Versioned API (v1)

The v1 API is the stable, authenticated API surface for external integrations. All v1 endpoints require API key authentication via the authorize middleware.

Authentication:

Authorization: Bearer <API_KEY>

GET /api/v1/openapi

Get the OpenAPI specification for the v1 API.

GET /api/v1/alerts

List alerts with filtering. Authenticated.

Query Parameters:

  • severity — Filter by severity
  • status — Filter by status
  • limit — Max results (default: 50)

POST /api/v1/risk/assess

Perform a risk assessment for an address.

Request Body:

{
  "address": "Via Ravegnana 145, Forlì"
}

Response: 200 OK

{
  "riskScore": 8,
  "floodZone": "Fascia B con possibili esondazioni e ristagni rapidi",
  "paiStatus": "PAI: compatibile solo con misure di riduzione del danno.",
  "historicalEvents": ["16-17 mag 2023 · Alluvione straordinaria in Romagna"],
  "summary": "L'indirizzo ricade in un'area che richiede monitoraggio continuo."
}

GET /api/v1/risk/report

Generate a comprehensive risk report for a property.

GET /api/v1/risk/embed

Get an embeddable risk card for a given address.

Query Parameters:

  • address — Property address (required)
  • apiKey — API key for widget authentication

GET /api/v1/risk/widget

Render an HTML risk widget for embedding.

GET /api/v1/predictions/[stationId]

Get flood predictions for a specific station.

Path Parameters:

  • stationId — Station identifier (e.g., montone-forli)

GET /api/v1/properties

List properties for the authenticated organization.

GET /api/v1/properties/[id]/risk

Get risk details for a specific property.

POST /api/v1/cascade

Run a cascade simulation.

POST /api/v1/investments/optimize

Generate an optimized investment portfolio for resilience.

GET /api/v1/pai/lookup

Look up PAI (Piano Assetto Idrogeologico) classification for an address.

Query Parameters:

  • address — Address to look up
  • lat / lng — Coordinates (alternative to address)

Error Responses

All endpoints return consistent error responses:

{
  "error": "Error description",
  "code": "ERROR_CODE",
  "details": {}
}

Common Status Codes:

Code Meaning
400 Bad Request — Invalid parameters
401 Unauthorized — Missing or invalid auth
403 Forbidden — Insufficient permissions
404 Not Found
429 Rate Limited
500 Internal Server Error

Rate Limiting

API rate limits are enforced per API key and subscription tier:

Tier Rate Limit Monthly Queries
Free 10 req/min 5
Professional 60 req/min 500
Enterprise 300 req/min Unlimited