Python / FastAPI Basics Interview Questions
How do you organise a FastAPI application with multiple routers (APIRouter)?
APIRouter is FastAPI's equivalent of Flask Blueprints — it lets you group related routes in separate files, then include them in the main app. This keeps large codebases manageable.
# routers/items.py from fastapi import APIRouter, Depends router = APIRouter( prefix="/items", # all routes here are prefixed tags=["items"], # Swagger UI grouping label responses={404: {"description": "Not found"}}, # shared response docs ) @router.get("/") def list_items(): return [{"name": "item1"}] @router.get("/{item_id}") def get_item(item_id: int): return {"item_id": item_id} @router.post("/", status_code=201) def create_item(name: str): return {"name": name}
# routers/users.py from fastapi import APIRouter router = APIRouter(prefix="/users", tags=["users"]) @router.get("/") def list_users(): return [{"username": "alice"}]
# main.py from fastapi import FastAPI from routers import items, users app = FastAPI() app.include_router(items.router) app.include_router(users.router) app.include_router( users.router, prefix="/v2", # override prefix for a second version dependencies=[Depends(verify_admin)], # apply dep to all routes ) @app.get("/") # root route stays in main.py def root(): return {"message": "API root"}
More Related questions...