A FastAPI-based backend service for the Fastapi Boilerplate platform. This application provides RESTful APIs for managing estates, maintenance activities, bills, and resident records.
- Framework: FastAPI
- Language: Python 3.8+
- Database: PostgreSQL
- ORM: SQLAlchemy
- Migration Tool: Alembic
- Testing: unittest
- Authentication: JWT (JSON Web Tokens)
- Python 3.8 or higher
- PostgreSQL 12+
- pip (Python package manager)
1. Clone the repository
git clone https://github.com/Smash-Tech-Group/fastapi-boilerplate.git
cd fastapi-boilerplate2. Create and activate virtual environment
# Create virtual environment
python3 -m venv .venv
# Activate virtual environment
# On Linux/Mac:
source .venv/bin/activate
# On Windows:
.venv\Scripts\activate3. Install dependencies
pip install -r requirements.txt4. Configure environment variables
Create a .env file by copying the sample:
cp .env.sample .envUpdate the .env file with your configuration:
DATABASE_URL=postgresql://user:password@localhost:5432/em_fast_api
SECRET_KEY=your-secret-key-here
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=305. Set up PostgreSQL database
# Access PostgreSQL as root
sudo -u postgres psql-- Create database user
CREATE USER user WITH PASSWORD 'your_password';
-- Create database
CREATE DATABASE db_fast_api;
-- Grant privileges
GRANT ALL PRIVILEGES ON DATABASE db_fast_api TO user;
-- Exit PostgreSQL
\q6. Run database migrations
# Apply existing migrations
alembic upgrade head# Apply existing migrations
alembic revision --autogenerate -m "message"# Apply existing migrations
alembic upgrade head7. Seed the database (optional)
python3 seed.py DB - Sheet1.csv8. Start the server
python main.pyThe API will be available at http://localhost:8000
API Documentation:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
| Command | Description |
|---|---|
python main.py |
Start the FastAPI development server |
alembic revision --autogenerate -m "message" |
Generate new migration |
alembic upgrade head |
Apply all pending migrations |
alembic downgrade -1 |
Rollback last migration |
python3 seed.py |
Populate database with dummy data |
python -m unittest tests/v1/test_*.py |
Run specific test file |
When you add new models or modify existing ones:
1. Ensure your model is imported
Import your model in api/v1/models/__init__.py:
from .your_model import YourModel2. Generate migration
alembic revision --autogenerate -m "add your_table"3. Apply migration
alembic upgrade headIf you encounter this error:
ERROR [alembic.util.messaging] Target database is not up to date.
Solution:
# First, update the database
alembic upgrade head
# Then generate your migration
alembic revision --autogenerate -m "your migration message"This project uses Python's unittest framework.
Run specific tests:
# Test login endpoint
python -m unittest tests/v1/test_login.py
# Test signup endpoint
python -m unittest tests/v1/test_signup.pyfastapi-boilerplate/
βββ alembic/ # Database migrations
β βββ versions/ # Migration version files
β βββ env.py # Alembic environment configuration
βββ api/
β βββ core/ # Core application components
β β βββ base/ # Base classes and models
β β βββ dependencies/ # Dependency injection
β β βββ responses.py # Standard API responses
β βββ db/ # Database configuration
β β βββ database.py # Database connection and session
β βββ loggers/ # Logging configuration
β βββ utils/ # Utility functions and helpers
β β βββ config.py # Application configuration
β β βββ constants.py # Application constants
β β βββ db_validators.py # Database validation utilities
β β βββ files.py # File handling utilities
β β βββ helpers.py # General helper functions
β β βββ json_validator.py # JSON validation
β β βββ log_streamer.py # Log streaming utilities
β β βββ mime_types.py # MIME type definitions
β β βββ minio_service.py # MinIO object storage service
β β βββ pagination.py # Pagination utilities
β β βββ rate_limiter.py # Rate limiting middleware
β β βββ settings.py # Application settings
β β βββ success_response.py # Success response formatters
β β βββ tweet_service.py # Tweet/social media service
β β βββ urllib_request.py # HTTP request utilities
β βββ v1/ # API version 1
β βββ models/ # SQLAlchemy ORM models
β β βββ __init__.py # Import all models here
β βββ routes/ # API route handlers
β β βββ __init__.py # Router configuration
β βββ schemas/ # Pydantic request/response schemas
β βββ services/ # Business logic layer
βββ logs/ # Application logs
βββ media/ # Media files
β βββ uploads/ # User uploaded files
βββ node_modules/ # Node.js dependencies (if any)
βββ qa_tests/ # QA test suite
βββ tests/ # Unit and integration tests
β βββ v1/ # Version 1 API tests
β β βββ test_login.py
β β βββ test_signup.py
β βββ conftest.py # Pytest configuration and fixtures
β βββ database.py # Test database setup
β βββ run_all_test.py # Test runner script
βββ tmp/ # Temporary files
βββ venv/ # Virtual environment (git-ignored)
βββ .env # Environment variables (git-ignored)
βββ .env.sample # Environment variables template
βββ alembic.ini # Alembic configuration
βββ CountryPricingTable.py # Country pricing utilities
βββ LICENSE # Apache 2.0 License
βββ main.py # Application entry point
βββ package.json # Node.js package configuration
βββ package-lock.json # Node.js dependency lock
βββ README.md # Project documentation
βββ release.config.cjs # Release configuration
βββ requirements.txt # Python dependencies
βββ setup.py # Package setup configuration
βββ update_api_status.py # API status update script
1. Create your model file in api/v1/models/your_model.py
2. Import it in api/v1/models/__init__.py:
from .your_model import YourModel3. Generate and apply migration:
alembic revision --autogenerate -m "add your_model"
alembic upgrade head1. Check existing route files in api/v1/routes/
If a related file exists, add your route there. Otherwise, create a new file.
2. Create route file (e.g., api/v1/routes/yourRoute.py):
from fastapi import APIRouter
router = APIRouter(
prefix="/estates", # Don't include /api/v1
tags=["yourRoute"]
)
@router.get("/")
async def get_estates():
return {"message": "List of estates"}3. Register the router in api/v1/routes/__init__.py:
from .estates import router as estates_router
api_version_one.include_router(estates_router)Note: Don't include the base prefix
/api/v1in your router, as it's already included in theapi_version_onerouter.
We follow the Git Flow workflow for branch management and collaboration.
main- Production-ready codedevelop- Integration branch for featuresfeature/*- New featureshotfix/*- Urgent production fixesrelease/*- Release preparation
1. Start a new feature
# Create and switch to a new feature branch from develop
git checkout develop
git pull origin develop
git checkout -b feature/your-feature-name2. Work on your feature
- Write clean, maintainable code
- Add tests for new functionality
- Test endpoints before committing
- Follow the coding guidelines below
3. Run tests
python -m unittest discover tests/4. Commit your changes
# Use conventional commit messages
git add .
git commit -m "feat: add Fastapi Boilerplate endpoints"Commit message conventions:
feat:- New featurefix:- Bug fixdocs:- Documentation changesstyle:- Code style changes (formatting, etc.)refactor:- Code refactoringtest:- Adding or updating testschore:- Maintenance tasks
5. Push migrations and create Pull Request
# Push your feature branch (including migrations)
git push origin feature/your-feature-nameThen create a Pull Request from feature/your-feature-name β develop
6. After PR approval and merge
# Delete the local feature branch
git checkout develop
git pull origin develop
git branch -d feature/your-feature-nameFor urgent production fixes:
# Create hotfix branch from main
git checkout main
git pull origin main
git checkout -b hotfix/fix-critical-bug
# Make your fix and test thoroughly
python -m unittest discover tests/
# Commit and push
git commit -m "fix: resolve critical authentication bug"
git push origin hotfix/fix-critical-bugCreate PR to both main and develop
When preparing a release:
# Create release branch from develop
git checkout develop
git pull origin develop
git checkout -b release/v1.2.0
# Update version numbers, changelog, etc.
# Test thoroughly
# Merge to main
git checkout main
git merge release/v1.2.0
git tag -a v1.2.0 -m "Release version 1.2.0"
git push origin main --tags
# Merge back to develop
git checkout develop
git merge release/v1.2.0
git push origin develop
# Delete release branch
git branch -d release/v1.2.0- Follow PEP 8 style guide for Python code
- Write descriptive variable and function names
- Add docstrings to all functions and classes
- Keep functions small and focused
- Write tests for all new endpoints and services
- Always test endpoints before pushing
- Include Alembic migrations in your commits
- Use Pydantic schemas for request/response validation
- Implement proper error handling with appropriate HTTP status codes
- Use dependency injection for database sessions
- Keep business logic in service layer, not in routes
- Models: SQLAlchemy ORM models (
api/v1/models/) - Schemas: Pydantic models for validation (
api/v1/schemas/) - Routes: API endpoints (
api/v1/routes/) - Services: Business logic (
api/v1/services/) - Tests: Unit tests (
tests/v1/)
| File | Purpose |
|---|---|
main.py |
Application entry point and FastAPI configuration |
alembic.ini |
Alembic migration configuration |
requirements.txt |
Python package dependencies |
.env |
Environment variables (git-ignored) |
.env.sample |
Template for required environment variables |
seed.py |
Database seeding script |
- FastAPI Documentation
- SQLAlchemy Documentation
- Alembic Documentation
- PostgreSQL Documentation
- Pydantic Documentation
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
- β Always test your endpoints before pushing
- β Include Alembic migrations in your commits
- β
Update
.env.samplewhen adding new environment variables - β
Import new models in
api/v1/models/__init__.py - β Follow the Git Flow workflow for all contributions
- β
Run
alembic upgrade headbefore generating new migrations