FastAPI by Example: Custom Response Classes
While JSON is the default, sometimes you need to return other formats. This code example demonstrates how to use `HTMLResponse` and `PlainTextResponse` to return raw content.
Code
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, PlainTextResponse
app = FastAPI()
@app.get("/html", response_class=HTMLResponse)
async def read_html():
return """
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
"""
@app.get("/text", response_class=PlainTextResponse)
async def read_text():
return "Hello World"
@app.get("/legacy")
async def read_legacy():
# You can also return a Response object directly
return HTMLResponse(content="<h1>Legacy</h1>", status_code=200)Explanation
FastAPI is designed to be a JSON-first framework, automatically serializing dictionaries and Pydantic models into JSON. However, many applications need to serve other content types, such as HTML pages, plain text logs, or XML data. The response_class parameter in the route decorator allows you to override the default JSON behavior and specify exactly how the return value should be handled.
When you use response_class=HTMLResponse, FastAPI performs two critical actions. First, it sets the Content-Type header to text/html, ensuring browsers render the content correctly. Second, it bypasses the JSON serialization process, expecting your function to return a raw string or bytes. This makes it efficient for serving server-side rendered templates or static HTML snippets.
For even more granular control, you can return a Response object directly from your function, as shown in the legacy example. This approach allows you to dynamically set the status code, headers, and media type at runtime, rather than defining them statically in the decorator. This is particularly useful for scenarios where the response format might change based on the input data.
Code Breakdown
response_class=HTMLResponse tells FastAPI to treat the return value as HTML string, not data to be JSON encoded.PlainTextResponse sets the Content-Type to text/plain. Useful for returning simple messages or debug info.HTMLResponse(...) directly allows you to customize the response dynamically inside the function body.status_code=200 explicitly sets the HTTP status. You can change this to 404 or 500 based on logic.
