Performance: Why routing organizes endpoints
MEDIUM IMPACT
Routing affects how quickly the server matches incoming requests to the correct code, impacting response time and server efficiency.
from fastapi import FastAPI, APIRouter app = FastAPI() user_router = APIRouter(prefix="/user") @user_router.get("") async def get_user(): return {"user": "info"} @user_router.get("/profile") async def get_profile(): return {"profile": "details"} @user_router.get("/settings") async def get_settings(): return {"settings": "data"} app.include_router(user_router)
from fastapi import FastAPI app = FastAPI() @app.get("/user") async def get_user(): return {"user": "info"} @app.get("/user/profile") async def get_profile(): return {"profile": "details"} @app.get("/user/settings") async def get_settings(): return {"settings": "data"} # All endpoints defined flatly without grouping or routers
| Pattern | Routing Checks | Request Matching Time | Scalability | Verdict |
|---|---|---|---|---|
| Flat endpoints on main app | High (checks all endpoints) | Slower as endpoints grow | Poor | [X] Bad |
| Grouped endpoints with routers | Low (checks grouped routes) | Faster matching | Good | [OK] Good |