← Back to FastAPI
Lesson 3.3 · Responses & Errors

Response Types

JSON is only the default. Send HTML, plain text, redirects, a CSV download, a file from disk and a stream - and learn the traps: a Response you return yourself skips the response model, dates break JSONResponse, and a file path from the URL can escape your folder.

Intermediate30 min

What you will be able to do

  • Know what FastAPI does with a dict, a str and a Response object
  • Send HTML and plain text with response_class
  • Redirect with the right code: 307, 303 or 301
  • Offer a CSV download with Content-Disposition
  • Send a file from disk safely with FileResponse
  • Send data piece by piece with StreamingResponse
  • Avoid the traps of returning a Response yourself

The idea, in plain English

So far every endpoint returned a dict or a model, and FastAPI turned it into JSON. That is right for most APIs. But a browser wants HTML, a spreadsheet user wants a CSV file, an old address should send people to the new one, and a long answer (like AI output) should arrive piece by piece.

For each of these FastAPI has a response class: HTMLResponse, PlainTextResponse, RedirectResponse, FileResponse, StreamingResponse. You either name it in the decorator (response_class=) or return an object of it. All of them are children of Response.

We build one shop API that answers in seven ways, then try the traps that catch real projects. FastAPI 0.143.0, Starlette 1.7.0.

Worked example: A small shop API that answers the same sales data in seven ways - JSON, HTML, text, a redirect, a CSV download, a report file and a slow stream.

workflowWhat happens to your return valuestep 1 / 3

1 - Return a dict or a list

The normal way. FastAPI checks it with the response model, turns dates into text and sends JSON.

/sales
200 application/json
date
"2026-10-01"
secret fields
removed by the model

FastAPI looks at what your function returns. Real results from our shop API.

Words you will see in this lesson

A few words about responses.

Small dictionary
Content-TypeA response header that says what the body is: application/json, text/html, text/csv...
Response classA class that builds one kind of response: JSONResponse, HTMLResponse, FileResponse...
RedirectAn answer that says "look at this other address" (the Location header).
Content-DispositionA header that tells the browser to download the body as a file, with a file name.
StreamA body sent in pieces, as each piece is ready.
GeneratorA Python function with yield - it gives values one at a time.

An everyday example: a post office

At a post office you can send the same news in different ways:

  • A normal letter in a standard envelope - JSON, the default.
  • A greeting card with pictures - HTML for a browser.
  • A postcard with one short line - plain text.
  • "This person moved, send it here" - a redirect.
  • A parcel with a label - a file download.
  • A newspaper delivered every morning - a stream, piece by piece.
  • The label on the outside says what is inside - that is the Content-Type header.

Example 1 - one shop API, seven answers

Read it route by route:

  • sales - returns a list. FastAPI makes JSON and turns the dates into text.
  • page and ping - response_class=HTMLResponse / PlainTextResponse in the decorator. The function just returns a str.
  • old_sales - returns RedirectResponse("/sales").
  • sales_csv - builds the CSV in memory with the csv module and returns it with media_type="text/csv" and a Content-Disposition header.
  • report - sends a file from the reports folder with FileResponse - but checks the path first (see "File paths" below).
  • stream - StreamingResponse with a generator. Each yield is sent as soon as it is ready; time.sleep(1) makes it slow so we can see that.
