FastAPI interview question · Most asked
How do you structure a larger FastAPI project?
Summary
Split routes into APIRouter modules per domain (users, orders), included with prefixes and tags, and separate schemas (Pydantic), models (ORM), services/repositories and dependencies into their own modules.
Longer Answer
A common layout: app/main.py (create app, include routers), app/core/config.py (settings), app/db/ (engine, session), app/<domain>/router.py, schemas.py, service.py, models.py. Routers can declare shared dependencies and responses. Keep business logic out of route functions so it's testable and reusable by CLI/workers.
Code Example
# app/users/router.py
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/{user_id}", response_model=UserOut)
async def get_user(user_id: int, db: DbSession):
return await service.get_user(db, user_id)
# app/main.py
app.include_router(users.router, prefix="/api/v1")
Key Points
APIRouter(prefix='/users', tags=['users'])- Domain-oriented packages
- Thin routes → services
- Centralized settings and DB session dependency
More most-asked FastAPI questions
- How does dependency injection with `Depends` work in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?