Chapter 6: Routing
ASP.NET Core endpoint routing maps URLs and HTTP verbs to handlers. FastAPI routes are path operation decorators.
from fastapi import APIRouter
router = APIRouter(prefix="/api/recipes", tags=["recipes"])
@router.get("")
def list_recipes():
...
@router.get("/{recipe_id}")
def get_recipe(recipe_id: int):
...
@router.put("/{recipe_id}")
def replace_recipe(recipe_id: int):
...
Register routers in the app:
from recipevault.api import recipes
app.include_router(recipes.router)
Routing best practices:
- Use plural resource names for REST-style resources.
- Keep route modules cohesive by feature, not by HTTP verb.
- Use
APIRouterfor modularity. - Put shared dependencies on routers when every endpoint in that router needs them.
- Avoid ambiguous routes such as
/{id}and/searchin surprising order. Prefer explicit prefixes.