Example 1 - responses.py
import csv import io import time from datetime import date from pathlib import Path from fastapi import FastAPI, HTTPException from fastapi.responses import (FileResponse, HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, StreamingResponse) from pydantic import BaseModel app = FastAPI() SALES = [{"day": date(2026, 10, 1), "item": "Lamp", "amount": 40}, {"day": date(2026, 10, 2), "item": "Chair", "amount": 75}] REPORTS = Path("reports") @app.get("/sales") # a dict or list -> JSON (the default) def sales(): return SALES @app.get("/page", response_class=HTMLResponse) # HTML for a browser def page(): return "<h1>Sales</h1><p>2 sales today</p>" @app.get("/ping", response_class=PlainTextResponse) # plain text def ping(): return "pong" @app.get("/old-sales") # a redirect to the new address def old_sales(): return RedirectResponse("/sales") @app.get("/sales.csv") # a CSV download, built in memory def sales_csv(): buffer = io.StringIO() writer = csv.DictWriter(buffer, fieldnames=["day", "item", "amount"], lineterminator="\n") writer.writeheader() writer.writerows(SALES) return PlainTextResponse(buffer.getvalue(), media_type="text/csv", headers={"Content-Disposition": 'attachment; filename="sales.csv"'}) @app.get("/reports/{name:path}") # a file from disk - checked first def report(name: str): path = (REPORTS / name).resolve() if not path.is_relative_to(REPORTS.resolve()) or not path.is_file(): raise HTTPException(status_code=404, detail="No such report") return FileResponse(path, filename=name) def count_slowly(): for n in range(1, 4): yield f"line {n}\n" # each yield is sent as soon as it is ready time.sleep(1) @app.get("/stream") def stream(): return StreamingResponse(count_slowly(), media_type="text/plain")
try_responses.py - call every route
from fastapi.testclient import TestClient from responses import app c = TestClient(app) def show(label, r, body=True): ct = r.headers.get("content-type") extra = "" if "content-disposition" in r.headers: extra = " Content-Disposition=" + r.headers["content-disposition"] if "location" in r.headers: extra = " Location=" + r.headers["location"] print(f"{label:<14} -> {r.status_code} {ct}{extra}") if body: print(" ", r.text.replace("\n", "\\n")) show("json", c.get("/sales")) show("html", c.get("/page")) show("text", c.get("/ping")) show("redirect", c.get("/old-sales", follow_redirects=False)) show("followed", c.get("/old-sales")) show("csv", c.get("/sales.csv")) show("file", c.get("/reports/august.csv")) show("missing file", c.get("/reports/may.csv")) show("escape", c.get("/reports/..%2F..%2Fsecret.txt")) show("stream", c.get("/stream"))

Reading the output

Look at the second column - the Content-Type:

  • json - application/json, and the dates became "2026-10-01".
  • html and text - text/html and text/plain, and the body is our str exactly, with no quotes.
  • redirect - 307 with Location=/sales and an empty body. TestClient follows redirects by default; with follow_redirects=False we see the 307 itself.
  • csv - text/csv plus Content-Disposition: attachment; filename="sales.csv". A browser saves it as sales.csv instead of showing it.
  • file - FileResponse guessed text/csv from the .csv ending and added the Content-Disposition because we gave filename=.
  • escape - a request for ../../secret.txt answered "No such report". Our check worked.
Output
json -> 200 application/json [{"day":"2026-10-01","item":"Lamp","amount":40},{"day":"2026-10-02","item":"Chair","amount":75}] html -> 200 text/html; charset=utf-8 <h1>Sales</h1><p>2 sales today</p> text -> 200 text/plain; charset=utf-8 pong redirect -> 307 None Location=/sales followed -> 200 application/json [{"day":"2026-10-01","item":"Lamp","amount":40},{"day":"2026-10-02","item":"Chair","amount":75}] csv -> 200 text/csv; charset=utf-8 Content-Disposition=attachment; filename="sales.csv" day,item,amount\n2026-10-01,Lamp,40\n2026-10-02,Chair,75\n file -> 200 text/csv; charset=utf-8 Content-Disposition=attachment; filename="august.csv" month,sales\nAugust,120\nSeptember,95\n missing file -> 404 application/json {"detail":"No such report"} escape -> 404 application/json {"detail":"No such report"} stream -> 200 text/plain; charset=utf-8 line 1\nline 2\nline 3\n

Redirects: 307, 303 or 301?

RedirectResponse uses 307 by default. The code decides what the client does next:

  • 307 - "go there, with the SAME method". Our POST /checkout-307 was followed as POST /orders - and /orders has only GET, so 405.
  • 303 - "see the other page, with GET". POST /checkout-303 was followed as GET /orders: 200. Use it after a form is sent, so a page refresh does not send the form again.
  • 301 - "moved for good". Browsers remember it, so use it only when the old address will never come back.
redirects.py
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/orders") def orders(): return ["order 1", "order 2"] @app.post("/checkout-307") def checkout_307(): return RedirectResponse("/orders") # default: 307 @app.post("/checkout-303") def checkout_303(): return RedirectResponse("/orders", status_code=303) # "see other": the browser switches to GET @app.get("/shop") def shop(): return RedirectResponse("https://example.com/shop", status_code=301) # moved for good
Output
POST /checkout-307 -> 307 Location=/orders POST /checkout-303 -> 303 Location=/orders GET /shop -> 301 Location=https://example.com/shop POST /checkout-307 followed -> POST /orders -> 405 {"detail":"Method Not Allowed"} POST /checkout-303 followed -> GET /orders -> 200 ["order 1","order 2"]

File paths: check before you send

