skip to content

In FastAPI, how do you return an HTML page or a CSV file instead of JSON, and what does response_class change?

level: juniorimportance: should knowfreq 38%

answer

  1. default is JSON
  2. a decorator argument, not a return value
  3. media type drives Content-Type and docs
  4. HTMLResponse, PlainTextResponse, FileResponse

basics

~20 s

Pass response_class=HTMLResponse (or PlainTextResponse) to the path operation decorator and return a string, or return a FileResponse for a file. response_class sets the response's class, its Content-Type and the media type FastAPI documents in OpenAPI.

solid answer

~40 s

FastAPI answers with JSON unless told otherwise. For an HTML page I put `response_class=HTMLResponse` on the decorator and return a `str`: FastAPI wraps it in that class, sends `Content-Type: text/html; charset=utf-8`, and documents `text/html` in the schema. For a CSV export I return `FileResponse(path, media_type="text/csv", filename="orders.csv")`, which streams the file and adds `Content-Disposition: attachment`, plus `Content-Length`, `Last-Modified` and `ETag` taken from the file. Returning a response object directly also works, but FastAPI then sends it as is and documents nothing about it. `default_response_class` on `FastAPI()` or an `APIRouter` changes the default for every route, and a route's own `response_class` still overrides it.

code

python · 18 lines
python
from pathlib import Path

from fastapi import FastAPI
from fastapi.responses import FileResponse, HTMLResponse

app = FastAPI()
EXPORT = Path("orders-export.csv")


@app.get("/welcome", response_class=HTMLResponse)
def welcome():
    return "<h1>Welcome back</h1>"


@app.get("/exports/orders")
def export_orders():
    EXPORT.write_text("id,total\n1,9.50\n")
    return FileResponse(EXPORT, media_type="text/csv", filename="orders.csv")

go deeper

for a junior

Recall that JSON is the default and that response_class=HTMLResponse on the decorator, with a returned string, gives an HTML page.

for a middle

Explain the difference between declaring response_class and returning a response object: who sets Content-Type, and what the generated docs show in each case.

for a senior

Point out that directly returned responses leave the docs wrong, and guard file routes against user-controlled paths before serving them with FileResponse.

for a principal

Decide whether HTML pages belong in this app at all, and if they do, whether a router-level default_response_class keeps them apart from the JSON API.

## The default: JSON A **path operation** is a function registered with a decorator such as `@app.get("/welcome")`. Whatever plain data it returns (a `dict`, a list, a Pydantic model) is turned into JSON and sent with `Content-Type: application/json`. That default is what most API routes want. Some routes do not: a server-rendered welcome page, a CSV export of orders, a plain-text health line. FastAPI gives you two ways to change the body format. ## Way 1: `response_class` on the decorator `response_class` is an argument of the **decorator**, like `status_code`, not a parameter of your function. It names the `Response` subclass FastAPI should put your return value into. ```python @app.get("/welcome", response_class=HTMLResponse) def welcome(): return "<h1>Welcome back</h1>" ``` Declaring it does three things: - **Wraps the return value.** The string you return becomes the body of an `HTMLResponse`. - **Sets the header.** The class's media type becomes `Content-Type`; Starlette appends `; charset=utf-8` to `text/` types, so the page arrives as `text/html; charset=utf-8`. - **Documents it.** The generated OpenAPI schema, and so Swagger UI and ReDoc, shows `text/html` for that route instead of `application/json`. The classes you will reach for most, all importable from `fastapi.responses` (they are Starlette's own classes, re-exported): | Class | Media type | What you return or pass | |---|---|---| | `JSONResponse` | `application/json` | JSON-compatible data | | `HTMLResponse` | `text/html` | a `str` or `bytes` of markup | | `PlainTextResponse` | `text/plain` | a `str` or `bytes` | | `RedirectResponse` | none | a URL; default status 307 | | `FileResponse` | guessed from the file name or path | a file path | | `Response` | whatever `media_type` you give it | raw `str` or `bytes` | ## Way 2: return a response object yourself You can also build the response in the function and return it, for example `return HTMLResponse(content=html)`. FastAPI then passes it through untouched: its body, status code and headers are exactly what you built. The trade-off is documentation. A response you return yourself is invisible to the schema, so the docs keep claiming `application/json`. If you want both, declare `response_class=HTMLResponse` on the decorator **and** return an `HTMLResponse`: the declaration is then used only to document the route, and your object is sent as is. ## Serving a CSV export with `FileResponse` `FileResponse` streams a file from disk asynchronously and takes its own arguments: 1. `path`: the file to send. 2. `media_type`: if you leave it out, it is guessed from `filename` or `path`, falling back to `application/octet-stream`. 3. `filename`: if set, it adds a `Content-Disposition: attachment` header so the browser saves the file under that name; a name with spaces or non-ASCII characters is encoded in the `filename*=utf-8''...` form. 4. `headers`: anything extra. It also adds `Content-Length`, `Last-Modified` and `ETag` derived from the file itself, and supports range requests. Returned directly, it is again undocumented, so a CSV route's docs still say `application/json` unless you describe the response yourself. Two safety notes for file routes. First, never build `path` from a user-supplied name without checking it stays inside the export directory, or a crafted name can read other files. Second, a generated export held in memory does not need a file at all: `Response(content=csv_text, media_type="text/csv")` with your own `Content-Disposition` header does the job. ## Smaller cases: plain text and in-memory bodies Not every non-JSON body needs a special class: - **A plain-text line**, such as a health check or a robots file: `response_class=PlainTextResponse` and return the string. The client receives `text/plain; charset=utf-8` instead of a quoted JSON string. - **A body you generate**, such as XML or a small CSV built from query results: `Response(content=body, media_type="application/xml")`. The base `Response` takes `content` as `str` or `bytes`, a `status_code`, a `headers` dict and a `media_type`, and adds `Content-Length` for you. - **Bytes from another service**, such as an image you proxy: `Response(content=data, media_type="image/png")`. The rule of thumb: declare a class on the decorator when the route always answers in that format and you want it documented; build the object yourself when you need to set the body, headers and status in code. ## Changing the default for a whole app or router `FastAPI(default_response_class=HTMLResponse)` or `APIRouter(default_response_class=...)` swaps the default for every route registered there. A route that declares its own `response_class` still wins, so one JSON route can live inside an HTML-first app. ## What to say in an interview - JSON is the default; `response_class` changes the class, the `Content-Type` and the documented media type. - Returning a response object gives full control and no documentation; declaring `response_class` as well restores the docs. - `FileResponse` with `filename` produces a download; with no `media_type` it guesses one from the name.

  • In FastAPI, what does the CSV route's documentation show if it returns a FileResponse directly?
    It still shows the default `application/json` response, because FastAPI cannot see what a function will return at runtime. The actual response carries `text/csv`. To document it you describe the response yourself, for example through the decorator's `responses` argument.
  • In FastAPI, how does FileResponse pick a Content-Type when you pass no media_type?
    It guesses from `filename` if you gave one, otherwise from `path`, using Python's MIME type table, and falls back to `application/octet-stream` when the extension is unknown. A `.csv` name gives `text/csv`, to which Starlette appends `; charset=utf-8` because it is a text type.

  • Returning an HTML string with no response_class and expecting a text/html page
  • Thinking response_class is a parameter of the path operation function
  • Believing a returned HTMLResponse is documented as text/html automatically
  • Thinking FileResponse needs filename set before it can send any file
  • Building the FileResponse path straight from a user-supplied file name