WeHelp
FastAPI 是簡單易學、現代化、高效能的後端系統開發框架,近代 Python 最受歡迎的技術堆疊之一。
  1. 簡介、安裝、快速開始
  2. 主機名稱、埠號
  3. 路徑、路由處理
  4. 路徑參數處理
  5. 查詢參數處理
  6. 靜態檔案處理
  7. 回應格式處理
  8. 網址導向
  9. 網頁表單互動
  10. 網頁表單 POST 方法
  11. 樣板引擎
  12. 請求文本處理
  13. 常見的連線方法
  14. 參數資料驗證
  15. 使用者狀態管理
  16. 資料庫連線
請求文本處理
FastAPI 可以透過 **Pydantic Model** 定義 JSON Request Body 的格式。當前端以 `application/json` 傳送資料時,FastAPI 會自動: 1. 讀取 HTTP Request Body 2. 將 JSON 解析成 Python 資料 3. 根據 Pydantic Model 進行型別與欄位驗證 4. 將驗證後的資料注入到路由函式參數中 ## 1. FastAPI 後端範例 安裝套件: ```bash pip install fastapi uvicorn ``` 建立 `main.py`: ```python from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() # 定義 JSON Request Body 的格式 class UserCreate(BaseModel): name: str email: str age: int @app.post("/users") def create_user(user: UserCreate): return { "message": "使用者建立成功", "user": { "name": user.name, "email": user.email, "age": user.age } } ``` 啟動伺服器: ```bash uvicorn main:app --reload ``` 伺服器預設會執行在: ```text http://127.0.0.1:8000 ``` ## 2. 前端使用 `fetch()` 傳送 JSON 建立一個 `index.html`: ```html <!DOCTYPE html> <html lang="zh-Hant"> <head> <meta charset="UTF-8"> <title>FastAPI JSON 範例</title> </head> <body> <h1>建立使用者</h1> <button id="submitButton">送出資料</button> <script> document .getElementById("submitButton") .addEventListener("click", async () => { const userData = { name: "王小明", email: "ming@example.com", age: 25 }; try { const response = await fetch("http://127.0.0.1:8000/users", { method: "POST", // 告訴 FastAPI:Request Body 是 JSON headers: { "Content-Type": "application/json" }, // JavaScript Object 轉成 JSON 字串 body: JSON.stringify(userData) }); const result = await response.json(); if (!response.ok) { console.error("請求失敗:", result); return; } console.log("伺服器回應:", result); } catch (error) { console.error("網路錯誤:", error); } }); </script> </body> </html> ``` 前端實際送出的 JSON 內容如下: ```json { "name": "王小明", "email": "ming@example.com", "age": 25 } ``` FastAPI 會將它轉換成 `UserCreate` 物件,因此可以直接使用: ```python user.name user.email user.age ``` ## 3. 欄位驗證 如果前端傳送的資料缺少欄位,或型別不正確,例如: ```json { "name": "王小明", "email": "ming@example.com" } ``` 由於缺少 `age`,FastAPI 會自動回傳 HTTP `422 Unprocessable Entity`,並提供驗證錯誤資訊。 例如: ```json { "detail": [ { "type": "missing", "loc": ["body", "age"], "msg": "Field required" } ] } ``` 若傳送: ```json { "name": "王小明", "email": "ming@example.com", "age": "abc" } ``` 也會因為 `age` 必須是整數而驗證失敗。 完整概念是: ```text fetch() ↓ JSON.stringify() ↓ HTTP POST + Content-Type: application/json ↓ FastAPI 解析 JSON ↓ Pydantic 驗證資料 ↓ 注入 UserCreate 參數 ↓ 回傳 JSON Response ```
相關學習地圖、教學課程
Python 後端工程、資料庫
從 0 開始,成為後端工程師的學習路徑。