-
-
Notifications
You must be signed in to change notification settings - Fork 0
API System
Relevant source files from the codebase:
- CLAUDE.md
- README.md
- bin/jwt.ts
- bin/kv.ts
- bin/openapi.ts
- public/openapi.json
- server/utils/response.ts
- server/utils/schemas.ts
- test/openapi.test.ts
- test/response-sorting.test.ts
- test/response.test.ts
- test/schemas.test.ts
This document covers the comprehensive API system powering the dave.io platform, including schema-first design, authentication mechanisms, endpoint architecture, and OpenAPI specification generation. The API system provides AI-powered services, image processing, URL redirection, and system management capabilities through a standardized REST interface.
For information about the underlying platform stack and Cloudflare Workers integration, see Core Architecture. For details about JWT authentication and security measures, see Authentication & Security.
The API system is built on a schema-first approach using Zod for validation and automatic OpenAPI generation. All endpoints follow standardized patterns for requests, responses, authentication, and error handling.
graph TD
Client[Client Request] --> Endpoint[API Endpoint]
Endpoint --> Auth[Authentication Check]
Auth --> Schema[Schema Validation]
Schema --> Logic[Business Logic]
Logic --> Services[External Services]
Services --> Response[Standard Response]
Response --> Metrics[Async Metrics]
Auth --> JWT[JWT Verification]
JWT --> Permissions[Permission Check]
Schema --> Zod[Zod Schema Parse]
Zod --> Validation[Input Validation]
Services --> AI[Cloudflare AI]
Services --> Images[Cloudflare Images]
Services --> KV[KV Storage]
Services --> D1[D1 Database]
Response --> Format[Response Formatting]
Format --> JSON[Sorted JSON Output]
Metrics --> KVMetrics[KV Metrics Storage]
Sources: server/api/, server/utils/schemas.ts, bin/openapi.ts, public/openapi.json
The API system uses Zod schemas as the single source of truth for validation, TypeScript types, and OpenAPI documentation. All schemas are centralized in schemas.ts with OpenAPI metadata.
Core Schema Categories:
| Schema Category | Examples | Purpose |
|---|---|---|
| Response Schemas |
ApiSuccessResponseSchema, ApiErrorResponseSchema
|
Standardized response format |
| Auth Schemas |
JWTPayloadSchema, AuthSuccessResponseSchema
|
Authentication and authorization |
| AI Service Schemas |
AiAltTextRequestSchema, AiTicketTitleResponseSchema
|
AI-powered endpoints |
| Image Schemas |
ImageOptimisationRequestSchema, ImageOptimisationResponseSchema
|
Image processing |
| System Schemas |
HealthCheckSchema, PingResponseSchema
|
System monitoring |
Sources: server/utils/schemas.ts, bin/openapi.ts
Every API request follows a standardized validation pipeline that ensures type safety and consistent error handling.
graph LR
Request[HTTP Request] --> Extract[Extract Token]
Extract --> Verify[Verify JWT]
Verify --> Authorize[Check Permissions]
Authorize --> Parse[Parse Request Body]
Parse --> Validate[Schema Validation]
Validate --> Execute[Business Logic]
Execute --> Format[Format Response]
Format --> Log[Log Request]
Log --> Metrics[Record Metrics]
Key Functions:
-
requireAuth()- server/utils/auth-helpers.ts - Permission validation -
Schema.parse()- server/utils/schemas.ts - Input validation -
createApiResponse()- server/utils/response.ts - Response formatting -
createApiError()- server/utils/response.ts - Error handling -
recordAPIMetrics()- server/middleware/metrics.ts - Usage tracking
Sources: server/utils/response.ts, server/utils/auth.ts, server/utils/schemas.ts, test/schemas.test.ts
The API provides several categories of endpoints, each with specific authentication requirements and functionality.
| Endpoint | Method | Purpose | Schema |
|---|---|---|---|
/api/ping |
GET | System health check | PingResponseSchema |
/api/images/optimise |
GET/POST | Image optimization | ImageOptimisationRequestSchema |
/go/{slug} |
GET | URL redirection | UrlRedirectSchema |
/api/ai/tickets/* |
POST | AI ticket management | AiTicket*Schema |
| Endpoint | Method | Permission | Purpose |
|---|---|---|---|
/api/ai/alt |
GET/POST | ai:alt |
Alt-text generation |
/api/tokens/{uuid}/* |
GET/POST | api:tokens |
Token management |
/api/dashboard/* |
GET | dashboard |
Analytics data |
Sources: public/openapi.json, server/api/, server/utils/schemas.ts
The AI endpoints leverage Cloudflare AI models for content generation:
graph TD
AIRequest[AI Request] --> Type{Request Type}
Type -->|Alt-text| AltText[Alt-text Generation]
Type -->|Ticket| Ticket[Ticket Management]
AltText --> ImageInput[Image Input]
ImageInput --> Optimize[Image Optimization]
Optimize --> LLAVA[LLaVA Vision Model]
LLAVA --> AltResponse[Alt-text Response]
Ticket --> TextInput[Text/Image Input]
TextInput --> ModelSelect[Select AI Model]
ModelSelect --> Vision[Vision Model]
ModelSelect --> Text[Text Model]
Vision --> TicketResponse[Ticket Response]
Text --> TicketResponse
Sources: server/utils/schemas.ts, public/openapi.json
The API uses hierarchical JWT permissions where parent permissions grant access to child resources.
Permission Hierarchy:
graph TD
Wildcard["*"] --> Everything[All Endpoints]
API[api] --> APITokens[api:tokens]
API --> APIMetrics[api:metrics]
AI[ai] --> AIAlt[ai:alt]
AI --> AITickets[ai:tickets]
Dashboard[dashboard] --> DashStats[dashboard:stats]
Admin[admin] --> AdminAccess[Admin Functions]
-
*- Administrative access (grants everything) -
api- API access (grantsapi:tokens,api:metrics, etc.) -
ai- AI services (grantsai:alt,ai:tickets, etc.) -
dashboard- Analytics access - Specific resources like
api:tokens,ai:alt
Authentication Helpers:
| Function | Permission Required | Usage |
|---|---|---|
requireAPIAuth(event, resource?) |
api or api:resource
|
General API access |
requireAIAuth(event, resource?) |
ai or ai:resource
|
AI services |
requireDashboardAuth(event) |
dashboard |
Analytics |
requireAdminAuth(event) |
admin |
Administrative |
Sources: server/utils/auth-helpers.ts, server/utils/schemas.ts, README.md
All API responses follow a consistent structure with sorted keys for deterministic output.
Success Response Structure:
{
"error": null,
"message": "Operation successful",
"ok": true,
"result": { "data": "..." },
"status": { "message": "Operation successful" },
"timestamp": "2025-01-08T12:00:00.000Z"
}Error Response Structure:
{
"error": "Validation failed",
"message": "Validation failed",
"ok": false,
"status": { "message": "Validation failed" },
"timestamp": "2025-01-08T12:00:00.000Z"
}Key Functions:
-
createApiResponse()- server/utils/response.ts - Success responses -
createApiError()- server/utils/response.ts - Error responses -
prepareSortedApiResponse()- server/utils/json-utils.ts - Key sorting
Sources: server/utils/response.ts, server/utils/schemas.ts, test/response.test.ts, test/response-sorting.test.ts
The OpenAPI specification is automatically generated from endpoint scanning and schema analysis.
Generation Command:
bun run generate:openapigraph LR
Schemas[Zod Schemas] --> Registry[OpenAPI Registry]
Endpoints[API Endpoints] --> Scanner[Endpoint Scanner]
Scanner --> Registry
Registry --> Generator[OpenAPI Generator]
Generator --> Spec[OpenAPI Specification]
Spec --> JSON[public/openapi.json]
Key Components:
-
scanApiEndpoints()- server/utils/endpoint-scanner.ts - Discovers API files -
OpenAPIRegistry- bin/openapi.ts - Schema registration - Schema metadata - server/utils/schemas.ts -
.openapi()definitions
Sources: bin/openapi.ts, server/utils/endpoint-scanner.ts, public/openapi.json, package.json, test/openapi.test.ts
The API system includes comprehensive testing for schemas, responses, and integration scenarios.
Test Categories:
| Test Type | Files | Coverage |
|---|---|---|
| Schema Validation | test/schemas.test.ts |
Zod schema parsing and validation |
| Response Formatting | test/response.test.ts |
API response structure |
| Key Sorting | test/response-sorting.test.ts |
Deterministic output |
| OpenAPI Generation | test/openapi.test.ts |
Specification completeness |
| Authentication | test/try-auth.test.ts |
JWT token handling |
Test Commands:
bun run test # Unit tests
bun run test:api # HTTP integration tests
bun run test:ui # Interactive test runner
bun run test:all # Complete test suiteSources: test/schemas.test.ts, test/response.test.ts, test/response-sorting.test.ts, test/openapi.test.ts, test/try-auth.test.ts, package.json
Navigation:
- Previous: Data Storage & Metrics
- Next: API Design & OpenAPI
- Related: AI Services, Authentication & Security