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

← All FastAPI questions