# teamhide/fastapi-boilerplate architecture

> Architecture diagram of the GitHub repository teamhide/fastapi-boilerplate, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-23). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/teamhide/fastapi-boilerplate
- Repository: https://github.com/teamhide/fastapi-boilerplate

## Overview

##### Project Type and Purpose
- This is a backend microservice/API boilerplate built with FastAPI, designed around Domain-Driven Design (DDD) and Hexagonal (Ports & Adapters) architecture.
- Its primary responsibilities are user management (CRUD, DTOs, validation) and JWT-based authentication, plus background tasks via Celery, caching via Redis, and asynchronous database access via SQLAlchemy.

##### File Structure Analysis
- Top-level directories:
- app/ – contains bounded contexts “auth” and “user,” each broken into adapter (input/output), application, domain, and a container for DI.
- core/ – shared libraries: configuration, async DB session management, exceptions, FastAPI middlewares/dependencies, cache abstractions, repository base.
- celery_task/ – standalone module for asynchronous background jobs.
- migrations/ & alembic.ini – database schema versioning.
- docker/ – Docker Compose setup plus initial SQL.
- main.py & app/server.py – entrypoints to wire FastAPI, DI container, cache, event dispatcher.
- tests/ – coverage for all layers.

##### README Insights
- Confirms stack: FastAPI + async SQLAlchemy sessions, JWT auth, permission dependencies, Celery workers, event dispatcher, caching with configurable backends.
- Deployment: Docker Compose, Alembic migrations, Poetry, pre-commit formatting.

