API Client
Purpose and Scope
The API Client is a centralized TypeScript client class that handles all HTTP communication between the Next.js frontend and the FastAPI backend. It provides authentication injection, workspace context management, request/response logging, and a development mock system.
For information about backend authentication and multi-tenancy, see Authentication & Multi-Tenancy. For frontend state management patterns, see State Management.
Sources: frontend/lib/api-client.ts:1-100
Architecture Overview
The API Client is implemented as a singleton class (ApiClient) that wraps the browser's native fetch API with workspace-aware authentication, standardized error handling, and a development-time mock system.
Class Structure
Sources: frontend/lib/api-client.ts:93-154
Authentication System
The API Client uses Clerk JWT tokens for authentication, which are injected into every request via the Authorization header. Workspace context is passed via the X-Workspace-ID header.
Authentication Flow
Sources: frontend/lib/api-client.ts:819-903, orchestrator/core/auth/hybrid.py (referenced)
Token Injection
The API Client requires a Clerk token getter function to be registered at app initialization:
Implementation Details:
Token fetch has a 2-second timeout to prevent hanging (frontend/lib/api-client.ts:829-840)
Falls back to
nullon timeout, logs warningRequest proceeds without auth (backend will return 401 if required)
Sources: frontend/lib/api-client.ts:156-163, frontend/lib/api-client.ts:827-841
Request Lifecycle
Every API call flows through the single request<T>() method, which handles authentication, serialization, error handling, and optional mock fallback.
Request Flow Diagram
Sources: frontend/lib/api-client.ts:819-927
Request Method Signature
Key Behaviors:
Automatic Body Serialization: Objects are JSON.stringify'd unless they are
FormData(frontend/lib/api-client.ts:844-847)Workspace Injection: Admin override takes priority over localStorage (frontend/lib/api-client.ts:855-862)
Error Detail Extraction: Attempts to parse
detailfield from error response body (frontend/lib/api-client.ts:887-895)HTTP 401 Handling: Throws user-friendly message about missing Clerk token (frontend/lib/api-client.ts:896-901)
Sources: frontend/lib/api-client.ts:819-927
Mock System
The API Client includes a comprehensive mock system for development that allows page-level or endpoint-level mock control with automatic fallback when the backend is unavailable.
Mock Configuration Hierarchy
Sources: frontend/lib/api-client.ts:238-264
Page-Level Mock Configuration
The PAGE_MOCK_CONFIG constant provides simple on/off switches per page:
Usage Pattern:
Sources: frontend/lib/api-client.ts:55-78, frontend/lib/api-client.ts:277-283
Mock Data Storage
Mock data is stored in the mockData object, keyed by endpoint path:
Dynamic Endpoint Matching:
The getMockDataForEndpoint() method supports pattern matching for dynamic paths like /api/agents/123/logs (frontend/lib/api-client.ts:769-796).
Sources: frontend/lib/api-client.ts:302-750, frontend/lib/api-client.ts:753-796
Workspace Management
The API Client implements workspace context management through the X-Workspace-ID header, with special handling for admin workspace override.
Workspace Resolution Flow
Sources: frontend/lib/api-client.ts:855-862
Admin Workspace Override
The admin workspace override is a module-level variable that takes priority over localStorage. It's used by the AdminWorkspaceSwitcher component to switch between workspaces or view platform-wide data:
Usage Example:
Backend Behavior:
When X-Workspace-ID: __all__ is sent, get_request_context_hybrid in the backend sets admin_all_workspaces=True and removes workspace filters from queries (see Data Isolation).
Sources: frontend/lib/api-client.ts:80-91, orchestrator/main.py:855-862
Configuration
The API Client is configured at instantiation through environment variables and runtime settings.
Environment Variables
NEXT_PUBLIC_API_URL
Backend API base URL
''
Build-time or runtime injection
NODE_ENV
Environment mode
'development'
Next.js
Base URL Resolution:
The base URL is resolved with multiple fallbacks to support different deployment scenarios:
Critical: If NEXT_PUBLIC_API_URL is not set, API calls will fail with 404 errors (frontend/lib/api-client.ts:106-117).
Sources: frontend/lib/api-client.ts:101-123
Default Headers
These are merged with request-specific headers and auth headers before each request (frontend/lib/api-client.ts:849-852).
Sources: frontend/lib/api-client.ts:120-122
Usage Patterns
Basic Request
Note: The body is automatically JSON.stringify'd if it's an object (frontend/lib/api-client.ts:844-847).
With Custom Headers
File Upload (FormData)
Sources: frontend/lib/api-client.ts:844-847
Page-Scoped Mock Control
Sources: frontend/lib/api-client.ts:277-283
Raw Fetch with Auth Headers
For APIs that don't use the standard request() method (e.g., skills API with raw fetch):
Sources: frontend/lib/api-client.ts:798-817
Error Handling
HTTP Error Extraction
When a request fails, the client attempts to extract detailed error messages from the response body:
Sources: frontend/lib/api-client.ts:884-903
Mock Fallback
If an API call fails and mocks are enabled for that endpoint/page, the client automatically falls back to mock data:
Mock Usage Events:
The mock-used event allows UI components to display indicators when mock data is being used (frontend/lib/api-client.ts:923-926).
Sources: frontend/lib/api-client.ts:909-927
Integration Points
Backend API Routes
The API Client communicates with FastAPI routes registered in main.py. Key router groups include:
agents_router
/api/agents
Agent CRUD and lifecycle
workflows_router
/api/workflows
Workflow execution
workflow_recipes_router
/api/workflow-recipes
Recipe management
composio_router
/api/composio
Tool integration
admin_plugins_router
/api/admin/plugins
Plugin marketplace admin
llm_analytics_router
/api/analytics/llm
Usage analytics
CORS Configuration:
The backend CORS middleware is configured to accept requests from origins listed in CORS_ALLOW_ORIGINS (orchestrator/config.py:78-79, orchestrator/main.py:433-445).
Sources: orchestrator/main.py:538-636, orchestrator/config.py:71-79
Middleware Stack
All requests pass through the backend middleware stack:
Sources: orchestrator/main.py:448-535
Development Tools
Console API (Development Only)
In development, the API Client exposes mock control via window.automatos.mocks:
Sources: frontend/lib/api-client.ts:130-141
Logging
Development mode logs are emitted for all requests:
Sources: frontend/lib/api-client.ts:825-926
Related Components
Authentication Flow: See Authentication & Multi-Tenancy for backend JWT validation
Request Context: See Workspace Management for workspace resolution logic
State Management: See State Management for React Query integration with the API Client
Credentials System: See Credentials Management for credential resolution cascade
Sources: frontend/lib/api-client.ts:1-927, orchestrator/main.py:1-869
Last updated

