FastAPI Response Types

雖然大多數時候我們回傳的是 JSON (Dictionary 或 Pydantic Model),但 FastAPI (基於 Starlette) 提供了多種 Response 類別來應付不同的需求。

HTMLResponse (回傳網頁)

如果你不使用樣板引擎 (如 Jinja2),只是想簡單回傳一段 HTML 字串:

from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/", response_class=HTMLResponse)
async def read_items():
    return """
    <html>
        <head><title>My App</title></head>
        <body><h1>Hello FastAPI!</h1></body>
    </html>
    """

設定 response_class=HTMLResponse 會自動將 Content-Type 設定為 text/html

直接回傳 HTMLResponse 物件

除了在裝飾器中設定,你也直接在函數中回傳 HTMLResponse 物件:

@app.get("/items/")
async def read_items():
    html_content = "<h1>Hello!</h1>"
    return HTMLResponse(content=html_content, status_code=200)

PlainTextResponse (純文字)

用於回傳純文字內容。

from fastapi.responses import PlainTextResponse

@app.get("/hello", response_class=PlainTextResponse)
async def hello():
    return "Hello, this is just plain text."

RedirectResponse (重新導向)

當你需要將使用者導引到另一個 URL 時使用。預設狀態碼是 307 Temporary Redirect

from fastapi.responses import RedirectResponse

@app.get("/go-to-google")
async def redirect_to_google():
    return RedirectResponse(url="https://www.google.com")

設定不同的 Redirect 狀態碼

你可以手動指定狀態碼,例如 301 (永久移動) 或 302 (暫時移動):

from fastapi import status

@app.get("/pypy")
async def redirect_pypy():
    # 使用數字或 status 常數
    return RedirectResponse(
        url="https://www.pypy.org/",
        status_code=status.HTTP_301_MOVED_PERMANENTLY
    )

JSONResponse (手動回傳 JSON)

通常 FastAPI 會幫你自動轉換。但如果你需要自訂更細緻的回應(如特殊的狀態碼或 Header),可以使用 JSONResponse

from fastapi.responses import JSONResponse

@app.get("/custom-json")
async def custom():
    return JSONResponse(
        content={"message": "Custom JSON"},
        status_code=202
    )

ORJSONResponse (高效能 JSON)

如果你對效能有極致要求,或者需要序列化一些特殊型別,可以安裝 orjson 並使用 ORJSONResponse

pip install orjson
from fastapi.responses import ORJSONResponse

@app.get("/fast-json", response_class=ORJSONResponse)
async def fast():
    return {"message": "Very fast response"}

總結

  • HTMLResponse: 用於回傳 HTML 內容。
  • PlainTextResponse: 用於回傳純文字。
  • RedirectResponse: 用於執行跳轉。
  • JSONResponse: 當需要手動控制 JSON 回應時。
  • response_class 參數能讓 FastAPI 自動處理對應的媒體類型 (Media Type)。