Skip to content
devtoolbox.cc

FastAPI · Chapter 3 of 6

FastAPI responses: status codes, errors, files, cookies

15 min study · Examples checked with FastAPI 0.163 on Python 3.14 ·

So far every handler returned a dictionary, sent as JSON with status 200. A response has more parts: a status code saying what happened, headers describing the body, and a body in whatever format fits. This chapter covers error responses, other media types, files and streams, redirects, and headers and cookies.

The example application

Create main.py, and a text file at public/outline.txt next to it for the download route:

Python track
1. Install Python
2. Values and numbers
from pathlib import Path
from typing import Annotated, Literal

from fastapi import Cookie, FastAPI, Header, HTTPException, Request, Response, status
from fastapi.responses import (
    FileResponse,
    HTMLResponse,
    JSONResponse,
    PlainTextResponse,
    RedirectResponse,
    StreamingResponse,
)

app = FastAPI()
OUTLINE = Path(__file__).resolve().parent / "public" / "outline.txt"
LESSONS = {1: "Variables", 2: "Loops"}


class LessonLocked(Exception):
    def __init__(self, lesson_id: int):
        self.lesson_id = lesson_id


@app.exception_handler(LessonLocked)
def locked_handler(request: Request, exc: LessonLocked):
    return JSONResponse(
        status_code=status.HTTP_403_FORBIDDEN,
        content={"detail": f"Lesson {exc.lesson_id} unlocks after the previous one"},
    )


@app.get("/lessons/{lesson_id}")
def read_lesson(lesson_id: int):
    if lesson_id == 3:
        raise LessonLocked(lesson_id)
    if lesson_id not in LESSONS:
        raise HTTPException(status_code=404, detail="Lesson not found")
    return {"id": lesson_id, "title": LESSONS[lesson_id]}


@app.get("/welcome", response_class=HTMLResponse)
def welcome():
    return "<h1>Study Tracker</h1><p>Pick a lesson to begin.</p>"


@app.get("/health", response_class=PlainTextResponse)
def health():
    return "ok"


@app.get("/outline.txt")
def outline():
    return FileResponse(OUTLINE, media_type="text/plain", filename="python-outline.txt")


@app.get("/export.csv")
def export():
    def rows():
        yield "id,title\n"
        for lesson_id, title in LESSONS.items():
            yield f"{lesson_id},{title}\n"
    return StreamingResponse(rows(), media_type="text/csv")


@app.get("/start")
def old_start_page():
    return RedirectResponse("/welcome", status_code=status.HTTP_308_PERMANENT_REDIRECT)


@app.get("/me/preferences")
def preferences(
    response: Response,
    theme: Annotated[Literal["light", "dark"], Cookie()] = "light",
    accept_language: Annotated[str | None, Header()] = None,
):
    response.headers["Cache-Control"] = "no-store"
    return {"theme": theme, "language": accept_language}


@app.put("/me/preferences/theme/{theme}", status_code=status.HTTP_204_NO_CONTENT)
def set_theme(theme: Literal["light", "dark"], response: Response):
    response.set_cookie("theme", theme, max_age=30 * 24 * 3600, httponly=True, samesite="lax", secure=True)

All responses quoted below came from running this application with TestClient.

Status codes say what happened

Clients, browsers, proxies and monitoring read the status code first, so it must match what happened:

Code Meaning Typical use
200 OK Success with a body Reads, updates that return the resource
201 Created A new resource exists POST that creates something
204 No Content Success without a body DELETE, or settings changes
400 / 422 The request is malformed / fails validation FastAPI uses 422 for validation
401 / 403 Not authenticated / authenticated but not allowed Missing token / wrong role
404 Not Found No such resource Unknown ID
409 Conflict Clashes with current state Duplicate title, stale version

Set it in the decorator (status_code=201), ideally with the fastapi.status constants. A {"status": 404} in the body does not change the HTTP status.

Raising errors

Inside a handler, raise HTTPException(status_code=404, detail="Lesson not found") stops the handler and sends {"detail": "Lesson not found"} with status 404.

For errors that belong to your domain, define an exception class and register a handler for it once with @app.exception_handler. In the example, LessonLocked becomes a 403 with a specific message wherever it is raised:

