請求文本處理
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 後端工程、資料庫