Expert guide for FastAPI enterprise backend template with clean three-layer architecture, RBAC, JWT auth, and production-ready features
Expert assistant for working with enterprise-grade FastAPI backend template featuring clean three-layer architecture (API → Service → Repository → Model), built-in RBAC permission management, JWT authentication, and comprehensive enterprise features.
Use this skill when working with FastAPI projects that follow clean architecture patterns, especially when:
Follow this strict separation of concerns:
1. **API Layer** (`src/api/v1/`)
- Routes and endpoint definitions
- Request parameter validation
- Response formatting
- Keep routes thin - delegate to services
2. **Service Layer** (`src/services/`)
- Business logic implementation
- Permission checks and authorization
- Data validation and transformation
- Orchestrates repository calls
3. **Repository Layer** (`src/repositories/`)
- Data access operations
- CRUD implementations
- Query optimization (select_related, prefetch_related)
- Database transaction management
4. **Model Layer** (`src/models/`)
- Tortoise ORM model definitions
- Database schema representation
- Relationships and constraints
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
uv sync
uv sync --dev
```
```bash
uv run aerich init-db
uv run aerich migrate --name "describe_your_changes"
uv run aerich upgrade
uv run aerich history
```
Follow this exact sequence:
1. **Define Model** (`src/models/admin.py`)
- Inherit from `BaseModel` and `TimestampMixin`
- Use string references for relationships: `fields.ForeignKeyField("models.User")`
- Add indexes on frequently queried fields
2. **Create Schemas** (`src/schemas/`)
- Define Pydantic models for validation
- Separate schemas for create, update, and response
3. **Implement Repository** (`src/repositories/`)
- Add CRUD operations
- Use async methods
- Optimize queries with select_related/prefetch_related
4. **Write Service** (`src/services/`)
- Implement business logic
- Add permission checks
- Call repository methods
5. **Add API Routes** (`src/api/v1/`)
- Create endpoint handlers
- Use dependency injection for auth
- Keep routes minimal - delegate to services
6. **Generate Migration**
```bash
uv run aerich migrate --name "feature_name"
uv run aerich upgrade
```
7. **Write Tests** (`tests/`)
```bash
uv run pytest tests/test_feature.py
```
```bash
uv run uvicorn src:app --reload --host 0.0.0.0 --port 8000
uv run uvicorn src:app --host 0.0.0.0 --port 8000 --workers 4
```
```bash
uv run pre-commit run --all-files
git commit --no-verify -m "urgent fix"
```
```bash
uv run ruff check --fix src/
uv run ruff format src/
uv run mypy src/
```
```python
from src.core.dependencies import DependAuth
@router.get("/protected")
async def protected_route(current_user: User = DependAuth):
# current_user is authenticated User object
pass
from src.core.dependencies import SuperUserRequired
@router.post("/admin-only")
async def admin_route(current_user: User = SuperUserRequired):
# Only super admins can access
pass
```
```python
users = await User.all().select_related("department", "role")
users = await User.all().prefetch_related("permissions", "groups")
users = await User.all()\
.select_related("role")\
.prefetch_related("permissions")
```
```python
class Employee(BaseModel, TimestampMixin):
department = fields.ForeignKeyField(
"models.Department",
related_name="employees"
)
```
1. **Change Default Credentials**
- Default: username=`admin`, password=`abcd1234`
- Must change immediately!
2. **Environment Variables**
```bash
# Generate strong secret key
openssl rand -hex 32
# Set in .env
SECRET_KEY=<generated-key>
APP_ENV=production
DEBUG=False
```
3. **Database**
- Use PostgreSQL instead of SQLite
- Configure proper connection pooling
4. **CORS Configuration**
- Set specific `CORS_ORIGINS` (no wildcards)
5. **API Documentation**
- Set strong `SWAGGER_UI_PASSWORD`
```bash
uv run pytest
uv run pytest tests/test_users.py
uv run pytest --cov=src --cov-report=html
```
```bash
docker build -t backend-template .
docker run -p 8000:8000 backend-template
```
```bash
uv sync --group docs
uv run mkdocs serve
uv run mkdocs build
uv run mkdocs gh-deploy
```
After starting server, access:
1. **Always use async/await** - All routes and database operations must be asynchronous
2. **Never bypass repository pattern** - No direct model queries in services or routes
3. **UV is the package manager** - Don't use pip directly
4. **Always generate migrations** - Never modify database schema manually
5. **Follow dependency injection** - Use FastAPI's dependency system for authentication
6. **String references for models** - Avoid circular imports in relationships
Configure in `.env`:
```python
class Product(BaseModel, TimestampMixin):
name = fields.CharField(max_length=100)
price = fields.DecimalField(max_digits=10, decimal_places=2)
category = fields.ForeignKeyField("models.Category", related_name="products")
class ProductCreate(BaseModel):
name: str
price: Decimal
category_id: int
class ProductRepository:
async def create(self, data: ProductCreate) -> Product:
return await Product.create(**data.dict())
class ProductService:
def __init__(self, repo: ProductRepository):
self.repo = repo
async def create_product(self, data: ProductCreate, user: User) -> Product:
# Business logic and permission checks
if not user.has_permission("product.create"):
raise PermissionDenied()
return await self.repo.create(data)
@router.post("/products")
async def create_product(
data: ProductCreate,
current_user: User = DependAuth
):
service = ProductService(ProductRepository())
return await service.create_product(data, current_user)
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/fastapi-enterprise-template-guide/raw