Performance: Why routing organizes endpoints
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 |
/items/?@app.get() to define GET routes, not @app.route() or @app.get_items()./items/ and /items work, but the question asks for /items/ exactly, so the decorator must match./hello in this FastAPI app?
from fastapi import FastAPI
app = FastAPI()
@app.get('/hello')
def say_hello():
return {'message': 'Hello, FastAPI!'}/hello returns a dictionary with key 'message' and value 'Hello, FastAPI!'.from fastapi import FastAPI
app = FastAPI()
@app.get('/users')
def get_users():
return {'users': ['Alice', 'Bob']}return is not indented, causing a syntax error.@app.get is correct, and returning a dictionary is valid for JSON response.APIRouter to group routes logically and then include them in the main app, improving structure and maintenance.Pass the test and this pattern moves unknown