Skip to content

API System

Dave Williams edited this page Jun 16, 2025 · 1 revision

API System

Relevant source files from the codebase:

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.

Overall Architecture

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]
Loading

Sources: server/api/, server/utils/schemas.ts, bin/openapi.ts, public/openapi.json

Schema-First Design

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

Request Validation Flow

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]
Loading

Key Functions:

Sources: server/utils/response.ts, server/utils/auth.ts, server/utils/schemas.ts, test/schemas.test.ts

Core API Endpoints

The API provides several categories of endpoints, each with specific authentication requirements and functionality.

Public Endpoints

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

Protected Endpoints

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

AI Services

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
Loading

Sources: server/utils/schemas.ts, public/openapi.json

Authentication Integration

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]
Loading
  • * - Administrative access (grants everything)
  • api - API access (grants api:tokens, api:metrics, etc.)
  • ai - AI services (grants ai: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

Response Standardization

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:

Sources: server/utils/response.ts, server/utils/schemas.ts, test/response.test.ts, test/response-sorting.test.ts

OpenAPI Specification Generation

The OpenAPI specification is automatically generated from endpoint scanning and schema analysis.

Generation Command:

bun run generate:openapi
graph 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]
Loading

Key Components:

Sources: bin/openapi.ts, server/utils/endpoint-scanner.ts, public/openapi.json, package.json, test/openapi.test.ts

Testing and Validation

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 suite

Sources: 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:

Clone this wiki locally