Chapter 15: Generating Responses with Handlers
ASP.NET Core handlers return IResult, IActionResult, model objects, redirects, files, or pages. FastAPI handlers can return Python data, response objects, redirects, streaming responses, files, or template responses.
from fastapi.responses import FileResponse, RedirectResponse
@router.post("/recipes/{recipe_id}/publish")
def publish_recipe(recipe_id: int):
recipes_service.publish(recipe_id)
return RedirectResponse(
url=f"/recipes/{recipe_id}",
status_code=303,
)
@router.get("/exports/{export_id}")
def download_export(export_id: str):
path = export_service.get_export_path(export_id)
return FileResponse(path, filename="recipes.csv")
Response rules:
- For APIs, return validated models and status codes.
- For browser posts, redirect after successful form submission.
- For downloads, use file responses.
- For long-running exports, start a job and return a status URL.
- For errors, use consistent exception handling.
HTTP semantics matter in Python just as much as in .NET.