Lumitech Python FastAPI Template
Welcome to the Lumitech Python FastAPI Template. This template offers a solid foundation for building back-end applications with Python and FastAPI, featuring SQLAlchemy ORM, Redis, OpenAPI documentation, and a ready-to-use Docker setup. Designed with best practices in mind, it ensures maintainability, scalability, and reliability, making development efficient and production-ready.
Lumitech is a custom software development company providing professional services worldwide. We partner with technology businesses globally helping them to build successful engineering teams and create innovative software products. We're a global team of software engineers, AI and ML specialists, product managers, and technology experts who have achieved a 600% growth rate since 2022. When a rocket launches toward the moon, it doesn't stop halfway. Neither do we.
- Python - programming language;
- FastAPI - web framework;
- Pydantic - data validation and serialization;
- OpenAPI - API documentation;
- PostgreSQL - relational database;
- SQLAlchemy - database ORM;
- Alembic - database migration tool;
- Redis - caching;
- Docker - containerization;
- UV - package and project manager;
- Pre-commit - managing and maintaining pre-commit hooks.
- Navigate to the project directory via
cd <project_name>
; - Copy .env.example to .env file via
cp .env.example .env
; - Fill environment variables listed in .env with relevant values;
- Create docker network via
docker network create <network_name>
; - Run the project via
docker compose -f prod.docker-compose.yml up
.
NOTE: use -d
flag to run containers in the background.
- Navigate to the project directory via
cd <project_name>
; - Copy .env.example to .env file via
cp .env.example .env
; - Fill environment variables listed in .env with relevant values;
- Create docker network via
docker network create <project_name>-network
; - Run the project via
docker compose -f dev.docker-compose.yml up
.
NOTE: use -d
flag to run containers in the background.
- Install uv if needed via
curl -LsSf https://astral.sh/uv/install.sh | sh
; - Navigate to the project directory via
cd <project_name>
; - Create a virtual environment via
uv venv
; - Activate the virtual environment via
source .venv/bin/activate
; - Install the project's dependencies via
uv sync
; - Initialize pre-commit environment and install pre-commit hooks via
pre-commit install
; - Copy .env.example to .env file via
cp .env.example .env
; - Fill environment variables listed in .env with relevant values;
- Run the project via
docker compose -f local.docker-compose.yml up
.
NOTE: use -d
flag to run containers in the background.
The project uses Alembic for database migrations. Migrations are automatically applied when the container starts, as configured in the entrypoint.sh file.
To create a new migration manually:
- Make changes to your SQLAlchemy models;
- Run
docker compose exec --user root fastapi alembic revision --autogenerate -m "<message>"
; - Review the generated migration file in app/database/migrations/versions/;
- Apply the migration with
docker compose exec --user root fastapi alembic upgrade head
.
NOTE: to downgrade the migration run docker compose exec --user root fastapi alembic downgrade -1
.
This template implements the Repository pattern to abstract database operations. The BaseRepository
class provides a set of common CRUD operations that can be extended for specific entities. Using a repository layer centralizes all database interactions, eliminates code duplication, and simplifies the integration of new entities. It enforces a clear contract for data access, isolates persistence logic from the rest of the application, and facilitates unit testing by enabling database operations to be easily mocked.
# Create a repository for a specific model.
class UserRepository(BaseRepository[User, UserCreate, UserUpdate]):
pass
user_repository = UserRepository(User)
# Fetch a user by ID.
user = await user_repository.fetch_one(id=user_id, session=session)
# Create a new user.
new_user = await user_repository.create(user_data, session)
The template uses a Manager pattern to implement business logic. The BaseManager
class works with repositories and adds error handling and validation. The manager layer separates business logic from database access and the presentation layer, resulting in a modular and maintainable architecture. It allows business rules to evolve independently of storage concerns, promotes reuse of logic across different operations, and improves overall scalability by clearly defining application service boundaries.
# Create a manager for a specific model.
class UserManager(BaseManager[User, UserCreate, UserUpdate]):
pass
user_manager = UserManager(User, UserRepository)
# Fetch a user by ID (with error handling).
try:
user = await user_manager.fetch_one(id=user_id, session=session)
except HTTPNotFoundException:
# Handle not found case.
# Create a new user.
new_user = await user_manager.create(user_data, session)
This template provides Docker configuration for three different environments:
- Local Development - Uses local.docker-compose.yml and local.Dockerfile with hot-reloading and direct port access for fastest development.
- Development with Proxy - Uses dev.docker-compose.yml and dev.Dockerfile with hot-reloading, Traefik proxy, SSL certificates, and domain routing.
- Production - Uses prod.docker-compose.yml and prod.Dockerfile optimized for production use.
The Docker setup includes:
- FastAPI application;
- PostgreSQL database;
- Redis for caching;
- Traefik application proxy (dev/prod environments);
The template includes OpenAPI documentation. When running the application, you can access the API documentation at:
- Swagger UI:
/docs
; - ReDoc:
/redoc
.
Follows commit message conventions to maintain a clean and consistent commit history:
feat
: a new feature.fix
: a bug fix.chore
: a routine task, maintenance.refactor
: a refactoring or for a code change that neither fixes a bug nor adds a feature.perf
: a code change that improves performance.test
: for adding or modifying tests.build
: for changes that affect the build system or external dependencies.ci
: for changes related to CI/CD and scripts.docs
: for documentation changes.style
: for code style changes.
Each commit message has the following format:
<type>(<?scope>): <description>
[optional body]
[optional footer]
The project is organized into several parts to promote a modular design, clean architecture, and separation of concerns:
app/database
:
This directory handles data persistence and interaction with the database.
engine.py
: sets up the SQLAlchemy engine and session for database operations;models.py
: defines the SQLAlchemy ORM models that represent database tables;migrations/
: houses Alembic configuration and migration scripts to manage database schema changes.
app/repository
:
Implements the data access layer following the Repository Pattern.
base.py
: defines generic CRUD operations to be extended by specific repositories;user.py
: implements user-specific data queries and operations.
app/manager
:
Encapsulates the business logic layer using the Manager Pattern.
base.py
: provides a base manager with common logic used across different managers;user.py
: contains user-specific business logic, orchestrating operations across repositories and utilities.
app/routes
:
Defines the API endpoints for the application using FastAPI.
user.py
: routes related to user management;misc.py
: routes for miscellaneous endpoints;dependencies.py
: Defines reusable FastAPI dependencies (e.g., database session injection).
app/schemas
:
Manages input and output validation using Pydantic models.
user.py
: defines request and response schemas for user-related endpoints.
app/exceptions
:
Centralizes error handling and custom exceptions.
database.py
: database-related custom exception classes;http.py
: custom HTTP exceptions;handlers.py
: FastAPI exception handlers that map exceptions to API responses.
app/utils
:
Provides utility functions, helpers, and abstractions for cross-cutting concerns.
cache.py
: Redis client setup for caching and session management;constants.py
: application-wide constants;misc.py
: general-purpose helper functions;mixins.py
: mixin classes for extending Pydantic models;pagination.py
: utilities for pagination handling;secrets.py
: secret management utilities (e.g., API keys, credentials);tokens.py
: JWT token generation and validation;types.py
: shared type hints and definitions.
app/settings.py
:
Handles application configuration (e.g., environment variables, settings management).
app/main.py
:
The FastAPI application instance setup, including routers registration and startup events.
Project root:
local.Dockerfile
/dev.Dockerfile
/prod.Dockerfile
: separate Dockerfiles for local development, development with proxy, and production environments;local.docker-compose.yml
/dev.docker-compose.yml
/prod.docker-compose.yml
: Docker Compose configurations for spinning up different environments;pyproject.toml
: project dependencies and configuration using the UV package manager;uv.lock
: lockfile for exact dependency versions;entrypoint.sh
: entrypoint script used when the application runs inside a Docker container;README.md
: overview and documentation for setting up and running the project.
.
βββ README.md
βββ app
β βββ __init__.py
β βββ alembic.ini
β βββ database
β β βββ __init__.py
β β βββ base.py
β β βββ engine.py
β β βββ migrations
β β β βββ env.py
β β β βββ script.py.mako
β β β βββ versions
β β β βββ ...
β β βββ models.py
β βββ entrypoint.sh
β βββ exceptions
β β βββ __init__.py
β β βββ database.py
β β βββ handlers.py
β β βββ http.py
β βββ main.py
β βββ manager
β β βββ __init__.py
β β βββ base.py
β β βββ user.py
β βββ repository
β β βββ __init__.py
β β βββ base.py
β β βββ user.py
β βββ routes
β β βββ __init__.py
β β βββ dependencies.py
β β βββ misc.py
β β βββ user.py
β βββ schemas
β β βββ __init__.py
β β βββ base.py
β β βββ user.py
β βββ settings.py
β βββ utils
β βββ __init__.py
β βββ cache.py
β βββ constants.py
β βββ misc.py
β βββ mixins.py
β βββ pagination.py
β βββ secrets.py
β βββ tokens.py
β βββ types.py
βββ dev.Dockerfile
βββ dev.docker-compose.yml
βββ local.Dockerfile
βββ local.docker-compose.yml
βββ prod.Dockerfile
βββ prod.docker-compose.yml
βββ pyproject.toml
βββ uv.lock