Skip to content

API Reference

Layerr exposes a comprehensive HTTP API with 158 routes across 21 categories. All routes flow through the central server (server.ts) and are protected by gateway middleware unless otherwise noted.

This count excludes three internal-only routes not meant for API consumers: the container liveness/readiness probes GET /healthz and GET /readyz (see Health & Readiness), and the production-only SPA catch-all that serves the frontend for unmatched paths (it doesn’t even exist as an Express route in dev mode, where Vite’s own middleware handles it instead).

All API responses follow a consistent envelope:

{
"data": { ... },
"meta": {
"requestId": "uuid",
"timestamp": "2026-01-15T10:30:00Z",
"workspaceId": "workspace-slug"
}
}

Error responses include:

{
"error": {
"code": "PROVIDER_UNAVAILABLE",
"message": "All providers in fallback chain exhausted",
"details": { "attempts": 3, "providers": ["openai", "anthropic", "ollama"] }
}
}

Most routes require the ADMIN_API_KEY or a valid session, passed either as Authorization: Bearer <key>, the x-admin-key: <key> header, or the layerr_session cookie set by /api/auth/login. The key/session is validated by the gateway middleware (security/gateway/middleware.ts).

Gateway / orchestration routes (the OpenAI-compatible /v1/* endpoints) additionally require the gateway_access capability and the orchestration.execute scope, and accept scoped lgw_* gateway tokens (see Gateway Token Management) in addition to admin keys and session cookies.

Routes marked [admin-only] below require an admin-role account regardless of capability grants. Routes marked with a capability name (e.g. traces, budget_controls) additionally require that capability be granted to the caller’s plan/workspace (see Entitlements & Access).

Per-workspace rate limits are enforced by the gateway:

TierRequests/minuteBurst
Free6010
Standard30050
Enterprise2000200

These routes implement the OpenAI API specification, allowing existing clients to use Layerr as a drop-in replacement.

RouteMethodDescription
/v1/chat/completionsPOSTMain chat completions endpoint (streaming and non-streaming). Accepts OpenAI-format requests, routes through Layerr intelligence
/v1/embeddingsPOSTEmbeddings passthrough to the caller’s configured cloud provider only — there is no local-model embeddings path
/v1/modelsGETList available models across all configured providers; best-effort live provider discovery is merged in
/v1/models/{modelId}GETGet details for a specific model (for SDKs that require this endpoint to exist)

Request body (OpenAI-compatible with Layerr extensions):

{
"model": "layerr-auto",
"messages": [{"role": "user", "content": "Write a React component"}],
"stream": true,
"layerr": {
"strategy": "quality",
"fallback": "relaxed",
"explain": true
}
}

Layerr extensions (all optional):

FieldTypeDescription
layerr.strategystringOverride strategy: cost, speed, quality, balanced
layerr.fallbackstringFallback mode: strict, relaxed, none
layerr.explainbooleanInclude routing explanation in response headers
layerr.workspacestringTarget workspace slug (for admin keys)

RouteMethodDescription
/api/routerPOSTClassify a raw prompt and return a routing decision (no model call)
/api/chatPOSTLayerr-native chat endpoint; queues, applies backpressure/global concurrency limiting, and streams the response as newline-delimited JSON
/api/conversationsGETList conversations; paginated if limit/offset given, else the legacy full list
/api/conversationsPOSTCreate a conversation
/api/conversations/{id}GETGet a specific conversation with full messages
/api/conversations/{id}PUTUpdate a conversation (title/messages)
/api/conversations/{id}DELETEDelete a conversation
/api/conversations/exportGETFull export of all of the caller’s conversations, all messages included
/api/conversations/{id}/projectPATCHAssign a conversation to a project
/api/projectsGETList projects
/api/projectsPOSTCreate a project (blocked once the workspace’s project_count usage limit is reached)
/api/projects/{id}PUTUpdate a project
/api/projects/{id}DELETEDelete a project; ?deleteChats=true cascades to its conversations

The Layerr-native path is split into two calls:

  1. POST /api/router — send the raw prompt. Returns a routing decision of the shape { category, model, provider, reasoning, confidence }.
  2. The client enriches that decision with the provider URL and a fallback pool.
  3. POST /api/chat — send the enriched decision plus messages. The response streams back as newline-delimited JSON.

Request body:

{
"prompt": "Refactor this function to TypeScript",
"hasAttachments": false
}

Response (routing decision):

{
"category": "CODING",
"model": "claude-sonnet-4",
"provider": "anthropic-prod",
"reasoning": "Code refactor on a quality-weighted workspace profile",
"confidence": 0.94
}

The native chat endpoint provides more control than the OpenAI-compatible route:

Request body:

{
"messages": [{"role": "user", "content": "Refactor this to TypeScript"}],
"context": {
"files": ["src/App.js", "src/types.ts"]
},
"preferences": {
"strategy": "quality",
"maxCost": 0.50,
"maxLatency": 30000
}
}

RouteMethodDescription
/api/auth/statusGETCurrent auth/session state, registration-enabled flag, active workspace
/api/auth/loginPOSTUsername/password login; sets the layerr_session cookie. Rate-limited
/api/auth/api-key-loginPOSTLogin via a layerr-api-issued API key. Rate-limited
/api/auth/workspaces/refreshPOSTRe-fetch linked workspaces/active workspace for a layerr-api-linked account
/api/auth/registerPOSTSelf-service registration; 403s unless the admin has enabled registration. Rate-limited
/api/auth/logoutPOSTClear the session cookie / server-side session
/api/auth/passwordPUTChange the caller’s own password; invalidates all existing sessions and issues a new one. Rate-limited

Per-user runtime configuration (provider URLs, API keys, category models) — distinct from the workspace strategy/orchestration profiles under Workspace Management.

RouteMethodDescription
/api/configGETRead the effective provider config for the caller; secret keys are masked before returning
/api/configPOSTSave user config; validates URLs (SSRF guard), restores masked keys by identity, syncs the provider-count usage metric

RouteMethodDescription
/api/onboarding/stateGETRead resumable onboarding state
/api/onboarding/statePUTDispatch an onboarding state-machine action
/api/onboarding/skipPOSTSkip onboarding
/api/onboarding/completePOSTMark onboarding complete (auto-derives licenseKeyPresent)
/api/onboarding/resetPOSTReset onboarding state
/api/onboarding/providers/detect-localPOSTProbe well-known local ports (Ollama, LM Studio, etc.) for running runtimes
/api/onboarding/providers/probePOSTProbe an arbitrary provider URL + key (SSRF-guarded) and infer its capabilities
/api/onboarding/providers/savePOSTIdempotent upsert of a provider into the user’s or workspace’s local provider list
/api/integrations/snippetsGETRender ready-to-paste integration code snippets (Cursor, Claude Code, etc.) with the caller’s gateway URL
/api/integrations/diagnosePOSTRun 4 canned probes (compatibility, streaming, tool-calling, invalid-model) against the caller’s own /v1/chat/completions

RouteMethodDescription
/api/healthGETProbe all configured providers’ connectivity plus Ollama auto-detection; includes a credential-health summary
/api/modelsGETAggregate discovered models across all configured local providers
/api/models/capabilitiesGETModel capability registry lookup (single model, or a filtered list with optional benchmark data)
/api/providers/healthGETPer-provider health snapshots (ring-buffer derived) plus basic connectivity
/api/providers/orchestrationGETPer-provider orchestration-role statistics, idle-provider detection, deterministic recommendations
/api/providers/credentials/healthGETFull credential/connection health report
/api/providers/credentials/{id}/healthGETHealth for one credential connection
/api/providers/credentials/{id}/rotatePOSTBegin or immediately complete a credential rotation
/api/providers/credentials/{id}/validatePOSTProbe one credential right now
/api/providers/credentials/{id}/revokePOSTRevoke a credential
/api/providers/credentials/{id}/logGETRotation history log for one connection
/api/providers/credentials/validate-allPOSTValidate every tracked connection at once
/api/providers/rate-limitsGETPer-provider rate-limit configs plus live utilization telemetry
{
"id": "openai-prod",
"name": "OpenAI Production",
"type": "openai",
"baseUrl": "https://api.openai.com/v1",
"models": ["gpt-4o", "gpt-4o-mini", "o1-preview"],
"status": "active",
"health": {
"status": "healthy",
"latencyP50": 1200,
"latencyP99": 4500,
"errorRate": 0.002
}
}

Named orchestration contexts and their strategy weighting — distinct from the per-user provider config under Global/User Config.

RouteMethodDescription
/api/workspace/profilesGETList all workspace profiles with their settings
/api/workspace/preferencesGETGet the caller’s active-workspace preference
/api/workspace/preferencesPUTSet the caller’s active-workspace preference (pin + optimization strategy)
/api/workspace/activeGETResolve the effective workspace profile (weights/thresholds) for a category

RouteMethodDescription
/api/strategy/resolveGETResolve an execution strategy from workload signals (category, complexity, latency/cost sensitivity, etc.)
/api/strategy/workspacesGETList workspaces with strategy configuration
/api/strategy/workspaces/{slug}/strategiesGETList strategies for a workspace

RouteMethodDescription
/api/tracesGETList persisted orchestration traces (retention-window filtered)
/api/traces/{id}GETLoad and build the full replay view of one trace
/api/traces/compareGETCompare two traces via query params (?a=<id>&b=<id>)
/api/traces/trendsGETTrend analysis over recent traces
/api/runtime/healthGETOrchestration runtime health: queue depth, concurrency, degraded-mode policy, provider saturation
/api/runtime/diagnosticsGETHeap/event-loop/cache-size diagnostics snapshot
/api/runtime/incidentsGETDetected incident patterns (failure spikes, saturation) summary
/api/runtime/incidents/exportGETNDJSON export of incidents for log aggregators
/api/runtime/error-codesGETStatic LAYERR-XXXX error-code registry
/api/runtime/executionsGETLive plus recent (30-minute window) orchestration executions from the tracer ring buffer; regular users are self-scoped, admins may pass ?scope=all
/api/scoring/runtime-previewGETPreview computed runtime scores for a category’s candidate model pool
/api/workload/analyzeGETAnalyze a prompt/message set into a workload profile with a signal breakdown
/api/intelligenceGETActive intelligence-module flags plus 30-minute ring-buffer request statistics (categories, fallback/retry/timeout rates)
/api/intelligence/adaptiveGETAdaptive-learning score adjustments (provider affinity, strategy effectiveness, etc.)

Recent activity is served by GET /api/usage/recent (see Usage & Limits), not by a trace route. Per-trace cost analysis lives at GET /api/economics/trace/{traceId} (see Economics Routes).

{
"traceId": "trace-uuid",
"workspaceId": "my-project",
"intent": {
"classification": "coding",
"confidence": 0.94
},
"strategy": "quality",
"routingDecision": {
"primaryProvider": "anthropic-prod",
"primaryModel": "claude-sonnet-4",
"fallbackChain": ["openai-prod", "ollama-local"],
"scores": {
"quality": 0.92,
"speed": 0.78,
"cost": 0.65
}
},
"execution": {
"attempts": 1,
"finalProvider": "anthropic-prod",
"latencyMs": 3400,
"tokensIn": 1240,
"tokensOut": 892,
"costUsd": 0.023
},
"explanation": {
"summary": "Selected Claude Sonnet for high-quality code generation",
"providerRationale": "Top quality score (0.92) for coding workloads"
}
}

RouteMethodDescription
/api/repo/intelligenceGETRepository profile and snapshot (language/framework inference, etc.) for the server’s current working-directory project

RouteMethodDescription
/api/project/memoryGETList all project-memory records for the caller
/api/project/memory/currentGETGet the memory record (plus adjustments) for the server’s current working-directory project
/api/project/memory/{projectKey}DELETEDelete one project-memory record

Scoped lgw_* tokens for third-party integrations that shouldn’t hold a full admin key or session cookie.

RouteMethodDescription
/api/gateway/tokensPOSTCreate a scoped gateway token (raw value is shown once and cannot be retrieved again)
/api/gateway/tokensGETList the caller’s tokens (metadata only)
/api/gateway/tokens/{id}DELETERevoke a token
/api/gateway/tokens/scopesGETList all available token scopes and their descriptions
/api/gateway/auditGETList gateway auth/scope audit events
/api/gateway/auditDELETEPurge audit events older than retentionDays
/api/gateway/analyticsGETGateway request/latency/fallback analytics by client type; ?global=true (admin) aggregates across users

RouteMethodDescription
/api/entitlements/meGETThe caller’s effective entitlements
/api/entitlements/check/{capability}GETCheck whether the caller has one named capability
/api/entitlements/workspaceGETFull capability map for the caller’s workspace
/api/entitlements/plansGETPublic catalog of plans, capabilities, and deployment mode
/api/access/meGETThe caller’s resolved workspace role and granted permissions
/api/access/checkGETCheck one permission (?permission=) for the caller
/api/admin/entitlementsGETList every user’s plan/entitlement
/api/admin/entitlements/{userId}PUTAssign a plan to a user

RouteMethodDescription
/api/licenseGETResolve the current license state for the caller
/api/licenseDELETEDeactivate a license (?userId= target, defaults to self)
/api/license/activatePOSTActivate a license key (format-validated)
/api/license/snapshotGETThe current offline license snapshot
/api/license/snapshot/refreshPOSTForce-refresh the offline snapshot
/api/license/eventsGETLicense activity audit log
/api/license/generatePOSTGenerate a local license key for testing / self-hosted activation
/api/admin/licensesGETList all active licenses across users

RouteMethodDescription
/api/admin/usersGETList all users
/api/admin/usersPOSTCreate a user, cloning the admin’s config as the default
/api/admin/users/{id}DELETEDelete a user (cannot delete self)
/api/admin/users/{id}/resetPUTForce-reset another user’s password
/api/admin/settingsGETRead admin-level settings (e.g. the registration toggle)
/api/admin/settingsPUTUpdate admin-level settings

RouteMethodDescription
/api/admin/secretsGETSecret-store status plus a list of stored secret names (no values)
/api/admin/secretsPOSTStore a named secret
/api/admin/secrets/{name}DELETEDelete a named secret
/api/guardrailsGETList guardrail policy rules
/api/guardrailsPOSTCreate a guardrail rule (warn / sanitize / reroute / block)
/api/guardrails/{id}PATCHUpdate a guardrail rule; invalidates the rule cache
/api/guardrails/{id}DELETEDelete a guardrail rule; invalidates the rule cache

RouteMethodDescription
/api/budgetsGETList budget rules with current-period spend
/api/budgetsPOSTCreate a budget rule (scope/period/limit/action validated)
/api/budgets/{id}PATCHUpdate a budget rule (owner-or-admin checked inline)
/api/budgets/{id}DELETEDelete a budget rule
/api/budgets/eventsGETList recent budget-threshold events
/api/cost/dashboardGETAggregate cost dashboard: period stats, per-provider/domain stats, top models, fallback cost impact
/api/cost/intelligenceGETDeterministic, rule-based cost-optimization recommendations
{
"workspaceId": "my-project",
"monthlyBudget": 100.00,
"weeklyAlertThreshold": 60.00,
"spentThisMonth": 34.50,
"remainingBudget": 65.50,
"projectedSpend": 98.20,
"status": "healthy"
}

RouteMethodDescription
/api/usage/recentGETRecent usage / activity feed
/api/usage/summaryGETAggregated usage summary
/api/usage/limitsGETCaller’s own usage counters and configured limits
/api/usage/limits/{userId}/{metric}GETCheck one metric for any user
/api/usage/limits/{userId}/{metric}PUTUpsert a per-user limit override
/api/usage/limits/{userId}/{metric}/resetPOSTManually reset a usage counter

RouteMethodDescription
/api/economics/trace/{traceId}GETRun or load baseline simulations for a trace; compute an efficiency score (0–100) and a deterministic cost narrative
/api/economics/profilesGETCatalog of baseline simulation profiles with descriptions
/api/economics/insightsGETFull ranked optimization-insight report
/api/economics/insights/summaryGETInsight summary string plus counts only
/api/economics/savingsGETFull multi-dimension savings-attribution report
/api/economics/savings/summaryGETTop-level savings numbers only
/api/economics/savings/providersGETSavings broken down by provider
/api/economics/savings/strategiesGETSavings broken down by strategy (category)
/api/economics/savings/monthlyGETMonthly savings trend
/api/economics/savings/fallbacksGETSavings attributed to fallback-chain use
/api/economics/savings/premiumGETPremium (above-baseline) spend / premium-avoidance savings
/api/economics/simulationsGETList stored simulation snapshots (filterable by profile)
/api/economics/simulations/aggregateGETAggregate simulation/savings stats for the caller
/api/economics/simulate/{traceId}GETSimulate all baseline profiles for one trace
/api/economics/simulate/{traceId}/{profile}GETSimulate a single named baseline profile for a trace

RouteMethodDescription
/api/evaluation/outcomesGETFull multi-dimension execution-outcome evaluation report
/api/evaluation/outcomes/summaryGETOverall outcome score (requires at least 5 traces)
/api/evaluation/outcomes/providersGETPer-provider outcome scores
/api/evaluation/outcomes/strategiesGETPer-category outcome scores
/api/evaluation/codingPOSTEvaluate a coding response’s text and persist the result
/api/evaluation/codingGETList coding evaluations, filterable by domain/grade/score/date
/api/evaluation/coding/summaryGETAggregate coding-evaluation summary over N days
/api/evaluation/coding/{traceId}GETRetrieve one stored coding evaluation
/api/evaluation/qualityGETAggregate quality/confidence score over a window
/api/evaluation/quality/trace/{traceId}GETPer-trace confidence score
/api/evaluation/benchmarksPOSTRun a benchmark harness pass over stored traces (requires at least 3 matching traces)
/api/evaluation/benchmarksGETList stored benchmark runs
/api/evaluation/benchmarks/{id}GETGet one benchmark run (ownership-checked)
/api/evaluation/benchmarks/{id}DELETEDelete a benchmark run
/api/evaluation/calibrationGETCompute (without persisting) a calibration report
/api/evaluation/calibrationPOSTCompute and persist a calibration report
/api/evaluation/calibration/latestGETLatest persisted calibration report
/api/evaluation/calibration/historyGETAlignment-score trend history
/api/evaluation/calibration/applyPOSTApply a safe recommendation (currently only invalidate-cache)

RouteMethodDescription
/api/runtime/readinessGETFull readiness report (provider probes, gateway uptime, secret/permission/environment checks); ?scope= narrows to providers/gateway/environment

Two additional routes exist purely for container/orchestrator probing and are not counted above or meant for API consumers:

  • GET /healthz — Liveness-only probe: returns uptime/pid, never touches the database or providers by design.
  • GET /readyz — Readiness probe: reports whether migrations and subsystem init have finished (the layerrReady flag).

CategoryCountPrefix
OpenAI-Compatible4/v1/
Chat & Conversations13/api/router, /api/chat, /api/conversations, /api/projects
Auth & Sessions7/api/auth
Global/User Config2/api/config
Onboarding10/api/onboarding, /api/integrations
Provider Management13/api/providers, /api/health, /api/models
Workspace Management4/api/workspace
Strategy3/api/strategy
Execution & Traces14/api/traces, /api/runtime, /api/scoring, /api/workload, /api/intelligence
Repository Intelligence1/api/repo
Project Memory3/api/project/memory
Gateway Token Management7/api/gateway
Entitlements & Access8/api/entitlements, /api/access, /api/admin/entitlements
Licensing8/api/license, /api/admin/licenses
Admin User Management6/api/admin/users, /api/admin/settings
Security & Admin7/api/admin/secrets, /api/guardrails
Budgets & Cost7/api/budgets, /api/cost
Usage & Limits6/api/usage
Economics15/api/economics
Evaluation19/api/evaluation
Health & Readiness1/api/runtime/readiness
Total158
CodeHTTP StatusDescription
UNAUTHORIZED401Invalid or missing API key
FORBIDDEN403Insufficient permissions
WORKSPACE_NOT_FOUND404Workspace does not exist
PROVIDER_UNAVAILABLE502All providers exhausted in fallback chain
RATE_LIMITED429Workspace or provider rate limit exceeded
BUDGET_EXCEEDED402Workspace has exceeded its budget
TIMEOUT504Request exceeded timeout profile
INVALID_STRATEGY400Requested strategy does not exist
GUARDRAIL_VIOLATION400Request violates content policy
CALIBRATION_PENDING503System is recalibrating, try again later

Because Layerr implements the OpenAI API specification, it is compatible with:

  • OpenAI SDK (Python/JS), point base_url to your Layerr instance
  • LangChain, use OpenAI-compatible adapter
  • Vercel AI SDK, use createOpenAI with custom endpoint
  • Continue.dev, configure as custom OpenAI-compatible provider
  • Cursor, set API base URL in settings

API documentation manually reconciled against server.ts’s actual route registrations on 2026-07-06 (158 documented routes, excluding 2 internal health probes and the SPA catch-all).