The API Layer provides the REST and streaming interfaces for all client-server communication in the Sim platform. It implements Next.js API routes with hybrid authentication, workspace-based authorization, comprehensive request validation, and observability. This document covers authentication patterns, authorization mechanisms, request/response handling, and the organization of API endpoints.
For database schema details, see Database Schema. For real-time collaboration via WebSocket, see Real-time Collaboration System. For workflow execution APIs specifically, see Workflow Execution Engine.
The API layer is organized using Next.js file-based routing under apps/sim/app/api/. Routes follow REST conventions with HTTP verbs (GET, POST, PUT, DELETE) mapped to handler functions exported from route.ts files.
All route handlers export async functions matching HTTP verbs:
| HTTP Method | Export Name | Example Usage |
|---|---|---|
| GET | export async function GET(request: NextRequest, context) | Read operations |
| POST | export async function POST(request: NextRequest, context) | Create operations, execution triggers, billing updates |
| PUT | export async function PUT(request: NextRequest, context) | Update operations (e.g., workflow state) |
| DELETE | export async function DELETE(request: NextRequest, context) | Delete operations |
Sources: apps/sim/app/api/workflows/[id]/route.ts:28-139, apps/sim/app/api/workflows/[id]/route.ts:145-345, apps/sim/app/api/billing/update-cost/route.ts28-161 apps/sim/app/api/chat/route.ts41-60 apps/sim/app/api/chat/route.ts62-158
The API layer supports multiple authentication mechanisms unified through hybrid authentication helpers and specialized validators for deployments (Chat/Webhooks).
| Mechanism | Use Case | Implementation | Header |
|---|---|---|---|
| Session | User browser requests | Better Auth session cookies | Cookie: better-auth.session_token |
| Internal JWT | Internal service-to-service calls | JWT signed with INTERNAL_API_SECRET | Authorization: Bearer <jwt> |
| API Key | External API calls / Billing updates | Workspace-scoped or Internal keys | x-api-key: <key> |
| Deployment Auth | Public/Protected Chat/Webhooks | Password/Email/SSO cookies | Cookie: chat_auth_[id] |
Hybrid Authentication Example (apps/sim/app/api/workflows/[id]/route.ts:34-42):
Internal API Key Example (Billing) (apps/sim/app/api/billing/update-cost/route.ts48-58):
Sources: apps/sim/app/api/workflows/[id]/route.ts:34-84, apps/sim/app/api/billing/update-cost/route.ts48-58 apps/sim/app/api/chat/utils.ts86-231
Authorization is enforced at the workspace level using the permissions table and utility functions that bridge the "Natural Language Space" (e.g., "Can I delete this?") to "Code Entity Space" (e.g., authorizeWorkflowByWorkspacePermission).
| Permission Type | Capabilities |
|---|---|
read | View workflows, logs, and metadata |
write | Create workflows, edit state, execute |
admin | Full control including deletion, workspace settings |
Sources: apps/sim/app/api/workflows/[id]/route.ts:162-184, apps/sim/app/api/chat/utils.ts28-47 apps/sim/app/api/chat/utils.ts52-84
The API layer facilitates tool execution via the executeTool function and the Tools registry, handling parameter merging, credential resolution, and hosted key management.
When executing tools, the system can automatically inject hosted API keys if the user hasn't provided their own, subject to rate limits and billing.
Key Injection Implementation:
apps/sim/tools/index.ts49-137 defines injectHostedKeyIfNeeded. It first checks for Bring Your Own Key (BYOK) configurations via getBYOKKey apps/sim/tools/index.ts67-79 If unavailable, it uses the getHostedKeyRateLimiter() to acquire a key from the platform's pool apps/sim/tools/index.ts81-95
Before execution, parameters are validated against the tool's ToolConfig schema.
apps/sim/tools/utils.ts33-34 exports validateRequiredParametersAfterMerge which ensures all mandatory parameters are present after merging defaults and user inputs.
Sources: apps/sim/tools/index.ts49-137 apps/sim/tools/index.ts171-210 apps/sim/tools/index.ts144-157
Workflow Listing and Management
apps/sim/app/api/workflows/[id]/route.ts:28-139 implements GET /api/workflows/[id]:
loadWorkflowFromNormalizedTables() first apps/sim/app/api/workflows/[id]/route.ts:85.authorizeWorkflowByWorkspacePermission apps/sim/app/api/workflows/[id]/route.ts:65.Workflow Deletion
apps/sim/app/api/workflows/[id]/route.ts:145-345 implements DELETE /api/workflows/[id]:
admin action permission apps/sim/app/api/workflows/[id]/route.ts:165.performDeleteWorkflow() apps/sim/app/api/workflows/[id]/route.ts:9.Cost Tracking
apps/sim/app/api/billing/update-cost/route.ts28-161 implements POST /api/billing/update-cost:
userStats columns like total_copilot_cost and total_copilot_calls using raw SQL increments apps/sim/app/api/billing/update-cost/route.ts90-101checkAndBillOverageThreshold for incremental billing apps/sim/app/api/billing/update-cost/route.ts124apps/sim/app/api/wand/route.ts159-450 implements POST /api/wand:
wandEnrichers registry to inject context (e.g., enrichTableSchema) into the LLM prompt apps/sim/app/api/wand/route.ts76-93updateUserStatsForWand() apps/sim/app/api/wand/route.ts95-157Sources: apps/sim/app/api/workflows/[id]/route.ts:28-345, apps/sim/app/api/billing/update-cost/route.ts28-161 apps/sim/app/api/wand/route.ts159-450
All API routes use Zod for strict input validation.
Chat Deployment Schema Example: apps/sim/app/api/chat/route.ts14-39:
Webhooks require specialized request handling, including verification and challenge responses.
handleWhatsAppVerification() checks the verificationToken against stored webhook configs apps/sim/lib/webhooks/utils.server.ts30-91handleSlackChallenge() immediately returns the challenge field if present apps/sim/lib/webhooks/utils.server.ts96-102Sources: apps/sim/app/api/chat/route.ts14-39 apps/sim/lib/webhooks/utils.server.ts30-102 apps/sim/app/api/billing/update-cost/route.ts13-22
Every API request generates a unique ID via generateRequestId() for log correlation across services.
apps/sim/app/api/workflows/[id]/route.ts:29:
The ExecutionLogger and LoggingSession classes handle persistence of execution metadata, including costs and trace spans.
startWorkflowExecution() creates a state snapshot and initializes the log entry apps/sim/lib/logs/execution/logger.ts135-212onBlockStart persists the lastStartedBlock marker using buildStartedMarkerPersistenceQuery to ensure the UI shows real-time progress apps/sim/lib/logs/execution/logging-session.ts171-185completeExecutionWithFinalization aggregates total costs, tokens, and durations into the final workflow_execution_logs record apps/sim/lib/logs/execution/logging-session.ts233-255Sources: apps/sim/app/api/workflows/[id]/route.ts:29, apps/sim/lib/logs/execution/logger.ts135-212 apps/sim/lib/logs/execution/logging-session.ts171-255 apps/sim/lib/logs/execution/logging-session.ts29-47
Refresh this wiki