WeHelp
FastAPI 是簡單易學、現代化、高效能的後端系統開發框架,近代 Python 最受歡迎的技術堆疊之一。
  1. 簡介、安裝、快速開始
  2. 主機名稱、埠號
  3. 路徑、路由處理
  4. 路徑參數處理
  5. 查詢參數處理
  6. 靜態檔案處理
  7. 回應格式處理
  8. 網址導向
  9. 網頁表單互動
  10. 網頁表單 POST 方法
  11. 樣板引擎
  12. 請求文本處理
  13. 常見的連線方法
  14. 參數資料驗證
  15. 使用者狀態管理
  16. 資料庫連線
參數資料驗證
FastAPI 主要透過 **Python 型別註記(type hints)** 與 **Pydantic 模型** 來定義及驗證參數資料型態。 - 路徑參數、查詢參數:直接使用函式參數的型別註記 - Request Body:使用 Pydantic `BaseModel` - FastAPI 會自動: 1. 解析輸入資料 2. 將資料轉換成指定型別 3. 驗證資料格式與限制 4. 驗證失敗時回傳 HTTP `422 Unprocessable Entity` ## 範例一:路徑參數與查詢參數 ```python from fastapi import FastAPI app = FastAPI() @app.get("/users/{user_id}") def get_user( user_id: int, # 路徑參數,必須是整數 active: bool = True, # 查詢參數,預設為 True limit: int = 10 # 查詢參數,預設為 10 ): return { "user_id": user_id, "active": active, "limit": limit } ``` 請求範例: ```text GET /users/123?active=false&limit=5 ``` 回應: ```json { "user_id": 123, "active": false, "limit": 5 } ``` 如果傳入: ```text GET /users/abc ``` 由於 `user_id` 必須是 `int`,FastAPI 會回傳驗證錯誤。 也可以使用 `Query` 增加額外限制: ```python from fastapi import FastAPI, Query app = FastAPI() @app.get("/products") def list_products( keyword: str = Query(..., min_length=2), page: int = Query(1, ge=1), size: int = Query(10, ge=1, le=100) ): return { "keyword": keyword, "page": page, "size": size } ``` 其中: - `...` 表示必填 - `min_length=2`:字串至少 2 個字元 - `ge=1`:大於或等於 1 - `le=100`:小於或等於 100 ## 範例二:使用 Pydantic 驗證 Request Body ```python from fastapi import FastAPI from pydantic import BaseModel, Field app = FastAPI() class Product(BaseModel): name: str price: float = Field(gt=0) quantity: int = Field(ge=1) description: str | None = None @app.post("/products") def create_product(product: Product): return { "message": "商品建立成功", "product": product } ``` 請求資料: ```json { "name": "Keyboard", "price": 999.5, "quantity": 2 } ``` FastAPI 會將 JSON 解析成 `Product` 物件,並驗證: - `name` 必須是字串 - `price` 必須是大於 `0` 的數值 - `quantity` 必須是大於或等於 `1` 的整數 - `description` 可以省略,也可以是字串或 `null` 若傳入: ```json { "name": "Keyboard", "price": -100, "quantity": 0 } ``` 則會因為不符合 `price` 與 `quantity` 的限制,回傳 `422` 驗證錯誤。 啟動程式: ```bash uvicorn main:app --reload ``` FastAPI 也會根據型別註記與 Pydantic 模型,自動產生 API 文件,可在以下網址查看: ```text http://127.0.0.1:8000/docs ```
相關學習地圖、教學課程
Python 後端工程、資料庫
從 0 開始,成為後端工程師的學習路徑。