路徑參數處理
# 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 後端工程、資料庫