一、Pydantic 请求模型
from pydantic import BaseModel
class TodoCreate(BaseModel):
title: str
priority: str = "medium"
done: bool = False
class TodoResponse(BaseModel):
id: int
title: str
priority: str
done: bool
# 使用
@app.post("/todos", response_model=TodoResponse)
def create_todo(todo: TodoCreate):
# FastAPI 自动验证请求体
# 如果 title 缺失,自动返回 422 错误
return {"id": 1, **todo.model_dump()}
💡
Pydantic = Zod: 前端的 Zod 定义 schema 做验证,Pydantic 是 Python 版的 Zod。
二、错误处理
from fastapi import HTTPException
@app.get("/todos/{todo_id}")
def get_todo(todo_id: int):
todo = find_todo(todo_id)
if not todo:
raise HTTPException(status_code=404, detail="任务不存在")
return todo
# 自动返回:{"detail": "任务不存在"}
三、完整 CRUD
todos_db = []
next_id = 1
@app.post("/todos", response_model=TodoResponse)
def create_todo(todo: TodoCreate):
global next_id
item = {"id": next_id, **todo.model_dump()}
todos_db.append(item)
next_id += 1
return item
@app.get("/todos", response_model=list[TodoResponse])
def list_todos():
return todos_db
@app.get("/todos/{todo_id}")
def get_todo(todo_id: int):
for t in todos_db:
if t["id"] == todo_id:
return t
raise HTTPException(status_code=404, detail="Not found")
@app.put("/todos/{todo_id}")
def update_todo(todo_id: int, todo: TodoCreate):
for i, t in enumerate(todos_db):
if t["id"] == todo_id:
todos_db[i] = {"id": todo_id, **todo.model_dump()}
return todos_db[i]
raise HTTPException(status_code=404, detail="Not found")
@app.delete("/todos/{todo_id}")
def delete_todo(todo_id: int):
global todos_db
todos_db = [t for t in todos_db if t["id"] != todo_id]
return {"deleted": todo_id}
动手练习
练习 1:User 模型
定义 UserCreate 和 UserResponse
class UserCreate(BaseModel):
name: str
email: str
age: int | None = None
class UserResponse(BaseModel):
id: int
name: str
email: str
查看答案
参考答案
# Optional 字段 = None 表示可选
练习 2:错误处理
给 API 加 404 处理
raise HTTPException(status_code=404, detail="用户不存在")
查看答案
参考答案
# 自动返回 {"detail": "..."}
练习 3:CRUD 接口
实现完整的 Todo CRUD
# POST /todos 创建
# GET /todos 列表
# GET /todos/1 详情
# PUT /todos/1 更新
# DELETE /todos/1 删除
查看答案
打卡验收
打卡方式: 全部勾选后,告诉我 "Day 16 打卡",并贴出你的代码。