Overview
FastrAPI provides several response classes for returning different content types from your route handlers. By default, routes return JSON, but you can use specific response classes for HTML, plain text, or redirects.
from fastrapi import FastrAPI
from fastrapi.responses import HTMLResponse, PlainTextResponse
app = FastrAPI()
@app.get("/html")
def get_html():
return HTMLResponse("<h1>Hello World</h1>")
@app.get("/text")
def get_text():
return PlainTextResponse("Hello World")
Response classes
JSONResponse
Return JSON data with proper content-type headers.
from fastrapi.responses import JSONResponse
@app.get("/data")
def get_data():
return JSONResponse(
{"message": "Success", "data": [1, 2, 3]},
status_code=200
)
Constructor
content
dict | list | Any
required
The data to serialize as JSON. Can be any JSON-serializable Python object
The HTTP status code for the response
Properties
The JSON content to be serialized
HTMLResponse
Return HTML content with text/html content-type.
from fastrapi.responses import HTMLResponse
@app.get("/page")
def get_page():
html_content = """
<!DOCTYPE html>
<html>
<head><title>My Page</title></head>
<body>
<h1>Welcome</h1>
<p>This is an HTML response</p>
</body>
</html>
"""
return HTMLResponse(html_content)
@app.get("/error")
def error_page():
return HTMLResponse(
"<h1>404 Not Found</h1>",
status_code=404
)
Constructor
The HTML content as a string
The HTTP status code for the response
Properties
PlainTextResponse
Return plain text content with text/plain content-type.
from fastrapi.responses import PlainTextResponse
@app.get("/robots.txt")
def robots():
content = """
User-agent: *
Disallow: /admin/
Allow: /
"""
return PlainTextResponse(content)
@app.get("/status")
def status():
return PlainTextResponse("OK", status_code=200)
Constructor
The plain text content as a string
The HTTP status code for the response
Properties
The plain text content string
RedirectResponse
Return a redirect response with a Location header.
from fastrapi.responses import RedirectResponse
@app.get("/old-path")
def old_path():
return RedirectResponse("/new-path")
@app.get("/external")
def external_redirect():
return RedirectResponse(
"https://example.com",
status_code=302
)
@app.post("/login")
def login(credentials):
# Perform login logic
return RedirectResponse("/dashboard", status_code=303)
Constructor
The URL to redirect to. Can be relative or absolute
The HTTP redirect status code. Common values:
301: Permanent redirect
302: Temporary redirect (changes method to GET)
303: See Other (always changes method to GET)
307: Temporary redirect (preserves method)
308: Permanent redirect (preserves method)
Properties
The HTTP redirect status code
Status codes
All response classes accept a status_code parameter. Common HTTP status codes:
Success (2xx)
200: OK
201: Created
202: Accepted
204: No Content
Redirection (3xx)
301: Moved Permanently
302: Found
303: See Other
307: Temporary Redirect
308: Permanent Redirect
Client Errors (4xx)
400: Bad Request
401: Unauthorized
403: Forbidden
404: Not Found
422: Unprocessable Entity
Server Errors (5xx)
500: Internal Server Error
502: Bad Gateway
503: Service Unavailable
Complete example
from fastrapi import FastrAPI
from fastrapi.responses import (
JSONResponse,
HTMLResponse,
PlainTextResponse,
RedirectResponse
)
from pydantic import BaseModel
app = FastrAPI()
class User(BaseModel):
name: str
email: str
@app.get("/")
def home():
return HTMLResponse("""
<!DOCTYPE html>
<html>
<head><title>Home</title></head>
<body><h1>Welcome to FastrAPI</h1></body>
</html>
""")
@app.get("/api/users")
def list_users():
return JSONResponse({
"users": [
{"id": 1, "name": "Alice"},
{"id": 2, "name": "Bob"}
]
})
@app.post("/api/users")
def create_user(user: User):
return JSONResponse(
{
"id": 3,
"name": user.name,
"email": user.email,
"created": True
},
status_code=201
)
@app.get("/health")
def health_check():
return PlainTextResponse("OK")
@app.get("/old-url")
def old_url():
return RedirectResponse("/new-url", status_code=301)
@app.get("/robots.txt")
def robots():
return PlainTextResponse(
"User-agent: *\nAllow: /\n"
)
@app.get("/download")
def download_file():
# For custom headers, you can still use JSONResponse
# with additional configuration
return PlainTextResponse(
"File content here",
status_code=200
)
if __name__ == "__main__":
app.serve("127.0.0.1", 8080)
Default response type
By default, FastrAPI routes return JSONResponse when you return a dictionary or list:
@app.get("/data")
def get_data():
# Automatically wrapped in JSONResponse
return {"message": "Hello World"}
You can override the default response class in the FastrAPI constructor:
from fastrapi.responses import PlainTextResponse
app = FastrAPI(default_response_class=PlainTextResponse)