Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

Chapter 19: Creating a Website with Controller-Style Routers

MVC controllers group related actions. In FastAPI, APIRouter modules fill that role.

# web/account.py
router = APIRouter(prefix="/account", tags=["account"])


@router.get("/login")
def login_page(request: Request):
    ...


@router.post("/login")
def login_submit(request: Request):
    ...


@router.post("/logout")
def logout():
    ...

Controller-style organization:

Avoid placing all logic in route functions. Route functions should translate HTTP into application calls and translate results back into HTTP.