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:
"timestamp" : " 2026-01-15T10:30:00Z " ,
"workspaceId" : " workspace-slug "
Error responses include:
"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:
Tier Requests/minute Burst Free 60 10 Standard 300 50 Enterprise 2000 200
These routes implement the OpenAI API specification, allowing existing clients to use Layerr as a drop-in replacement.
Route Method Description /v1/chat/completionsPOST Main chat completions endpoint (streaming and non-streaming). Accepts OpenAI-format requests, routes through Layerr intelligence /v1/embeddingsPOST Embeddings passthrough to the caller’s configured cloud provider only — there is no local-model embeddings path /v1/modelsGET List available models across all configured providers; best-effort live provider discovery is merged in /v1/models/{modelId}GET Get details for a specific model (for SDKs that require this endpoint to exist)
Request body (OpenAI-compatible with Layerr extensions):
"messages" : [{ "role" : " user " , "content" : " Write a React component " }],
Layerr extensions (all optional):
Field Type Description layerr.strategystring Override strategy: cost, speed, quality, balanced layerr.fallbackstring Fallback mode: strict, relaxed, none layerr.explainboolean Include routing explanation in response headers layerr.workspacestring Target workspace slug (for admin keys)
Route Method Description /api/routerPOST Classify a raw prompt and return a routing decision (no model call) /api/chatPOST Layerr-native chat endpoint; queues, applies backpressure/global concurrency limiting, and streams the response as newline-delimited JSON /api/conversationsGET List conversations; paginated if limit/offset given, else the legacy full list /api/conversationsPOST Create a conversation /api/conversations/{id}GET Get a specific conversation with full messages /api/conversations/{id}PUT Update a conversation (title/messages) /api/conversations/{id}DELETE Delete a conversation /api/conversations/exportGET Full export of all of the caller’s conversations, all messages included /api/conversations/{id}/projectPATCH Assign a conversation to a project /api/projectsGET List projects /api/projectsPOST Create a project (blocked once the workspace’s project_count usage limit is reached) /api/projects/{id}PUT Update a project /api/projects/{id}DELETE Delete a project; ?deleteChats=true cascades to its conversations
The Layerr-native path is split into two calls:
POST /api/router — send the raw prompt. Returns a routing decision of the shape { category, model, provider, reasoning, confidence }.
The client enriches that decision with the provider URL and a fallback pool.
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 " ,
Response (routing decision):
"model" : " claude-sonnet-4 " ,
"provider" : " anthropic-prod " ,
"reasoning" : " Code refactor on a quality-weighted workspace profile " ,
The native chat endpoint provides more control than the OpenAI-compatible route:
Request body :
"messages" : [{ "role" : " user " , "content" : " Refactor this to TypeScript " }],
"files" : [ " src/App.js " , " src/types.ts " ]
Route Method Description /api/auth/statusGET Current auth/session state, registration-enabled flag, active workspace /api/auth/loginPOST Username/password login; sets the layerr_session cookie. Rate-limited /api/auth/api-key-loginPOST Login via a layerr-api-issued API key. Rate-limited /api/auth/workspaces/refreshPOST Re-fetch linked workspaces/active workspace for a layerr-api-linked account /api/auth/registerPOST Self-service registration; 403s unless the admin has enabled registration. Rate-limited /api/auth/logoutPOST Clear the session cookie / server-side session /api/auth/passwordPUT Change 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 .
Route Method Description /api/configGET Read the effective provider config for the caller; secret keys are masked before returning /api/configPOST Save user config; validates URLs (SSRF guard), restores masked keys by identity, syncs the provider-count usage metric
Route Method Description /api/onboarding/stateGET Read resumable onboarding state /api/onboarding/statePUT Dispatch an onboarding state-machine action /api/onboarding/skipPOST Skip onboarding /api/onboarding/completePOST Mark onboarding complete (auto-derives licenseKeyPresent) /api/onboarding/resetPOST Reset onboarding state /api/onboarding/providers/detect-localPOST Probe well-known local ports (Ollama, LM Studio, etc.) for running runtimes /api/onboarding/providers/probePOST Probe an arbitrary provider URL + key (SSRF-guarded) and infer its capabilities /api/onboarding/providers/savePOST Idempotent upsert of a provider into the user’s or workspace’s local provider list /api/integrations/snippetsGET Render ready-to-paste integration code snippets (Cursor, Claude Code, etc.) with the caller’s gateway URL /api/integrations/diagnosePOST Run 4 canned probes (compatibility, streaming, tool-calling, invalid-model) against the caller’s own /v1/chat/completions
Route Method Description /api/healthGET Probe all configured providers’ connectivity plus Ollama auto-detection; includes a credential-health summary /api/modelsGET Aggregate discovered models across all configured local providers /api/models/capabilitiesGET Model capability registry lookup (single model, or a filtered list with optional benchmark data) /api/providers/healthGET Per-provider health snapshots (ring-buffer derived) plus basic connectivity /api/providers/orchestrationGET Per-provider orchestration-role statistics, idle-provider detection, deterministic recommendations /api/providers/credentials/healthGET Full credential/connection health report /api/providers/credentials/{id}/healthGET Health for one credential connection /api/providers/credentials/{id}/rotatePOST Begin or immediately complete a credential rotation /api/providers/credentials/{id}/validatePOST Probe one credential right now /api/providers/credentials/{id}/revokePOST Revoke a credential /api/providers/credentials/{id}/logGET Rotation history log for one connection /api/providers/credentials/validate-allPOST Validate every tracked connection at once /api/providers/rate-limitsGET Per-provider rate-limit configs plus live utilization telemetry
"name" : " OpenAI Production " ,
"baseUrl" : " https://api.openai.com/v1 " ,
"models" : [ " gpt-4o " , " gpt-4o-mini " , " o1-preview " ],
Named orchestration contexts and their strategy weighting — distinct from the per-user provider config under Global/User Config .
Route Method Description /api/workspace/profilesGET List all workspace profiles with their settings /api/workspace/preferencesGET Get the caller’s active-workspace preference /api/workspace/preferencesPUT Set the caller’s active-workspace preference (pin + optimization strategy) /api/workspace/activeGET Resolve the effective workspace profile (weights/thresholds) for a category
Route Method Description /api/strategy/resolveGET Resolve an execution strategy from workload signals (category, complexity, latency/cost sensitivity, etc.) /api/strategy/workspacesGET List workspaces with strategy configuration /api/strategy/workspaces/{slug}/strategiesGET List strategies for a workspace
Route Method Description /api/tracesGET List persisted orchestration traces (retention-window filtered) /api/traces/{id}GET Load and build the full replay view of one trace /api/traces/compareGET Compare two traces via query params (?a=<id>&b=<id>) /api/traces/trendsGET Trend analysis over recent traces /api/runtime/healthGET Orchestration runtime health: queue depth, concurrency, degraded-mode policy, provider saturation /api/runtime/diagnosticsGET Heap/event-loop/cache-size diagnostics snapshot /api/runtime/incidentsGET Detected incident patterns (failure spikes, saturation) summary /api/runtime/incidents/exportGET NDJSON export of incidents for log aggregators /api/runtime/error-codesGET Static LAYERR-XXXX error-code registry /api/runtime/executionsGET Live 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-previewGET Preview computed runtime scores for a category’s candidate model pool /api/workload/analyzeGET Analyze a prompt/message set into a workload profile with a signal breakdown /api/intelligenceGET Active intelligence-module flags plus 30-minute ring-buffer request statistics (categories, fallback/retry/timeout rates) /api/intelligence/adaptiveGET Adaptive-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 ).
"workspaceId" : " my-project " ,
"classification" : " coding " ,
"primaryProvider" : " anthropic-prod " ,
"primaryModel" : " claude-sonnet-4 " ,
"fallbackChain" : [ " openai-prod " , " ollama-local " ],
"finalProvider" : " anthropic-prod " ,
"summary" : " Selected Claude Sonnet for high-quality code generation " ,
"providerRationale" : " Top quality score (0.92) for coding workloads "
Route Method Description /api/repo/intelligenceGET Repository profile and snapshot (language/framework inference, etc.) for the server’s current working-directory project
Route Method Description /api/project/memoryGET List all project-memory records for the caller /api/project/memory/currentGET Get the memory record (plus adjustments) for the server’s current working-directory project /api/project/memory/{projectKey}DELETE Delete one project-memory record
Scoped lgw_* tokens for third-party integrations that shouldn’t hold a full admin key or session cookie.
Route Method Description /api/gateway/tokensPOST Create a scoped gateway token (raw value is shown once and cannot be retrieved again) /api/gateway/tokensGET List the caller’s tokens (metadata only) /api/gateway/tokens/{id}DELETE Revoke a token /api/gateway/tokens/scopesGET List all available token scopes and their descriptions /api/gateway/auditGET List gateway auth/scope audit events /api/gateway/auditDELETE Purge audit events older than retentionDays /api/gateway/analyticsGET Gateway request/latency/fallback analytics by client type; ?global=true (admin) aggregates across users
Route Method Description /api/entitlements/meGET The caller’s effective entitlements /api/entitlements/check/{capability}GET Check whether the caller has one named capability /api/entitlements/workspaceGET Full capability map for the caller’s workspace /api/entitlements/plansGET Public catalog of plans, capabilities, and deployment mode /api/access/meGET The caller’s resolved workspace role and granted permissions /api/access/checkGET Check one permission (?permission=) for the caller /api/admin/entitlementsGET List every user’s plan/entitlement /api/admin/entitlements/{userId}PUT Assign a plan to a user
Route Method Description /api/licenseGET Resolve the current license state for the caller /api/licenseDELETE Deactivate a license (?userId= target, defaults to self) /api/license/activatePOST Activate a license key (format-validated) /api/license/snapshotGET The current offline license snapshot /api/license/snapshot/refreshPOST Force-refresh the offline snapshot /api/license/eventsGET License activity audit log /api/license/generatePOST Generate a local license key for testing / self-hosted activation /api/admin/licensesGET List all active licenses across users
Route Method Description /api/admin/usersGET List all users /api/admin/usersPOST Create a user, cloning the admin’s config as the default /api/admin/users/{id}DELETE Delete a user (cannot delete self) /api/admin/users/{id}/resetPUT Force-reset another user’s password /api/admin/settingsGET Read admin-level settings (e.g. the registration toggle) /api/admin/settingsPUT Update admin-level settings
Route Method Description /api/admin/secretsGET Secret-store status plus a list of stored secret names (no values) /api/admin/secretsPOST Store a named secret /api/admin/secrets/{name}DELETE Delete a named secret /api/guardrailsGET List guardrail policy rules /api/guardrailsPOST Create a guardrail rule (warn / sanitize / reroute / block) /api/guardrails/{id}PATCH Update a guardrail rule; invalidates the rule cache /api/guardrails/{id}DELETE Delete a guardrail rule; invalidates the rule cache
Route Method Description /api/budgetsGET List budget rules with current-period spend /api/budgetsPOST Create a budget rule (scope/period/limit/action validated) /api/budgets/{id}PATCH Update a budget rule (owner-or-admin checked inline) /api/budgets/{id}DELETE Delete a budget rule /api/budgets/eventsGET List recent budget-threshold events /api/cost/dashboardGET Aggregate cost dashboard: period stats, per-provider/domain stats, top models, fallback cost impact /api/cost/intelligenceGET Deterministic, rule-based cost-optimization recommendations
"workspaceId" : " my-project " ,
"weeklyAlertThreshold" : 60.00 ,
"remainingBudget" : 65.50 ,
Route Method Description /api/usage/recentGET Recent usage / activity feed /api/usage/summaryGET Aggregated usage summary /api/usage/limitsGET Caller’s own usage counters and configured limits /api/usage/limits/{userId}/{metric}GET Check one metric for any user /api/usage/limits/{userId}/{metric}PUT Upsert a per-user limit override /api/usage/limits/{userId}/{metric}/resetPOST Manually reset a usage counter
Route Method Description /api/economics/trace/{traceId}GET Run or load baseline simulations for a trace; compute an efficiency score (0–100) and a deterministic cost narrative /api/economics/profilesGET Catalog of baseline simulation profiles with descriptions /api/economics/insightsGET Full ranked optimization-insight report /api/economics/insights/summaryGET Insight summary string plus counts only /api/economics/savingsGET Full multi-dimension savings-attribution report /api/economics/savings/summaryGET Top-level savings numbers only /api/economics/savings/providersGET Savings broken down by provider /api/economics/savings/strategiesGET Savings broken down by strategy (category) /api/economics/savings/monthlyGET Monthly savings trend /api/economics/savings/fallbacksGET Savings attributed to fallback-chain use /api/economics/savings/premiumGET Premium (above-baseline) spend / premium-avoidance savings /api/economics/simulationsGET List stored simulation snapshots (filterable by profile) /api/economics/simulations/aggregateGET Aggregate simulation/savings stats for the caller /api/economics/simulate/{traceId}GET Simulate all baseline profiles for one trace /api/economics/simulate/{traceId}/{profile}GET Simulate a single named baseline profile for a trace
Route Method Description /api/evaluation/outcomesGET Full multi-dimension execution-outcome evaluation report /api/evaluation/outcomes/summaryGET Overall outcome score (requires at least 5 traces) /api/evaluation/outcomes/providersGET Per-provider outcome scores /api/evaluation/outcomes/strategiesGET Per-category outcome scores /api/evaluation/codingPOST Evaluate a coding response’s text and persist the result /api/evaluation/codingGET List coding evaluations, filterable by domain/grade/score/date /api/evaluation/coding/summaryGET Aggregate coding-evaluation summary over N days /api/evaluation/coding/{traceId}GET Retrieve one stored coding evaluation /api/evaluation/qualityGET Aggregate quality/confidence score over a window /api/evaluation/quality/trace/{traceId}GET Per-trace confidence score /api/evaluation/benchmarksPOST Run a benchmark harness pass over stored traces (requires at least 3 matching traces) /api/evaluation/benchmarksGET List stored benchmark runs /api/evaluation/benchmarks/{id}GET Get one benchmark run (ownership-checked) /api/evaluation/benchmarks/{id}DELETE Delete a benchmark run /api/evaluation/calibrationGET Compute (without persisting) a calibration report /api/evaluation/calibrationPOST Compute and persist a calibration report /api/evaluation/calibration/latestGET Latest persisted calibration report /api/evaluation/calibration/historyGET Alignment-score trend history /api/evaluation/calibration/applyPOST Apply a safe recommendation (currently only invalidate-cache)
Route Method Description /api/runtime/readinessGET Full 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).
Category Count Prefix OpenAI-Compatible 4 /v1/Chat & Conversations 13 /api/router, /api/chat, /api/conversations, /api/projectsAuth & Sessions 7 /api/authGlobal/User Config 2 /api/configOnboarding 10 /api/onboarding, /api/integrationsProvider Management 13 /api/providers, /api/health, /api/modelsWorkspace Management 4 /api/workspaceStrategy 3 /api/strategyExecution & Traces 14 /api/traces, /api/runtime, /api/scoring, /api/workload, /api/intelligenceRepository Intelligence 1 /api/repoProject Memory 3 /api/project/memoryGateway Token Management 7 /api/gatewayEntitlements & Access 8 /api/entitlements, /api/access, /api/admin/entitlementsLicensing 8 /api/license, /api/admin/licensesAdmin User Management 6 /api/admin/users, /api/admin/settingsSecurity & Admin 7 /api/admin/secrets, /api/guardrailsBudgets & Cost 7 /api/budgets, /api/costUsage & Limits 6 /api/usageEconomics 15 /api/economicsEvaluation 19 /api/evaluationHealth & Readiness 1 /api/runtime/readinessTotal 158
Code HTTP Status Description UNAUTHORIZED401 Invalid or missing API key FORBIDDEN403 Insufficient permissions WORKSPACE_NOT_FOUND404 Workspace does not exist PROVIDER_UNAVAILABLE502 All providers exhausted in fallback chain RATE_LIMITED429 Workspace or provider rate limit exceeded BUDGET_EXCEEDED402 Workspace has exceeded its budget TIMEOUT504 Request exceeded timeout profile INVALID_STRATEGY400 Requested strategy does not exist GUARDRAIL_VIOLATION400 Request violates content policy CALIBRATION_PENDING503 System 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).