FileResponse sends whatever file you give it. If the name comes from the URL, a client can ask for a file outside your folder (path traversal - Lesson 1.4).

  • We wrote an unsafe route: FileResponse(Path("reports") / name) with name:path and no check.
  • GET /unsafe/..%2F..%2Fsecret.txt sent our secret file: "secret=42". %2F is an encoded "/", so .. got through.
  • A plain /unsafe/../../secret.txt answered 404 - the client tidied the "../" away first. Attackers do not use such clients, so do not count on it.
  • The fix in report(): resolve() makes the full real path, and is_relative_to(REPORTS.resolve()) checks it is still inside the folder. Also check is_file().
The unsafe route (do not copy)
@app.get("/unsafe/{name:path}") def unsafe(name: str): return FileResponse(Path("reports") / name) # NO check

Tip: FileResponse also sent Content-Length, ETag and Last-Modified, and it answered a Range request ("bytes=0-10") with 206 and only the first 11 bytes. Browsers use this to resume downloads and play videos.

Streaming: piece by piece

We ran the app with uvicorn and read /stream with curl -N (do not wait for the end), printing the time of each line:

  • The headers came at once, then one line every second - the client did not wait 3 seconds for everything.
  • There is no Content-Length: the server does not know the size in advance, so it uses transfer-encoding: chunked.
  • Use it for big exports, logs and AI answers word by word (Agentic AI uses the same idea).
  • Once the first piece is sent, the status code is fixed. An error in the middle cannot change the 200 any more.
Output - curl -N, with the time of each line
22:05:15 HTTP/1.1 200 OK 22:05:15 date: Mon, 12 Oct 2026 16:35:14 GMT 22:05:15 server: uvicorn 22:05:15 content-type: text/plain; charset=utf-8 22:05:15 transfer-encoding: chunked 22:05:15 22:05:15 line 1 22:05:16 line 2 22:05:17 line 3

Traps when you return a Response yourself

traps.py has a user record with a password hash and a date, and UserOut with only name and joined.

  • A str without response_class became JSON: "pong" with quotes. Set response_class=PlainTextResponse if you mean text.
  • /me returned the record normally: UserOut removed the password hash.
  • /me-direct had response_model=UserOut but returned a JSONResponse - the password hash was sent. A Response object skips the response model completely.
  • /me-date put a date into JSONResponse: 500. JSONResponse uses plain json, which does not know dates. In tests: "TypeError: Object of type date is not JSON serializable".
  • jsonable_encoder() first turns dates (and models) into JSON-friendly values - but it does not filter anything: the hash is there again.
  • Rule: return dicts and models when you can. Return a Response only when you need something JSON cannot do - and then you must filter and convert yourself.
traps.py
from datetime import date from pathlib import Path from fastapi import FastAPI from fastapi.encoders import jsonable_encoder from fastapi.responses import FileResponse, JSONResponse from pydantic import BaseModel app = FastAPI() USER = {"name": "Ravi", "password_hash": "x9f2...", "joined": date(2026, 1, 5)} class UserOut(BaseModel): name: str joined: date @app.get("/text") # a str, no response_class def text(): return "pong" @app.get("/me", response_model=UserOut) # normal return: filtered by UserOut def me(): return USER @app.get("/me-direct", response_model=UserOut) # a Response returned yourself def me_direct(): return JSONResponse({"name": USER["name"], "password_hash": USER["password_hash"]}) @app.get("/me-date") def me_date(): return JSONResponse(USER) # a date inside JSONResponse @app.get("/me-encoded") def me_encoded(): return JSONResponse(jsonable_encoder(USER)) # jsonable_encoder first @app.get("/unsafe/{name:path}") def unsafe(name: str): return FileResponse(Path("reports") / name) # NO check
Output
str -> 200 application/json "pong" model -> 200 application/json {"name":"Ravi","joined":"2026-01-05"} direct -> 200 application/json {"name":"Ravi","password_hash":"x9f2..."} date -> 500 text/plain; charset=utf-8 Internal Server Error encoded -> 200 application/json {"name":"Ravi","password_hash":"x9f2...","joined":"2026-01-05"} unsafe -> 200 text/plain; charset=utf-8 secret=42 in tests: TypeError Object of type date is not JSON serializable

What /docs says

We checked app.openapi() for every route. /page showed text/html and /ping text/plain, from their response_class. But /sales.csv and /stream showed application/json - wrong. FastAPI cannot see what a returned Response contains.

  • responses={200: {"content": {"text/csv": {}}}} added text/csv, but application/json stayed in the list.
  • A tiny class CSVResponse(PlainTextResponse) with media_type = "text/csv", used as response_class, gave only text/csv - and the function can just return a str.
