Cơ BảnFastAPI iconFastAPI

APIRouter dùng để tổ chức FastAPI app như thế nào?

APIRouter gom routes theo feature/module, cho phép đặt prefix, tags, dependencies và responses chung. Root app include router qua app.include_router().

Ví dụ:

python
router = APIRouter(prefix="/users", tags=["users"])

@router.get("/{user_id}")
async def get_user(user_id: int):
    return await service.get_user(user_id)

app.include_router(router)

App lớn nên tách theo domain như users, orders, billing, không tách theo technical layer kiểu tất cả controllers chung một file.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI