How jujumilk3/fastapi-clean-architecture works
Project Type and Purpose
• This is a backend RESTful API service built with FastAPI following a clean‐architecture approach.
• It exposes two API versions (v1, v2) for resources: user, auth, post, tag.
• It uses SQLAlchemy models, Alembic for migrations, dependency‐injector for DI, JWT for authentication, and runs on Uvicorn in containerized environments.
High‐Level Architectural Layers
• API Layer (Interface / Delivery)
• app/main.py – Uvicorn entry point
• app/api/v1/routes.py & endpoints/… – version 1 REST routes
• app/api/v2/routes.py & endpoints/… – version 2 REST routes
• Responsibilities: HTTP request/response, versioning, dependency wiring.
• Core / Infrastructure
• app/core/config.py – environment config
• app/core/container.py – DI container (service & repo providers)
• app/core/database.py – SQLAlchemy engine & session
• app/core/middleware.py – request/response middleware
• app/core/security.py – JWT utilities, role enforcement
• Alembic (alembic.ini, migrations/) – database migrations
• Domain / Business Logic
• app/services/*.py – business rules per entity (UserService, PostService, etc.)
• app/repository/*.py – data access layer (SQLAlchemy-based repositories)
• Interaction: Services invoke repositories; repositories execute DB queries.
• Data Models and Schemas
• app/model/*.py – SQLAlchemy ORM definitions (User, Post, Tag, PostTag)
• app/schema/*.py – Pydantic schemas for request/response validation
• Utilities
• app/util/*.py – helpers for hashing, date, object conversion, query building.
• Testing
• tests/unit_tests – isolated component tests (container, fixtures)
• tests/integration_tests – end‐to‐end API tests against real DB
• tests/test_data – sample JSON payloads.
Components and Interactions
• Client (e.g., browser, mobile app, CLI) issues HTTP requests →
• Uvicorn/app.main → FastAPI router picks correct versioned route →
• Route handler pulls dependencies from DI container →
• Controller calls Service layer →
• Service applies business logic, calls Repository →
• Repository uses SQLAlchemy session to query or persist to Database →
• DB (MySQL or PostgreSQL) returns results →
• Service returns domain objects →
• Route uses Pydantic schema to serialize response →
• Client receives JSON.
• Alembic migrations manage DB schema outside runtime.
Architectural Patterns and Principles
• Clean Architecture (separation of concerns: interface, application, domain, infrastructure)
• Service‐Repository pattern (services for business logic; repositories for persistence)
• Dependency Injection (via dependency‐injector container)
• Versioned API routing (v1, v2 separation)
• JWT authentication & role-based access control as cross‐cutting concerns via middleware