Full answer
By default FastAPI serialises the return value to JSON and wraps it in a JSONResponse. For other formats:
HTMLResponse: HTML pages or snippets. Setresponse_class=HTMLResponseso OpenAPI documentstext/html, then return a string.PlainTextResponse: plain text, for example a health check for a load balancer that expects text.RedirectResponse(url, status_code=307): default 307 keeps the method and body; use 303 after a form POST so the browser follows with GET; 301 or 308 for permanent moves.FileResponse(path, filename="report.pdf"): sends a file from disk efficiently withContent-Dispositionand content length.filenametriggers a download.StreamingResponse(generator, media_type=...): sends data as it is produced (CSV exports, large files, server-sent events).Response(content=bytes, media_type="image/png"): raw bytes with any media type.
Two ways to use them:
@app.get("/notice", response_class=HTMLResponse)
def notice(): return "<h1>Holiday</h1>"
@app.get("/old-results")
def old(): return RedirectResponse("/results", status_code=301)Important behaviour: when you return a Response object yourself, FastAPI sends it as is. No response model validation or filtering, no jsonable_encoder. Make sure the content is already safe and correct.
For server-rendered HTML pages, use Jinja2 templates (fastapi.templating.Jinja2Templates) with autoescaping, not hand-built strings with user input, to avoid XSS.
You can also change the default for the whole app: FastAPI(default_response_class=...).
import tempfile
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, RedirectResponse
from fastapi.testclient import TestClient
app = FastAPI()
report = Path(tempfile.mkdtemp()) / "term1.csv"
report.write_text("roll_no,marks\n1,88\n2,73\n")
@app.get("/notice", response_class=HTMLResponse)
def notice():
return "<h1>College closed on Friday</h1>"
@app.get("/ping", response_class=PlainTextResponse)
def ping():
return "pong"
@app.get("/old-results")
def old_results():
return RedirectResponse("/results", status_code=301)
@app.get("/reports/term1")
def download():
return FileResponse(report, media_type="text/csv", filename="term1-results.csv")
c = TestClient(app, follow_redirects=False)
r = c.get("/notice"); print(r.headers["content-type"], r.text)
r = c.get("/ping"); print(r.headers["content-type"], r.text)
r = c.get("/old-results"); print(r.status_code, r.headers["location"])
r = c.get("/reports/term1"); print(r.headers["content-disposition"], r.text.splitlines())
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): text/html; charset=utf-8 <h1>College closed on Friday</h1> text/plain; charset=utf-8 pong 301 /results attachment; filename="term1-results.csv" ['roll_no,marks', '1,88', '2,73']
Key points
- Return a Response subclass or set response_class
- HTML, plain text, redirect, file, streaming and raw responses
- Returned Response objects skip response models
- 303 after POST, 307/308 to keep the method
- Use templates with autoescaping for HTML
Common mistakes
- Returning HTML strings without response_class, so clients receive a JSON-encoded string
- Building HTML with user input by string formatting (XSS)
- Using 307 after a form POST, so the browser re-posts
- Expecting response_model filtering to apply to a returned Response object
Follow-ups
- How would you stream a 1 GB CSV export?
- Which redirect code would you use after a successful form submission, and why?
- How do you serve server-rendered pages with Jinja2 in FastAPI?
Tips
- Name the classes and a use for each
- Point out that returning a Response skips validation
- Know the redirect status codes