As a FastAPI application grows, organizing everything into global folders such as routers, schemas, services, and models can become difficult to maintain.
A feature-based structure groups code by business domain instead.
app/├── main.py├── cli.py│├── api/│ └── router.py│├── core/│ ├── config.py│ ├── database.py│ ├── security.py│ ├── cookies.py│ ├── sse.py│ └── text.py│├── db/│ ├── base.py│ └── registry.py│├── shared/│ └── bot_protection/│├── data/│ └── faqs.json│└── features/├── auth/├── admins/├── categories/├── plants/├── customers/├── orders/├── payments/├── reviews/├── notifications/├── overview/├── knowledge/└── chat/
main.pyThe entry point of the FastAPI application. It creates the app, configures middleware such as CORS, and mounts the main API router.
cli.pyContains command-line commands for tasks that are not HTTP requests, such as creating an admin account.
api/The API layer aggregates routers from all features.
main.py↓api/router.py↓feature routers
core/Contains application-wide infrastructure that is not specific to a business feature.
For example:
Features can use core, but core should not depend on business features.
db/Contains the SQLAlchemy foundation.
base.py defines Base and common model mixins, while registry.py imports all feature models so SQLAlchemy and Alembic can discover the complete database schema.
shared/Contains reusable application-level logic shared by multiple features.
For example, bot protection can be used by both orders and reviews without belonging to either feature.
data/Contains static application data, such as the FAQ data used to build the chatbot’s knowledge base.
features/Contains the actual business domains of the application.
Each feature owns the code related to that domain:
features/plants/├── router.py├── public_router.py├── service.py├── schemas.py├── models.py└── dependencies.py
The common responsibility is:
router↓service↓models↓database
schemas define the API data contract, while dependencies contain reusable dependencies for that feature.
knowledge/Handles the application’s RAG and Weaviate functionality, such as indexing plants, FAQs, and blogs and retrieving relevant information.
chat/Handles the chatbot API and DeepSeek integration. It can use the knowledge feature to retrieve relevant information before generating a response.