WeHelp
FastAPI 是簡單易學、現代化、高效能的後端系統開發框架,近代 Python 最受歡迎的技術堆疊之一。
  1. 簡介、安裝、快速開始
  2. 主機名稱、埠號
  3. 路徑、路由處理
  4. 路徑參數處理
  5. 查詢參數處理
  6. 靜態檔案處理
  7. 回應格式處理
  8. 網址導向
  9. 網頁表單互動
  10. 網頁表單 POST 方法
  11. 樣板引擎
  12. 請求文本處理
  13. 常見的連線方法
  14. 參數資料驗證
  15. 使用者狀態管理
  16. 資料庫連線
路徑參數處理
# FastAPI 路徑參數 路徑參數(Path Parameter)是放在 URL 路徑中的變數,通常用來表示特定資源。 例如: ```text /items/123 ``` 其中 `123` 就可以視為 `item_id`。 在 FastAPI 中: 1. 使用 `{參數名稱}` 宣告路徑參數。 2. 在路由函式中使用相同名稱的參數接收它。 3. 透過 Python 型別標註指定資料型別,FastAPI 會自動轉換與驗證。 --- ## 範例一:接收整數型路徑參數 ```python from fastapi import FastAPI app = FastAPI() @app.get("/items/{item_id}") def get_item(item_id: int): return { "item_id": item_id, "message": f"取得商品 {item_id}" } ``` 啟動後請求: ```text http://127.0.0.1:8000/items/123 ``` 回應: ```json { "item_id": 123, "message": "取得商品 123" } ``` 由於 `item_id` 被宣告為 `int`,因此: ```text http://127.0.0.1:8000/items/abc ``` 會因為無法轉換成整數而產生驗證錯誤。 --- ## 範例二:接收字串型路徑參數 ```python from fastapi import FastAPI app = FastAPI() @app.get("/users/{username}") def get_user(username: str): return { "username": username, "message": f"使用者名稱是 {username}" } ``` 啟動後請求: ```text http://127.0.0.1:8000/users/alice ``` 回應: ```json { "username": "alice", "message": "使用者名稱是 alice" } ``` 這裡的 `username` 是字串,因此可以接收像 `alice`、`tom` 等文字內容。 --- ## 重點整理 - 路徑參數使用大括號表示: ```python @app.get("/items/{item_id}") ``` - 路由函式中的參數名稱必須與路徑中的名稱相同: ```python def get_item(item_id: int): ``` - 型別標註會協助 FastAPI 自動轉換與驗證: ```python item_id: int username: str ``` - 路徑參數通常用於指定某個特定資源,例如: ```text /users/10 /products/25 /orders/1001 ```
相關學習地圖、教學課程
Python 後端工程、資料庫
從 0 開始,成為後端工程師的學習路徑。