Production Best Practices
1️⃣ Recommended Folder Structure
2️⃣ Mapping to Spring Boot (So It Feels Familiar)
| Spring Boot | FastAPI |
|---|---|
| @SpringBootApplication | main.py |
| Controller | api/endpoints |
| Service | services |
| Repository | repositories |
| Entity | models |
| DTO | schemas |
| application.yml | config.py / .env |
| Filters | middlewares |
3️⃣ main.py – Application Entry Point
➡ Similar to:
4️⃣ Router Aggregation (Like Controller Scanning)
api/v1/router.py
5️⃣ Controller Layer (Endpoints)
api/v1/endpoints/users.py
6️⃣ Schema (DTO)
schemas/user.py
7️⃣ Service Layer (Business Logic)
services/user_service.py
8️⃣ Repository Layer (DB Access)
repositories/user_repo.py
9️⃣ Dependency Injection (FastAPI Style)
➡ Similar concept to @Autowired.
🔟 Environment Configuration
.env
config.py
1️⃣1️⃣ Testing Structure
Uses:
-
pytest -
TestClient
1️⃣2️⃣ Production-Grade Tips
✅ Keep business logic out of controllers
✅ Use async DB drivers
✅ Version your APIs (/v1)
✅ Use dependency injection properly
✅ Add middleware for logging
✅ Use Docker for consistency
1️⃣3️⃣ Minimal Structure (For Small Services)
Use this only for small microservices.
Final Thoughts
FastAPI doesn’t force structure like Spring Boot, but teams must enforce discipline.
If you follow the above structure:
-
Code stays clean
-
Team collaboration improves
-
Scaling becomes easy