Python / FastAPI 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"}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
