API Architecture
GAIA’s backend is built with FastAPI, a modern, high-performance Python web framework. The API follows a layered architecture with clear separation of concerns.Application Factory Pattern
The API uses the factory pattern to create and configure the FastAPI application instance.Creating the Application
- UJSONResponse: Uses ujson for faster JSON serialization
- Environment-based docs: API docs disabled in production
- Lifespan management: Handles startup/shutdown events
- Modular routing: API versioning with
/api/v1prefix
Middleware Stack
Middleware is configured in order and executes in a stack-like manner.Middleware Configuration
Available Middleware
1. WorkOS Authentication
Handles authentication using WorkOS for session management.2. Rate Limiting
Protects endpoints from abuse using SlowAPI.3. Logging Middleware
Logs all requests and responses with timing information.4. Profiling Middleware
Optional performance profiling with pyinstrument.5. CORS Configuration
Environment-based CORS origin management:Application Lifespan
Lifespan events handle startup and shutdown operations.Lifespan Context Manager
Lazy Provider System
GAIA uses a lazy provider system for optimal startup performance:Dependency Injection
FastAPI’s dependency injection system is used throughout the API.Current User Dependency
Database Session Dependency
Rate Limiting Dependency
Routing Structure
API routes are organized by feature domain:Example Router Definition
Error Handling
GAIA uses FastAPI’s exception handling system:Configuration Management
Settings are managed using Pydantic with environment variables:Best Practices
- Use dependency injection for shared logic and database access
- Implement proper error handling with meaningful HTTP status codes
- Use Pydantic models for request/response validation
- Apply rate limiting to protect endpoints
- Log important operations using structured logging
- Use background tasks for non-blocking operations
- Leverage lazy loading for optimal startup performance
- Follow RESTful conventions for endpoint design