0%

FastAPI自学教程(9) 请求体多参数处理

1. 混合参数声明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from fastapi import FastAPI, Path, Body
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
name: str
price: float
tax: float | None = None

@app.put("/items/{item_id}")
async def update_item(
item_id: int = Path(..., ge=0, le=1000),
q: str | None = None,
item: Item | None = None
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
if item:
results.update({"item": item})
return results
  • 同时支持路径参数、查询参数和请求体参数声明
  • 路径参数验证支持数值范围约束(ge/le)
  • 请求体参数通过 None 设置可选性

2. 多请求体参数处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Item(BaseModel):
name: str
description: str | None = None

class User(BaseModel):
username: str
full_name: str | None = None

@app.put("/items/{item_id}")
async def update_item(
item_id: int,
item: Item,
user: User
):
return {"item_id": item_id, "item": item, "user": user}
  • 支持多个Pydantic模型作为请求体参数
  • 请求参数以参数名: Model结构传递
  • 请求体需使用键值对格式(如{"item": {}, "user": {}}

3. 单一值嵌入请求体

1
2
3
4
5
6
@app.put("/items/{item_id}")
async def update_item(
item_id: int,
item: Item = Body(..., embed=True)
):
return {"item_id": item_id, "item": item}
  • embed=True 强制请求体使用键包装
  • 默认请求体格式:{"name": "Foo", ...}
  • 嵌入后格式:{"item": {"name": "Foo", ...}}

4. 字段级验证

1
2
3
4
5
6
7
from pydantic import Field

class Item(BaseModel):
name: str = Field(..., min_length=3)
price: float = Field(gt=0,
description="必须大于0的价格")
tags: list[str] = []
  • 使用Field实现字段级验证
  • 支持约束类型:
    • 数值范围(gt/ge/lt/le)
    • 字符串长度(min_length/max_length)
    • 正则表达式(regex参数)
    • 自定义描述(description)

5. 嵌套模型

1
2
3
4
5
6
7
8
class Image(BaseModel):
url: str
name: str

class Item(BaseModel):
name: str
images: list[Image] | None = None
tags: dict[str, str] = {}
  • 支持多层嵌套模型
  • 复杂类型支持:
    • 列表类型(list[Model])
    • 字典类型(dict[key_type, value_type])
    • 联合类型(Union)
    • 特殊类型(HttpUrl等)

6. 文档支持

  • 交互式文档自动展示:
    • 参数类型约束说明
    • 字段验证规则可视化
    • 嵌套模型结构树展示
    • 错误响应示例(HTTP 422)
  • 通过example参数添加示例值:
    1
    2
    Item = Body(...,
    example={"name": "Foo", "price": 35.4})

提示:使用Annotated语法(FastAPI ≥0.95.1)可增强代码可读性,旧版兼容写法通过Query()/Body()直接添加验证规则。通过/docs可实时测试多参数请求体交互。