docs_fix.py
from fastapi import FastAPI from fastapi.responses import PlainTextResponse app = FastAPI() class CSVResponse(PlainTextResponse): # a text response with the CSV type media_type = "text/csv" @app.get("/a.csv", responses={200: {"content": {"text/csv": {}}}}) # adds text/csv to the docs def a(): return PlainTextResponse("day,item\n", media_type="text/csv") @app.get("/b.csv", response_class=CSVResponse) # the docs AND the response say text/csv def b(): return "day,item\n"
Output
docs /a.csv ['application/json', 'text/csv'] docs /b.csv ['text/csv'] GET /b.csv -> 200 text/csv; charset=utf-8 'day,item\n'

Response types at a glance

JSON

The default.

return {"ok": True}
HTML / text

Return a str.

@app.get("/", response_class=HTMLResponse)
Redirect

307 default; 303 after a form.

RedirectResponse("/orders", status_code=303)
Download

Text made in memory.

PlainTextResponse(text, media_type="text/csv",
  headers={"Content-Disposition": 'attachment; filename="x.csv"'})
File

Check the path first.

FileResponse(path, filename="report.csv")
Stream

Pieces as they are ready.

StreamingResponse(gen(), media_type="text/plain")

Try it yourself

The code does not change. Swap the content string and the program does something else entirely.

Open it in a browser

“Run fastapi dev responses.py and open /page, /sales.csv and /stream. What does the browser do with each?”

A JSON stream

“Change the generator to yield one JSON line per sale ({"item": ...}\n) with media_type="application/x-ndjson".”

Inline, not download

“Change Content-Disposition to inline; filename="sales.csv". What does the browser do now?”

A 302

“Try status_code=302 on /checkout and follow it. Which method does the client use?”

What usually goes wrong

Returning JSONResponse with secret fields

A returned Response skips the response model - nothing is filtered.

✗ return JSONResponse(user_record)
✓ return user_record   # with response_model=UserOut
Returning a str for text

Without response_class the str becomes JSON, with quotes.

✗ @app.get("/ping")
def ping(): return "pong"
✓ @app.get("/ping", response_class=PlainTextResponse)
A file path straight from the URL

An encoded ../ can reach files outside the folder.

✗ FileResponse(Path("reports") / name)
✓ path = (REPORTS / name).resolve()
if not path.is_relative_to(REPORTS.resolve()): raise ...
307 after a form POST

The client repeats the POST on the new address. Use 303 to switch to GET.

Practice

Write these yourself before opening anything. Getting them wrong first is most of how this sticks.

1.

Add GET /sales.html that shows SALES as an HTML table (one <tr> per sale), and GET /sales/latest that redirects with 307 to /sales/{day} of the newest sale. Check the Content-Type of both and make /docs show text/html for the table.

Show hint

response_class=HTMLResponse and build the rows with a join. For the redirect, use RedirectResponse(f"/sales/{day}").

Key points

  • A dict or model becomes JSON and goes through the response model.
  • response_class= sets the type for a returned str - and shows it in /docs.
  • RedirectResponse is 307 by default; use 303 after a POST.
  • Content-Disposition: attachment makes the browser download the body.
  • FileResponse sends any path you give it - resolve and check it first.
  • StreamingResponse sends each yield at once, without Content-Length.
  • A Response you return yourself skips the response model and the JSON conversion.

Quick check before you move on

What did return "pong" send without response_class?
JSON: "pong" with quotes, as application/json.
Which code does RedirectResponse use by default?
307.
What happened when a date was put into JSONResponse?
500 - TypeError: Object of type date is not JSON serializable.
Which header did the stream use instead of Content-Length?
transfer-encoding: chunked.

Interview questions

When would you return a Response object instead of a dict?

For non-JSON content (HTML, CSV, files, streams), custom headers or status on a one-off basis, or performance-sensitive pre-serialised JSON. You then lose response_model filtering and jsonable conversion, so you must handle both yourself.

How do you serve user-requested files safely?

Never join untrusted input to a path directly: resolve the path, check it stays inside an allowed base directory and is a regular file, or map ids to known files. Prefer generated names over client names.

What is the difference between 301, 302, 303 and 307?

301 permanent (cacheable), 302 temporary (method change is historically allowed), 303 see other (always GET - the POST/redirect/GET pattern), 307 temporary keeping method and body (308 is its permanent form).

Quiz

  1. 1.

    Why was the password hash sent by /me-direct although it had response_model=UserOut?

  2. 2.

    Why did the POST to /checkout-307 end with 405?

  3. 3.

    How did report() stop ../../secret.txt?

  4. 4.

    Why did /docs show application/json for /sales.csv?

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...