參數資料驗證
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 後端工程、資料庫