# Backend Architecture

> Learn how the LearnHouse FastAPI backend is built: Python 3.14, SQLModel, Alembic, PostgreSQL with pgvector, Redis, background jobs and CLI tasks.

The LearnHouse backend is a **FastAPI** application written in Python, located at `apps/api` in the project. It is the central API layer and handles all business logic and data management.

## Technology Stack

- **FastAPI**: Python web framework
- **Python 3.14**
- **SQLModel**: ORM for database interactions (built on SQLAlchemy and Pydantic)
- **Alembic**: Database migration management
- **PostgreSQL 16** with **pgvector** extension: Primary relational database
- **redis-py**: Python Redis client
- **Uvicorn**: ASGI server
- **uv**: Python package manager

Exact versions are pinned in `apps/api/pyproject.toml` and `uv.lock`.

## Key Dependencies

- **asyncpg**, **psycopg[binary]** and **psycopg2-binary**: PostgreSQL drivers (asyncpg by default for the app or psycopg 3 with `LEARNHOUSE_DB_DRIVER=psycopg`, psycopg2 for Alembic)
- **pyjwt[crypto]**: JWT token handling
- **pwdlib[argon2]**: Password hashing with Argon2
- **pydantic-ai-slim**: Provider-agnostic AI generation (Google, OpenAI, Anthropic, Mistral, and others)
- **google-genai**: Gemini SDK, also used for image and text-to-speech generation
- **pgvector**: Vector embeddings for RAG
- **stripe**: Payment processing
- **workos**: Enterprise SSO
- **boto3**: S3-compatible storage
- **resend**: Transactional email (SMTP is also supported)
- **sentry-sdk**: Error tracking and monitoring
- **mcp**: The MCP server that lets AI apps work with an organization

## Configuration

The backend uses a dual configuration system:

- **YAML config** at `config/config.yaml` for structured settings
- **Environment variables** which override YAML values when set

The API prefix for all endpoints is `/api/v1/`. See the [environment variable reference](https://docs.learnhouse.app/self-hosting/configuration/environment-variables) for every setting.

## Command-line tasks

`apps/api/cli.py` holds maintenance commands that run against the configured database, for example `migrate` (bring the schema up to date; the API also does this on startup unless `LEARNHOUSE_AUTO_MIGRATE=false`), `install` (create the first organization and admin), `lms-import` (convert exports from another LMS), `backfill`, `index-backfill`, `transcode-backfill` and `chapters-backfill`. Run them with `uv run python cli.py <command>` from `apps/api`, or inside the app container from `/app/api`.

## Responsibilities

The backend handles all core platform operations:

- **Authentication and authorization**: JWT-based token authentication with role-based access control
- **Course management**: CRUD operations for organizations, courses, chapters, and activities
- **User management**: Registration, profiles, and permissions
- **File storage and uploads**: Handling media uploads with support for local filesystem and S3-compatible storage (via boto3)
- **AI features**: Provider-agnostic generation through Pydantic AI, and RAG over course content with pgvector
- **Search**: Content indexing and search across courses and activities
- **Payments**: Stripe integration for course monetization
- **Email**: Transactional email via Resend or SMTP
- **MCP server**: Served at `/mcp` with its own OAuth flow, so AI apps can read and change content with a member's permissions
- **Background jobs**: AI search indexing, HLS video transcoding, AI captions and scheduled backfills, run inside the API process with Redis as the queue

## Database Layer

SQLModel is used as the ORM, connecting to a PostgreSQL 16 database with the pgvector extension for AI embeddings. Database models define the schema for all entities: organizations, users, courses, chapters, activities, folders, and more. Migrations are managed with **Alembic** and applied by `cli.py migrate` or on API startup.

## Caching

Redis is used for:

- **Response caching**: Frequently accessed data is cached to reduce database load.
- **Session data**: Temporary session information is stored in Redis for fast retrieval.

## API Documentation

FastAPI automatically generates interactive API documentation, but it is only available when running in development mode.

> Swagger UI (`/docs`), ReDoc (`/redoc`) and the OpenAPI schema (`/openapi.json`) are only served when `LEARNHOUSE_DEVELOPMENT_MODE=true` is set. They are disabled in production.

## Directory Structure

```
apps/api/
├── src/
│   ├── routers/      # API route definitions
│   ├── db/           # SQLModel table definitions
│   ├── services/     # Business logic
│   ├── security/     # Authentication and authorization
│   └── core/         # Configuration and dependencies
├── migrations/       # Alembic database migrations
├── scripts/          # Standalone helper scripts
├── cli.py            # Maintenance commands
├── ee/               # Enterprise Edition features (not in community builds)
└── config/           # config.yaml defaults and the config loader
```

## Development

The backend runs on **port 1338** by default during local development (configurable via `LEARNHOUSE_PORT`). In production Docker deployments, it runs on port 9000. Install dependencies and run the server:

```bash
uv sync              # install dependencies
uv run python app.py # start the dev server (which calls uvicorn internally)
```

When using the LearnHouse CLI (`learnhouse dev`), the backend starts automatically with hot reload enabled.
