Response Formats
1. 預設回應(JSON 格式)
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/json")
def return_json():
return JSONResponse{"message": "這是 JSON 回應"}2. 純文字回應(Plain Text)
from fastapi.responses import PlainTextResponse
@app.get("/text")
def return_text():
return PlainTextResponse("這是純文字內容")3. HTML 回應
4. 回傳檔案(FileResponse)
5. 串流資料(StreamingResponse)
6. 導向(RedirectResponse)
7. 回應模型(Response Model)
8. 自訂狀態碼與標頭
小結
回應類型
回傳格式
使用方式
Last updated