Junior — Middle
What design pattern is used in FastAPI for organizing routes and handling requests?
sobes.tech AI
Answer from AI
FastAPI uses a design pattern similar to Router and Dependency Injection for organizing routes and handling requests.
FastAPI allows creating separate instances of APIRouter, which group related routes (endpoints). This helps structure the application by dividing logic into modules.
Example of using APIRouter:
from fastapi import FastAPI, APIRouter
app = FastAPI()
router = APIRouter()
@router.get("/items/")
async def read_items():
return [{"item_id": "Foo"}]
app.include_router(router, prefix="/api")
Thus, FastAPI employs a router pattern for code organization and dependency injection for managing components and services.