Performance: Including routers in main app
This affects the initial server startup time and the routing lookup speed during request handling.
from fastapi import FastAPI, APIRouter items_router = APIRouter() @items_router.get('/items') def read_items(): return {'items': []} users_router = APIRouter() @users_router.get('/users') def read_users(): return {'users': []} app = FastAPI() app.include_router(items_router) app.include_router(users_router)
from fastapi import FastAPI app = FastAPI() @app.get('/items') def read_items(): return {'items': []} @app.get('/users') def read_users(): return {'users': []}
| Pattern | Routing Table Size | Startup Time | Request Routing Speed | Verdict |
|---|---|---|---|---|
| All routes on main app | Large (all routes in one table) | Longer (registers all routes at once) | Slower (linear search through routes) | [X] Bad |
| Routes organized in routers | Smaller per router, combined efficiently | Shorter (modular registration) | Faster (optimized routing lookup) | [OK] Good |
include_router in a FastAPI application?include_router doesuser_router with prefix /users in a FastAPI app named app?include_router, not add_router or others.prefix='/users'.get_items endpoint?from fastapi import FastAPI, APIRouter
app = FastAPI()
router = APIRouter()
@router.get('/items')
async def get_items():
return {'items': [1, 2, 3]}
app.include_router(router, prefix='/api')/items inside the router./api, so the full path is /api/items.from fastapi import FastAPI, APIRouter
app = FastAPI()
router = APIRouter()
@router.get('/hello')
async def say_hello():
return {'message': 'Hello'}
app.include_router(router, prefix='/greet')
app.include_router(router, prefix='/greet')/greet.user_router with prefix /users and item_router with prefix /items. You want to include both in your FastAPI app and add tags for automatic docs grouping. Which code snippet correctly includes both routers with tags?tags argument in include_router.tags=['users'].Pass the test and this pattern moves unknown