a. Presentation Layer
- FastAPI HTTP Server (main.py → app/server.py)
- Routers: /api/v1/auth and /api/v1/user
b. Adapter Layer (API)
- Input adapters: Pydantic request/response schemas and controllers in app/*/adapter/input/api/v1
- Output adapters: Persistence adapters (SQLAlchemy + generic repository adapters)
c. Application Layer
- Services (application/service/*.py) orchestrating use cases
- DTOs and exception handling
d. Domain Layer
- Entities (User, JWT claims)
- Value Objects (e.g., Location)
- UseCase interfaces and business rules
e. Infrastructure Layer
- Async SQLAlchemy session factory, Transactional decorator
- Cache manager and backends (Redis)
- Celery worker & tasks
- Event dispatcher
- Configuration loader, Docker deploy
f. External Systems
- PostgreSQL (or other RDBMS)
- Redis
- Celery Broker (e.g., RabbitMQ/Redis)

##### Interactions and Data Flows
- Client → FastAPI HTTP Server → Authentication Middleware (JWT decoding & permission check) → Router → Input Adapter → Application Service → Domain UseCase → Repository Port → Output Adapter → Async SQLAlchemy → Database
- Application Service may dispatch domain events to the event dispatcher → Celery tasks
- Caching decorator intercepts service calls → Redis GET/SET → return cached data or fallback to underlying DB call
- Alembic manages schema migrations on startup
- Docker Compose brings up DB, Redis, and Celery broker/workers

##### Architectural Patterns and Principles
- Hexagonal Architecture (Ports & Adapters): clear separation of inbound adapters (API) and outbound adapters (DB, cache).
- Layered DDD: Domain layer is pure business logic; Application layer orchestrates; Adapters handle I/O.
- Dependency Injection via container.py in each module.
- Asynchronous I/O across web, DB, and cache.
- Transactional decorator to manage commit/rollback automatically.

##### Essential Elements to Capture
- All FastAPI routers and middlewares (authentication, logging, SQLAlchemy injection).
- DI Container initialization and binding of services to adapters.
- Data transformations: DTOs ↔ Entities.
- Event dispatch: from application layer to Celery tasks.
- Caching: decorator intercept, key maker, backend flow.
- Database transactions: session_factory vs. global session.

## Diagram (Mermaid)

```mermaid
flowchart TB
    %% FastAPI Container
    subgraph "FastAPI Container"
        direction TB
        MainEntrypoint["main.py"]:::presentation
        ServerEntrypoint["app/server.py"]:::presentation
        AuthRouter["AuthRouter"]:::presentation
        UserRouter["UserRouter"]:::presentation
        AuthController["AuthController"]:::presentation
        UserController["UserController"]:::presentation
        AuthInputSchemas["Auth Pydantic Schemas"]:::presentation
        UserInputSchemas["User Pydantic Schemas"]:::presentation
    end

    %% Auth Context
    subgraph "Auth Context"
        direction TB
        AuthService["AuthService (application)"]:::application
        AuthAppDTOs["Auth DTOs"]:::application
        AuthAppExceptions["Auth Exceptions"]:::application
        AuthEntity["Auth Entities"]:::domain
        AuthUseCase["JWT UseCase Interface"]:::domain
    end

    %% User Context
    subgraph "User Context"
        direction TB
        UserService["UserService (application)"]:::application
        UserAppDTOs["User DTOs"]:::application
        UserAppExceptions["User Exceptions"]:::application
        UserEntity["User Entity"]:::domain
        UserVO["Location VO"]:::domain
        UserUseCase["User UseCase Interface"]:::domain
        UserRepoAdapter["UserRepositoryAdapter"]:::infra
        SQLAlchemyUser["SQLAlchemy User Model"]:::infra
    end

    %% Infrastructure
    subgraph "Infrastructure"
        direction TB
        AppContainer["app/container.py"]:::infra
        UserContainer["app/user/container.py"]:::infra
        DBSession["Async DB Session"]:::infra
        Transactional["Transactional Decorator"]:::infra
        CacheManager["Cache Manager"]:::infra
        RedisBackend["Redis Backend"]:::infra
        BaseBackend["Base Backend"]:::infra
        KeyMaker["Key Maker"]:::infra
        CustomKeyMaker["Custom Key Maker"]:::infra
        MiddlewareAuth["Auth Middleware"]:::infra
        MiddlewareDB["DB Middleware"]:::infra
        PermissionDep["Permission Dependency"]:::infra
        LoggingDep["Logging Dependency"]:::infra
        ConfigLoader["Configuration Loader"]:::infra
        AlembicIni["alembic.ini"]:::infra
        MigrationsDir["migrations/"]:::infra
        DockerCompose["docker-compose.yml"]:::infra
        InitSQL["init.sql"]:::infra
    end

    %% Celery
    CeleryWorker["Celery Worker & Tasks"]:::infra

    %% External Systems
    PostgreSQL["PostgreSQL"]:::external
    RedisExt["Redis"]:::external
    Broker["Message Broker"]:::external

    %% Connections
    MainEntrypoint -->|imports| ServerEntrypoint
    ServerEntrypoint -->|includes routers| AuthRouter
    ServerEntrypoint -->|includes routers| UserRouter

    AuthRouter -->|HTTP request| AuthController
    UserRouter -->|HTTP request| UserController

    AuthController -->|validates| AuthInputSchemas
    UserController -->|validates| UserInputSchemas

    AuthController -->|calls| AuthService
    UserController -->|calls| UserService

    AuthService -->|uses DTOs| AuthAppDTOs
    AuthService -->|handles exceptions| AuthAppExceptions
    AuthService -->|invokes| AuthUseCase

    UserService -->|uses DTOs| UserAppDTOs
    UserService -->|handles exceptions| UserAppExceptions
    UserService -->|invokes| UserUseCase

    AuthUseCase -->|manages| AuthEntity
    UserUseCase -->|manages| UserEntity
    UserUseCase -->|uses VO| UserVO

    UserUseCase -->|requires| UserRepoAdapter
    UserRepoAdapter -->|SQLAlchemy| SQLAlchemyUser
    SQLAlchemyUser -->|DB session| DBSession

    DBSession -->|transaction| Transactional
    Transactional -->|manages commit/rollback| SQLAlchemyUser

    AuthService -->|caches| CacheManager
    UserService -->|caches| CacheManager
    CacheManager -->|backend| RedisBackend
    RedisBackend -->|implements| BaseBackend
    CacheManager -->|uses| KeyMaker
    CacheManager -->|uses| CustomKeyMaker

    ServerEntrypoint -->|injects| AppContainer
    ServerEntrypoint -->|injects| UserContainer

    ServerEntrypoint -->|middleware| MiddlewareAuth
    ServerEntrypoint -->|middleware| MiddlewareDB
    ServerEntrypoint -->|dependency| PermissionDep
    ServerEntrypoint -->|dependency| LoggingDep

    ServerEntrypoint -->|loads config| ConfigLoader

    ServerEntrypoint -->|runs migrations| AlembicIni
    AlembicIni -->|dir| MigrationsDir

    DockerCompose -->|deploys| PostgreSQL
    DockerCompose -->|deploys| RedisExt
    DockerCompose -->|deploys| Broker
    DockerCompose -->|initial SQL| InitSQL
    DockerCompose -->|starts| ServerEntrypoint
    DockerCompose -->|starts| CeleryWorker

    AuthService -->|dispatch| CeleryWorker

    %% Click Events
    click MainEntrypoint "https://github.com/teamhide/fastapi-boilerplate/blob/master/main.py"
    click ServerEntrypoint "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/server.py"
    click AuthRouter "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/auth/adapter/input/api/v1/auth.py"
    click UserRouter "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/user/adapter/input/api/v1/user.py"
    click AuthInputSchemas "https://github.com/teamhide/fastapi-boilerplate/tree/master/app/auth/adapter/input/api/v1/request/"
    click AuthInputSchemas "https://github.com/teamhide/fastapi-boilerplate/tree/master/app/auth/adapter/input/api/v1/response/"
    click UserInputSchemas "https://github.com/teamhide/fastapi-boilerplate/tree/master/app/user/adapter/input/api/v1/request/"
    click UserInputSchemas "https://github.com/teamhide/fastapi-boilerplate/tree/master/app/user/adapter/input/api/v1/response/"
    click UserRepoAdapter "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/user/adapter/output/persistence/repository_adapter.py"
    click SQLAlchemyUser "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/user/adapter/output/persistence/sqlalchemy/user.py"
    click AuthService "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/auth/application/service/jwt.py"
    click UserService "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/user/application/service/user.py"
    click AuthAppDTOs "https://github.com/teamhide/fastapi-boilerplate/tree/master/app/auth/application/dto/"
    click AuthAppExceptions "https://github.com/teamhide/fastapi-boilerplate/tree/master/app/auth/application/exception/"
    click UserAppDTOs "https://github.com/teamhide/fastapi-boilerplate/tree/master/app/user/application/dto/"
    click UserAppExceptions "https://github.com/teamhide/fastapi-boilerplate/tree/master/app/user/application/exception/"
    click AuthEntity "https://github.com/teamhide/fastapi-boilerplate/tree/master/app/auth/domain/entity/"
    click UserEntity "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/user/domain/entity/user.py"
    click UserVO "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/user/domain/vo/location.py"
    click AuthUseCase "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/auth/domain/usecase/jwt.py"
    click UserUseCase "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/user/domain/usecase/user.py"
    click AppContainer "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/container.py"
    click UserContainer "https://github.com/teamhide/fastapi-boilerplate/blob/master/app/user/container.py"
    click DBSession "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/db/session.py"
    click Transactional "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/db/transactional.py"
    click CacheManager "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/helpers/cache/cache_manager.py"
    click RedisBackend "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/helpers/cache/redis_backend.py"
    click BaseBackend "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/helpers/cache/base/backend.py"
    click KeyMaker "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/helpers/cache/base/key_maker.py"
    click CustomKeyMaker "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/helpers/cache/custom_key_maker.py"
    click MiddlewareAuth "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/fastapi/middlewares/authentication.py"
    click MiddlewareDB "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/fastapi/middlewares/sqlalchemy.py"
    click PermissionDep "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/fastapi/dependencies/permission.py"
    click LoggingDep "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/fastapi/dependencies/logging.py"
    click ConfigLoader "https://github.com/teamhide/fastapi-boilerplate/blob/master/core/config.py"
    click CeleryWorker "https://github.com/teamhide/fastapi-boilerplate/tree/master/celery_task/tasks/"
    click AlembicIni "https://github.com/teamhide/fastapi-boilerplate/blob/master/alembic.ini"
    click MigrationsDir "https://github.com/teamhide/fastapi-boilerplate/tree/master/migrations/"
    click DockerCompose "https://github.com/teamhide/fastapi-boilerplate/blob/master/docker/docker-compose.yml"
    click InitSQL "https://github.com/teamhide/fastapi-boilerplate/blob/master/docker/init.sql"

    %% Styles
    classDef presentation fill:#D0E6FF,stroke:#0366D6,color:#0366D6;
    classDef application fill:#E6FFEA,stroke:#28A745,color:#28A745;
    classDef domain fill:#E8F0FE,stroke:#1A73E8,color:#1A73E8;
    classDef infra fill:#FFEFD5,stroke:#D2691E,color:#D2691E;
    classDef external fill:#F5F5F5,stroke:#999999,color:#555555;
```
