1
---
2
name: fastapi-templates
3
description: Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.
4
---
5
6
# FastAPI Project Templates
7
8
Production-ready FastAPI project structures with async patterns, dependency injection, middleware, and best practices for building high-performance APIs.
9
10
## When to Use This Skill
11
12
- Starting new FastAPI projects from scratch
13
- Implementing async REST APIs with Python
14
- Building high-performance web services and microservices
15
- Creating async applications with PostgreSQL, MongoDB
16
- Setting up API projects with proper structure and testing
17
18
## Core Concepts
19
20
### 1. Project Structure
21
22
**Recommended Layout:**
23
24
```
25
app/
26
├── api/ # API routes
27
│ ├── v1/
28
│ │ ├── endpoints/
29
│ │ │ ├── users.py
30
│ │ │ ├── auth.py
31
│ │ │ └── items.py
32
│ │ └── router.py
33
│ └── dependencies.py # Shared dependencies
34
├── core/ # Core configuration
35
│ ├── config.py
36
│ ├── security.py
37
│ └── database.py
38
├── models/ # Database models
39
│ ├── user.py
40
│ └── item.py
41
├── schemas/ # Pydantic schemas
42
│ ├── user.py
43
│ └── item.py
44
├── services/ # Business logic
45
│ ├── user_service.py
46
│ └── auth_service.py
47
├── repositories/ # Data access
48
│ ├── user_repository.py
49
│ └── item_repository.py
50
└── main.py # Application entry
51
```
52
53
### 2. Dependency Injection
54
55
FastAPI's built-in DI system using `Depends`:
56
57
- Database session management
58
- Authentication/authorization
59
- Shared business logic
60
- Configuration injection
61
62
### 3. Async Patterns
63
64
Proper async/await usage:
65
66
- Async route handlers
67
- Async database operations
68
- Async background tasks
69
- Async middleware
70
71
### 4. Dependencies
72
73
The packages the examples import:
74
75
```text
76
# requirements.txt
77
fastapi
78
uvicorn[standard]
79
pydantic-settings
80
sqlalchemy[asyncio]>=2.0 # DeclarativeBase; [asyncio] installs greenlet for the async engine
81
asyncpg # PostgreSQL driver: postgresql+asyncpg://...
82
PyJWT
83
pwdlib[argon2]
84
python-multipart # only for a login route that uses OAuth2PasswordRequestForm
85
86
# requirements-dev.txt
87
pytest
88
pytest-asyncio
89
httpx
90
aiosqlite # test database: sqlite+aiosqlite:///:memory:
91
```
92
93
## Detailed worked examples and patterns
94
95
Detailed sections (starting with `## Implementation Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient.
96
97
## Testing
98
99
```python
100
# tests/conftest.py
101
import pytest_asyncio
102
from httpx import ASGITransport, AsyncClient
103
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
104
from sqlalchemy.orm import sessionmaker
105
106
from app.main import app
107
from app.core.database import get_db, Base
108
109
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
110
111
# Async fixtures need pytest_asyncio.fixture in pytest-asyncio's default strict mode
112
@pytest_asyncio.fixture
113
async def db_session():
114
engine = create_async_engine(TEST_DATABASE_URL, echo=True)
115
async with engine.begin() as conn:
116
await conn.run_sync(Base.metadata.create_all)
117
118
AsyncSessionLocal = sessionmaker(
119
engine, class_=AsyncSession, expire_on_commit=False
120
)
121
122
async with AsyncSessionLocal() as session:
123
yield session
124
await engine.dispose()
125
126
@pytest_asyncio.fixture
127
async def client(db_session):
128
async def override_get_db():
129
yield db_session
130
131
app.dependency_overrides[get_db] = override_get_db
132
133
# httpx 0.28 removed AsyncClient(app=...); use an ASGI transport
134
transport = ASGITransport(app=app)
135
async with AsyncClient(transport=transport, base_url="http://test") as client:
136
yield client
137
app.dependency_overrides.clear()
138
139
# tests/test_users.py
140
import pytest
141
142
@pytest.mark.asyncio
143
async def test_create_user(client):
144
response = await client.post(
145
"/api/v1/users/",
146
json={
147
"email": "test@example.com",
148
"password": "testpass123",
149
"name": "Test User"
150
}
151
)
152
assert response.status_code == 201
153
data = response.json()
154
assert data["email"] == "test@example.com"
155
assert "id" in data
156
```
157