Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

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:

HTTP semantics matter in Python just as much as in .NET.