Pydantic 与 FastAPI 的结合使用是现代 Python Web 开发中的最佳实践之一。FastAPI 本身内置了对 Pydantic 的深度集成,使得数据验证、序列化和 API 文档生成变得非常简单。

数据模型定义

在 FastAPI 中,通常使用 Pydantic 的 BaseModel 来定义 API 请求和响应的数据结构:

from pydantic import BaseModel
from typing import Optional
from fastapi import FastAPI

class User(BaseModel):
    id: int
    name: str
    email: Optional[str] = None

class UserCreate(BaseModel):
    name: str
    email: str

路由参数验证

FastAPI 会自动使用 Pydantic 模型来验证传入的请求数据:

app = FastAPI()

@app.post("/users/")
async def create_user(user: UserCreate):
    FastAPI 自动验证 user 参数是否符合 UserCreate 模型
    return user

请求体验证

当客户端发送 JSON 数据时,FastAPI 会自动将数据解析为 Pydantic 模型对象:

@app.post("/users/")
async def create_user(user: UserCreate):
    user 参数已经是一个 UserCreate 实例
    包含了类型检查和数据验证
    return {"message": "User created", "user": user}

响应模型

FastAPI 也支持使用 Pydantic 模型作为响应模型,自动进行序列化:

@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int):
    返回的 User 对象会自动转换为 JSON 响应
    return User(id=user_id, name="John", email="john@example.com")

自动文档生成

由于 FastAPI 与 Pydantic 的深度集成,API 文档会自动包含数据模型的详细信息,包括字段类型、约束和示例数据。

这种结合使用方式的优势在于:数据验证在运行时自动完成,类型提示提供了良好的开发体验,同时还能生成交互式 API 文档。

百度AI生成,内容仅供参考加粗样式

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