GET /lessons/1 -> 200 {"id": 1, "title": "Variables"}
GET /lessons/3 -> 403 {"detail": "Lesson 3 unlocks after the previous one"}
GET /lessons/9 -> 404 {"detail": "Lesson not found"}

Business code then stays free of HTTP details. Never put stack traces in error bodies.

HTML, text, files and streams

A handler’s return value is JSON unless you say otherwise. Returning a plain string from a normal route produces the JSON string "...", quotes included. response_class=HTMLResponse sends the string as text/html and PlainTextResponse as text/plain.

FileResponse sends a file from disk efficiently and sets its media type; with filename= it adds Content-Disposition: attachment; filename="python-outline.txt", so browsers download it under that name. The path in the example is fixed by the server. Never build a file path from user input without checking it stays inside the allowed folder (files chapter), or the route becomes a way to read any file on the machine.

StreamingResponse takes an iterator, here a generator, and sends each piece as it is produced. A large CSV export then never needs to fit in memory: /export.csv returns id,title\n1,Variables\n2,Loops\n with media type text/csv, built line by line.

Redirects

A redirect is a 3xx status with a Location header; RedirectResponse defaults to 307. With 301 and 302, browsers may turn a redirected POST into a GET. 307 (temporary) and 308 (permanent) always repeat the same method and body. 303 See Other always makes the browser follow up with a GET, which is the standard answer to a successful form POST (chapter 4). The /start route moved for good, so it returns 308 with Location: /welcome; browsers remember permanent redirects, so use them only for moves that won’t be undone.

Headers and cookies

Declare request headers as parameters with Header(). FastAPI converts the Python name to the HTTP name, so accept_language reads the Accept-Language header. To set response headers, add a response: Response parameter and change response.headers. The example sets Cache-Control: no-store, so browsers and proxies don’t cache personal settings.

A cookie is a small value the browser stores and sends back with every request to the site. response.set_cookie creates one, and a Cookie() parameter reads it, validated like any other input:

PUT /me/preferences/theme/dark -> 204 (empty body)
  set-cookie: theme=dark; HttpOnly; Max-Age=2592000; Path=/; SameSite=lax; Secure

GET /me/preferences  (Cookie: theme=dark, Accept-Language: de-DE)
  -> 200 {"theme": "dark", "language": "de-DE"}   cache-control: no-store

GET /me/preferences  (Cookie: theme=blue)
  -> 422 ["cookie", "theme"] Input should be 'light' or 'dark'

The attributes matter. HttpOnly hides the cookie from JavaScript, which limits what an injected script can steal. Secure sends it over HTTPS only, so it won’t round-trip on a plain http://localhost; tests use an https:// base URL. SameSite=lax stops most cross-site requests from carrying it, a first defence against cross-site request forgery. Max-Age sets the lifetime; response.delete_cookie("theme") removes it.

Cookies come from the client and can be edited, so treat them as untrusted input: validate them, as the Literal type does here, and never store something like role=admin in a plain cookie. A 204 response must have no body, so the handler returns nothing and FastAPI sends an empty response.

Practice

Add DELETE /me/preferences/theme that removes the cookie and returns 204, and change /lessons/{lesson_id} so that a lesson ID above 1000 is answered with a 308 redirect to /archive/{lesson_id}. Test both with TestClient (pass follow_redirects=False to see the redirect itself).

Answer check: response.delete_cookie("theme") produces a set-cookie header with Max-Age=0, which tells the browser to drop it. For the redirect, return RedirectResponse(f"/archive/{lesson_id}", status_code=308) from inside the handler; the test sees status 308 and the location header /archive/1001. Without follow_redirects=False, the client follows it to an unknown path and you see a 404.

Summary

Choose status codes that match the outcome and raise HTTPException, or register handlers for your own exceptions. Use HTMLResponse, PlainTextResponse, FileResponse and StreamingResponse for non-JSON bodies, 303 after form posts and 307/308 to keep the method, and read headers and cookies as validated parameters. Set cookies with HttpOnly, Secure and SameSite, and never trust their contents.

All FastAPI chapters