ai-voicebot/TYPESCRIPT_GENERATION.md
2025-09-01 20:34:01 -07:00

5.2 KiB

OpenAPI TypeScript Generation

This project now supports automatic TypeScript type generation from the FastAPI server's Pydantic models using OpenAPI schema generation.

Overview

The implementation follows the "OpenAPI Schema Generation (Recommended for FastAPI)" approach:

  1. Server-side: FastAPI automatically generates OpenAPI schema from Pydantic models
  2. Generation: Python script extracts the schema and saves it as JSON
  3. TypeScript: openapi-typescript converts the schema to TypeScript types
  4. Client: Typed API client provides type-safe server communication

Generated Files

  • client/openapi-schema.json - OpenAPI schema extracted from FastAPI
  • client/src/api-types.ts - TypeScript interfaces generated from OpenAPI schema
  • client/src/api-client.ts - Typed API client with convenience methods

How It Works

1. Schema Generation

The server/generate_schema_simple.py script:

  • Imports the FastAPI app from main.py
  • Extracts the OpenAPI schema using app.openapi()
  • Saves the schema as JSON in client/openapi-schema.json

2. TypeScript Generation

The openapi-typescript package:

  • Reads the OpenAPI schema JSON
  • Generates TypeScript interfaces in client/src/api-types.ts
  • Creates type-safe definitions for all Pydantic models

3. API Client

The client/src/api-client.ts file provides:

  • Type-safe API client class
  • Convenience functions for each endpoint
  • Proper error handling with custom ApiError class
  • Re-exported types for easy importing

Usage in React Components

import { apiClient, adminApi, healthApi, lobbiesApi, sessionsApi } from './api-client';
import type { LobbyModel, SessionModel, AdminSetPassword } from './api-client';

// Using the convenience APIs
const healthStatus = await healthApi.check();
const lobbies = await lobbiesApi.getAll();
const session = await sessionsApi.getCurrent();

// Using the main client
const adminNames = await apiClient.adminListNames();

// With type safety for request data
const passwordData: AdminSetPassword = {
  name: "admin",
  password: "newpassword"
};
const result = await adminApi.setPassword(passwordData);

// Type-safe lobby creation
const lobbyRequest: LobbyCreateRequest = {
  type: "lobby_create",
  data: {
    name: "My Lobby",
    private: false
  }
};
const newLobby = await sessionsApi.createLobby("session-id", lobbyRequest);

Regenerating Types

Manual Generation

# Generate schema from server
docker compose exec server uv run python3 generate_schema_simple.py

# Generate TypeScript types
docker compose exec client npx openapi-typescript openapi-schema.json -o src/api-types.ts

# Type check
docker compose exec client npm run type-check

Automated Generation

# Run the comprehensive generation script
./generate-ts-types.sh

NPM Scripts (in frontend container)

# Generate just the schema
npm run generate-schema

# Generate just the TypeScript types (requires schema to exist)
npm run generate-types

# Generate both schema and types
npm run generate-api-types

Development Workflow

  1. Modify Pydantic models in shared/models.py
  2. Regenerate types using one of the methods above
  3. Update React components to use the new types
  4. Type check to ensure everything compiles

Benefits

  • Type Safety: Full TypeScript type checking for API requests/responses
  • Auto-completion: IDE support with auto-complete for API methods and data structures
  • Error Prevention: Catch type mismatches at compile time
  • Documentation: Self-documenting API with TypeScript interfaces
  • Sync Guarantee: Types are always in sync with server models
  • Refactoring Safety: IDE can safely refactor across frontend/backend

File Structure

server/
├── main.py                    # FastAPI app with Pydantic models
├── generate_schema_simple.py  # Schema extraction script
└── generate_api_client.py     # Enhanced generator (backup)

shared/
└── models.py                  # Pydantic models (source of truth)

client/
├── openapi-schema.json        # Generated OpenAPI schema
├── package.json              # Updated with openapi-typescript dependency
└── src/
    ├── api-types.ts          # Generated TypeScript interfaces
    └── api-client.ts         # Typed API client

Troubleshooting

Container Issues

If the frontend container has dependency conflicts:

# Rebuild the frontend container
docker compose build client
docker compose up -d client

TypeScript Errors

Ensure the generated types are up to date:

./generate-ts-types.sh

Module Not Found Errors

Check that the volume mounts are working correctly and files are synced between host and container.

API Evolution Detection

The system now includes automatic detection of API changes:

  • Automatic Checking: In development mode, the system automatically warns about unimplemented endpoints
  • Console Warnings: Clear warnings appear in the browser console when new API endpoints are available
  • Implementation Stubs: Provides ready-to-use code stubs for new endpoints
  • Schema Monitoring: Detects when the OpenAPI schema changes

See client/src/API_EVOLUTION.md for detailed documentation on using this feature.