FastAPI template built with modern Python async patterns.
This preset provides a solid foundation for building scalable web applications with JWT authentication, database migrations, and clean architecture.
This FastAPI Preset is a comprehensive template designed to kickstart your web application development with a proven, well-structured foundation. It demonstrates modern backend development practices including asynchronous programming, JWT-based authentication, database migrations with Alembic, and a clean layered architecture.
Database Flexibility: The project supports both SQLite for quick development and testing, and PostgreSQL for production environments.The database setup involves a few simple steps:
-
Configure your .env file with database connection details
-
Set up the database engine in database.py
-
Configure Alembic for migrations in alembic.ini
All configurations are clearly documented and easy to modify for your specific needs.
Purpose & Scope: This preset is perfect for developers of all levels who want to rapidly start their FastAPI projects without spending time on boilerplate setup.This template provides everything you need. It includes essential features like user registration/login, item management with ownership validation, and database migrations - giving you a solid starting point for any web application.
Note on Development: This is an actively maintained preset designed to be simple and understandable for everyone. The current version includes core authentication and CRUD operations with clean, well-documented code that's easy to follow. Future updates will focus on making the preset even more beginner-friendly while adding practical features that are useful for real projects. The goal is to create a template that's both educational for learning and practical for building real applications.
-
Clean Architecture
-
Repository pattern for business logic
-
DAO (Data Access Object) layer for database operations
-
Request Context for dependency management
-
Generic Response Schemas with type safety
-
-
π Data Validation System (Early Development)
ValidationServicefor centralized data integrity checks- Global uniqueness validation (prevent duplicates across database)
- Per-user uniqueness validation (prevent duplicates within user's records)
- Early error detection (validation before database commit)
- Extensible rule-based configuration
-
Modern Response Handling
- Generic
DataResponse[T]for single object endpoints - Generic
ListResponse[T]for collection endpoints - Type-safe response schemas with Pydantic
- Consistent API response structure
- Generic
-
User Authentication
- User registration with email and username validation
- JWT-based login with secure password hashing
- Token-based session management with cookies
- Protected routes with user context
-
Item Management
- Create, read, and delete items
- Ownership-based item operations
- Prevent duplicate item names per user
- Public and user-specific item views
-
Database Support
- PostgreSQL (recommended for production)
- SQLite (for development and testing)
- Async database operations with SQLAlchemy 2.0
- Alembic database migrations
-
Security
- BCrypt password hashing
- JWT token validation with expiration
- CORS middleware configuration
- Input validation with Pydantic schemas
-
API Documentation
- Automatic Swagger UI at
/docs - OpenAPI schema generation
- Detailed endpoint descriptions
- Automatic Swagger UI at
FastAPIPreset/
βββ .venv/ # Python virtual environment
βββ context/ # Context dataclasses
β βββ request_context.py # Request context
βββ DAO/ # Data Access Object layer
β βββ general_dao.py # Common database operations
β βββ item_dao.py # Item-specific database operations
β βββ user_dao.py # User-specific database operations
βββ database/ # Database configuration and models
β βββ database.py # Database engine and session setup
β βββ models.py # SQLAlchemy data models
β βββ response_schemas.py # Generic Pydantic schemas for API responses
β βββ schema.py # Pydantic schemas for validation
βββ helpers/ # Utility functions and helpers
β βββ general_helper.py # HTTP error handling utilities
β βββ jwt_helper.py # JWT token creation
β βββ password_helper.py # Password hashing and verification
β βββ token_helper.py # Token extraction and validation
β βββ user_helper.py # User authentication logic
βββ services/ # Business logic and validation services
β βββ validation_services.py # Data validation and uniqueness checks
β βββ item_services.py # Item-related business logic
β βββ user_services.py # User-related business logic
βββ repository/ # Business logic layer
β βββ item_repository.py # Item business logic
β βββ user_repository.py # User business logic
βββ routes/ # API route definitions
β βββ item_router.py # Item-related endpoints
β βββ user_router.py # User-related endpoints
βββ migrations/ # Alembic database migrations
β βββ versions/ # Migration scripts
β βββ env.py # Alembic environment configuration
β βββ script.py.mako # Migration template
βββ .env # Environment variables
βββ alembic.ini # Alembic configuration
βββ config.py # Application settings
βββ main.py # FastAPI application entry point
βββ requirements.txt # Python dependencies
βββ test_postgres.py # PostgreSQL connection tester
βββ README.md # This file
- Python 3.11+ (recommended: 3.11 or higher)
- PostgreSQL (for production) or SQLite (for development)
- pip (Python package manager)
-
Clone or download the preset:
# If using git git clone <your-repository-url> cd FastAPIPreset # Or simply download and extract the preset files
-
Set up the virtual environment:
python -m venv .venv # Activate the virtual environment: # Windows: .venv\Scripts\Activate # macOS/Linux: source .venv/bin/activate
-
Install dependencies:
pip install -r requirements.txt
Update your .env file for SQLite:
DB_LITE="sqlite+aiosqlite:///fastapi_preset.db"
DB_LITE_FOR_ALEMBIC="sqlite:///fastapi_preset.db"-
Install PostgreSQL:
- Windows: Download from PostgreSQL Official Site
- macOS:
brew install postgresql - Linux (Ubuntu):
sudo apt install postgresql postgresql-contrib
-
Start PostgreSQL service:
- Windows: Start from Services or use pgAdmin
- macOS:
brew services start postgresql - Linux:
sudo systemctl start postgresql
-
Create database:
psql -U postgres -c "CREATE DATABASE fastapi_preset;" -
Test PostgreSQL connection:
python test_postgres.py
- Create a
.envfile in the root directory:
# Database Configuration
# Choose either SQLite or PostgreSQL:
# SQLite (Development)
DB_LITE="sqlite+aiosqlite:///fastapi_preset.db"
DB_LITE_FOR_ALEMBIC="sqlite:///fastapi_preset.db"
# PostgreSQL (Production)
DB_HOST=localhost
DB_PORT=5432
DB_NAME=fastapi_preset
DB_USER=your_postgres_username
DB_PASSWORD=your_postgres_password
DATABASE_URL_POSTGRE="postgresql+asyncpg://your_username:your_password@localhost:5432/fastapi_preset"
DATABASE_URL_ALEMBIC_POSTGRE="postgresql://your_username:your_password@localhost:5432/fastapi_preset"
# JWT Authentication
SECRET_KEY=your_very_secure_secret_key_here
ALGORITHM=HS256- Generate a secure SECRET_KEY:
# Using Node.js (if you have it installed): node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" # Or using Python: python -c "import secrets; print(secrets.token_hex(32))"
-
Configure Alembic in
alembic.ini:sqlalchemy.url = postgresql://your_username:your_password@localhost:5432/fastapi_preset # OR for SQLite: # sqlalchemy.url = sqlite:///fastapi_preset.db
-
Run migrations:
# Create initial migration (if needed) alembic revision --autogenerate -m "Initial migration" # Apply migrations alembic upgrade head
-
Common Alembic commands:
# Create new migration alembic revision --autogenerate -m "Description of changes" # Apply all pending migrations alembic upgrade head # Rollback last migration alembic downgrade -1 # Check current migration status alembic current # Show migration history alembic history --verbose
-
Start the FastAPI server:
uvicorn main:app --reload
-
Access the application:
- API Server: http://127.0.0.1:8000
- Interactive Documentation: http://127.0.0.1:8000/docs
- Alternative Documentation: http://127.0.0.1:8000/redoc
π‘ Note: API Testing Tools Recommendation
For testing API endpoints, I recommend using specialized tools:-
Yaak - Modern, intuitive interface with excellent user experience
-
Clean, distraction-free design
-
Easy request organization
-
Great for beginners
-
-
Postman - Industry standard with extensive features
-
Comprehensive testing capabilities
-
Environment variables and collections
-
Team collaboration features
-
Why use these tools?
-
Better than browser testing: Proper handling of different HTTP methods
-
Header management: Easy JWT token and authentication header setup
-
Request organization: Save and organize your API calls
-
Environment variables: Manage different configurations (local/dev/prod)
-
Response inspection: Detailed view of headers, status codes, and response bodies
Personal Recommendation: Try Yaak first - it's lightweight, clean interface makes API testing much more enjoyable, especially when learning FastAPI!
And it's kinda pretty, lol

POST /api/v1/users/sign_up- User registrationPOST /api/v1/users/sign_in- User login (returns JWT token in cookie)POST /api/v1/users/logout- User logout (clears authentication cookie)
GET /api/v1/users/- Get all users (public)GET /api/v1/users/user/{user_id}- Get user profile by ID (public)GET /api/v1/users/me/- Get current authenticated user's profile (protected)PATCH /api/v1/users/me/update- Update current user profile (protected, with ValidationService)GET /api/v1/users/me/items- Get all items of current user (protected)GET /api/v1/users/me/item/{item_id}- Get specific item of current user (protected)
GET /api/v1/items/- Get all items with user info (public)GET /api/v1/items/item/{item_id}- Get item by ID with user info (public)POST /api/v1/items/create_item- Create new item (protected, with ValidationService)PATCH /api/v1/items/update_item/{item_id}- Update item (protected, with ValidationService, ownership verification)DELETE /api/v1/items/delete_item/{item_id}- Delete item (protected, owner only)
Request Context is a pattern that provides a convenient way to pass common dependencies (database, current user, logger, etc.) between application layers.
Click to expand request context example
from context.request_context import RequestContext, get_request_context
@user_router.get("/me/items")
async def get_current_user_items(context: RequestContext = Depends(get_request_context)):
"""
- **context**: Request Context contains:
- **db**: Database session
- **current_user**: Authenticated user
"""
return await user_repository.get_current_user_items(current_user=context.current_user,
db=context.db)Advantages:
- Clean function signatures
- Easy to add new dependencies
- Centralized management
- Simplifies testing
Click to expand explicit dependency example
@user_router.get("/me/items")
async def get_current_user_items(current_user: schema.User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)):
"""
- **current_user**: Authenticated user
- **db**: Database session
"""
return await user_repository.get_current_user_items(current_user=current_user,
db=db)When to use:
- Simple endpoints with 1-2 dependencies
- When you need explicit control over dependencies
- Better clarity for beginners
- Add field to RequestContext (
/context/request_context.py):
@dataclass
class RequestContext:
db: AsyncSession
current_user: any
logger: logging.Logger # New dependency
cache: RedisClient # New dependency
Update context factory:
async def get_request_context(db: AsyncSession = Depends(get_db),
current_user: any = Depends(get_current_user),
logger: logging.Logger = Depends(get_logger), # New
cache: RedisClient = Depends(get_redis_client) # New
) -> RequestContext:
return RequestContext(db=db,
current_user=current_user,
logger=logger, # New
cache=cache # New
)Now all endpoints automatically get access!
BEFORE (with context)
async def some_endpoint(context: RequestContext = Depends(get_request_context)):
user = context.current_user
db = context.dbAFTER (without context)
async def some_endpoint(current_user: schema.User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)):
user = current_user
db = db@user_router.get("/me/items")
async def get_current_user_items(context: RequestContext = Depends(get_request_context)):
"""
Using Request Context - clean signature,
easy to add new dependencies.
"""
return await user_repository.get_current_user_items(current_user=context.current_user,
db=context.db)@user_router.get("/me/items")
async def get_current_user_items(
current_user: schema.User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
):
"""
Standard FastAPI approach - explicit dependencies,
better for understanding data flow.
"""
return await user_repository.get_current_user_items(
current_user=current_user,
db=db
)Request Context
- Scalability - easy to add services
- Code cleanliness - short function signatures
- Consistency - unified interface for all dependencies
- Testability - one mock for all dependencies
Standard Dependencies
- Clarity - explicitly see which dependencies are used
- Flexibility - different dependencies for different endpoints
- Simplicity - fewer abstractions to learn
- Standard - follows FastAPI documentation
The ValidationService is a centralized validation system that ensures data integrity by checking for duplicate values in globally unique and per-user unique fields before database operations.
Current Status:
-
Global Unique Field Validation - Prevents duplicate values across entire database
- Example: Email addresses, usernames must be globally unique
-
Per-User Unique Field Validation - Prevents duplicates within a single user's records
- Example: Item names must be unique per user (one user cannot have two items named "My Item")
-
Extensible Rules - Easy to add new validation rules without changing validation logic
Request Data
β
ValidationService.validate_update()
β
Check VALIDATION_RULES for model
β
For each unique field in update data:
- Check if value already exists (exclude current record)
- Raise HTTPException(409) if duplicate found
β
β All checks pass β Continue to database update
β Duplicate found β Raise HTTPException(409) before commit
# In services/validation_services.py
VALIDATION_RULES = {
"User": {
"unique_fields": ["email", "name"], # Globally unique
"required_fields": ["email", "name", "password"],
# "unique_per_user_fields": [] # Users don't have per-user unique fields
},
"Item": {
"unique_fields": [], # Items can have same name globally
"required_fields": ["name", "user_id"],
"unique_per_user_fields": ["name"] # But not per user
}
}- Add model to VALIDATION_RULES:
VALIDATION_RULES = {
# ... existing rules ...
"Project": {
"unique_fields": ["slug"], # Projects have globally unique slugs
"required_fields": ["name", "slug", "user_id"],
"unique_per_user_fields": ["name", "code"] # But names and codes unique per user
}
}- That's it!
ValidationServiceautomatically handles all validation.
# In repository or DAO layer
from services.validation_services import ValidationService
# Before updating a record:
await ValidationService.validate_update(
model_class=models.Item,
record=existing_item, # Current database record
update_data={"name": "New Name"}, # Data being updated
db=db_session
)
# If duplicate found β HTTPException(409) raised
# If validation passes β Safe to proceed with update
await db_session.commit()Successful Update (No Duplicates):
{
"status": 200,
"message": "Item updated successfully",
"data": { ... }
}Validation Error (Duplicate Found):
{
"status": 409,
"detail": "Value 'Gaming Laptop' for field 'name' already exists for this user"
}Method: check_field_duplicates
- Checks if a value exists for a field across entire table
- Excludes current record from search (allows keeping same value during update)
- Returns:
Trueif duplicate found,Falseif safe
Method: check_field_duplicates_per_user
- Checks if a value exists for a field within specific user's records
- Requires model to have
user_idattribute - Excludes current record by ID
- Returns:
Trueif duplicate found for user,Falseif safe
Safety Net: IntegrityError Handling
# In GeneralDAO.update_record()
try:
await db.commit()
except IntegrityError as e:
# Catches any database constraint violations
# that ValidationService might have missed
await db.rollback()
raise HTTPException(status_code=409, detail="...")This preset follows a clean architecture pattern:
-
Routes Layer (
/routes/)-
HTTP endpoint definitions
-
Request validation with Pydantic schemas
-
Dependency injection
-
Response formatting
-
-
Repository Layer (
/repository/)-
Business logic and validation
-
Error handling
-
Data transformation between layers
-
Coordinates between routes and DAO
-
-
DAO Layer (
/DAO/)-
Data access operations
-
Database queries and transactions
-
Model-specific operations
-
Generic operations for any model
-
-
Models & Schemas (
/database/)-
SQLAlchemy data models
-
Pydantic schemas for request validation
-
Response schemas for API responses
-
Database configuration
-
-
Services Layer (
/services/)ValidationService- Centralized data validation and uniqueness checks- Item services - Item-related business logic
- User services - User-related business logic
-
Helpers (
/helpers/)-
Utility functions
-
JWT token management
-
Password hashing
-
Error handling utilities
-
- Create a new model in
database/models.py
# In database/models.py
class NewModel(Base):
"""
New model description.
Explain the purpose and relationships of this model.
"""
__tablename__ = 'new_model'
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String, nullable=False)
description: Mapped[str] = mapped_column(
String,
nullable=False,
server_default="No description"
)
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
# Many-to-one relationship with User model
user: Mapped["User"] = relationship(
"User",
back_populates="new_model", # Make sure to add this back_populates to User model
lazy="selectin"
)Don't forget to update the User model to include the back relationship:
# In User class, add:
new_model: Mapped[List["NewModel"]] = relationship(
"NewModel",
back_populates="user",
lazy="selectin"
)- Add Pydantic schemas in
database/schema.py
# In database/schema.py
class NewModelCreate(BaseModel):
name: str = Field(..., min_length=3)
description: Optional[str] = None
class NewModelUpdate(BaseModel):
name: Optional[str] = None
description: Optional[str] = None- Create Response Schemas
# In database/response_schemas.py
class NewModelResponse(BaseModel):
id: int
name: str
description: str
user_id: int
class Config:
from_attributes = True
# No need to create response wrapper classes - use generics!Tip: once you have schema classes like this, look at services/user_services.py for examples of
converting SQLAlchemy models to response models. The same pattern is used by
ItemService and the new create_current_user_response helper.
- Implement DAO Methods
# In DAO/new_model_dao.py
class NewModelDAO:
@classmethod
async def create_new_model(cls, db: AsyncSession, request: schema.NewModelCreate, user_id: int):
new_model = models.NewModel(
name=request.name,
description=request.description,
user_id=user_id
)
db.add(new_model)
await db.commit()
await db.refresh(new_model)
return new_modelNote: Updates are handled universally through GeneralDAO.update_record() which automatically uses ValidationService for validation. No need to create custom update methods!
- Add Validation Rules (If Needed)
If your model has unique fields, add validation rules to ValidationService:
# In services/validation_services.py - Update VALIDATION_RULES dictionary
VALIDATION_RULES = {
# ... existing models ...
"NewModel": {
"unique_fields": [], # Fields unique across entire DB
"required_fields": ["name", "user_id"],
"unique_per_user_fields": ["name"] # Fields unique per user
}
}Then ValidationService automatically validates these fields on updates!
- Add Repository Logic
# In repository/new_model_repository.py
async def create_new_model(
request: schema.NewModelCreate,
current_user: schema.User,
db: AsyncSession
) -> response_schemas.DataResponse[NewModelResponse]: # Use generic response
# Business logic and validation
new_model = await NewModelDAO.create_new_model(
db=db,
request=request,
user_id=current_user.id
)
return response_schemas.DataResponse[NewModelResponse](
message="New model created successfully",
status_code=200,
data=response_schemas.NewModelResponse(
id=new_model.id,
name=new_model.name,
description=new_model.description,
user_id=new_model.user_id
)
)- Define API Routes
# In routes/new_model_router.py
@router.post("/create_new_model")
async def create_new_model_endpoint(
request: schema.NewModelCreate,
context: RequestContext = Depends(get_request_context)
) -> response_schemas.DataResponse[NewModelResponse]: # Specify return type
return await new_model_repository.create_new_model(
request=request,
current_user=context.current_user,
db=context.db
)# In appropriate router file
@router.post("/new_endpoint")
async def new_feature(
request: schema.NewSchema,
current_user: schema.User = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
) -> DataResponse[NewModelResponse]: # Specify return type
return await repository.new_feature_logic(
request=request,
current_user=current_user,
db=db
)-
PostgreSQL connection failed:
- Ensure PostgreSQL service is running
- Verify credentials in
.envfile - Run
python test_postgres.pyto diagnose - Check if database exists and user has permissions
-
SQLite database not created:
- Check file path in
.env - Ensure directory has write permissions
- Check file path in
-
Alembic "empty migration":
- Ensure
target_metadata = Base.metadatainmigrations/env.py - Verify models are imported in
migrations/env.py
- Ensure
-
Migration conflicts:
- Check current migration state:
alembic current - Resolve conflicts:
alembic stamp headthenalembic upgrade head
- Check current migration state:
-
JWT tokens not working:
- Verify
SECRET_KEYin.envmatches the one used to create tokens - Check token expiration (default: 30 minutes)
- Verify
-
Password hashing errors:
- Ensure
bcryptis properly installed - Check password length (automatically handled in helpers)
- Ensure
Enable detailed logging by setting:
# In database.py - already enabled for development
echo=True # Set to False in production| Variable | Description | Default |
|---|---|---|
DB_HOST |
PostgreSQL host | localhost |
DB_PORT |
PostgreSQL port | 5432 |
DB_NAME |
Database name | fastapi_preset |
DB_USER |
Database user | postgres |
DB_PASSWORD |
Database password | - |
SECRET_KEY |
JWT signing key | - |
ALGORITHM |
JWT algorithm | HS256 |
A new data validation system has been added to ensure data integrity at the application level, before database operations.
What Changed:
- Added
ValidationServicefor centralized validation - Moved validation logic from DAO layer to service layer
- Early error detection (409 before commit, not IntegrityError from DB)
- Easy to extend - just add rules to
VALIDATION_RULESdictionary
Current Implementation:
- Supports update operations with
validate_update()method - Checks globally unique fields and per-user unique fields
- Automatically integrated into
GeneralDAO.update_record()
This preset is designed to be extended and customized for specific project needs. Feel free to:
- Add new features and endpoints
- Improve error handling and validation
- Enhance security measures
- Add testing suites
- Extend documentation
This FastAPI Preset is open-source and available for educational and commercial use. Please attribute the original source when using this as a foundation for your projects.
After setting up this preset, consider adding:
- Frontend Integration (React, Vue, etc.)
- Email Service for notifications
- File Upload capabilities
- Redis Integration for caching
- Docker Configuration for containerization
- Testing Suite with pytest
- API Rate Limiting
- Background Tasks with Celery
Happy coding! π