0%

FastAPI自学教程(10)- 请求体字段验证

1. 基础字段声明

1
2
3
4
5
6
7
8
9
10
from pydantic import BaseModel, Field

class Item(BaseModel):
name: str
description: str | None = Field(
default=None,
title="商品描述",
max_length=300
)
price: float = Field(gt=0, description="价格必须大于零")
  • 使用 Field() 声明字段级验证规则
  • 支持设置默认值(default=None)创建可选字段
  • 可添加元数据:标题(title)、描述(description)、示例(example)

2. 数值验证规则

1
2
3
class Product(BaseModel):
price: float = Field(..., gt=0, le=10000)
stock: int = Field(ge=0, example=100)
  • 支持四类数值约束:
    • gt:严格大于(>)
    • ge:大于等于(≥)
    • lt:严格小于(<)
    • le:小于等于(≤)
  • 示例值通过 example 参数设置

3. 字符串验证规则

1
2
3
class User(BaseModel):
username: str = Field(min_length=3, max_length=50)
password: str = Field(regex=r"^[A-Za-z\d@$!%*?&]{8,}$")
  • 支持长度约束(min_length/max_length
  • 通过正则表达式(regex)验证格式
  • 无效输入触发 HTTP 422 验证错误

4. Annotated 声明方式

1
2
3
4
5
6
7
8
from typing import Annotated
from fastapi import Body

@app.put("/items/{item_id}")
async def update_item(
item: Annotated[Item, Body(embed=True)]
):
return item
  • 推荐使用 Annotated 包装类型和验证元数据
  • Body(embed=True) 强制请求体使用键包装:
    • 默认格式:{"name": "Foo", ...}
    • 嵌入后格式:{"item": {"name": "Foo", ...}}
  • 兼容旧版直接使用 Field() 的声明方式

5. 文档集成特性

1
2
3
class Item(BaseModel):
name: str = Field(..., example="手机")
price: float = Field(example=2999.0, description="人民币价格,含增值税")
  • 交互式文档自动显示:
    • 字段验证规则
    • 示例值和字段描述
    • 正则表达式模式示例
  • 错误响应包含具体验证失败原因

注意Field 需从 pydantic 导入,与 Query/Path 等 FastAPI 组件来源不同 。通过访问 /docs 可查看完整验证规则说明文档 。