Body - Fields
和路径操作函数 Query,Path,Body 一样,可以在 Pydantic 模型中使用 Field 添加验证信息和元信息
Import Field
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
    name: str
    description: str = Field(None, title="The description of the item", max_length=300)
    price: float = Field(..., gt=0, description="The price must be greater than zero")
    tax: float = None
@app.put("/items/{item_id}")
async def update_item(*, item_id: int, item: Item = Body(..., embed=True)):
    results = {"item_id": item_id, "item": item}
    return results
注意:Field 参数直接由 pydantic导入,而不是来自 FastAPI
提示: Field 提供和 Query 等一样的 api
技术细节:
Query,Path等都会创建Param子类的实例,而Param又继承于pydantic的FieldInfoField也会返回FieldInfo的实例Body也会返回FieldInfo子类的实例,包括Body的子类等从
fastapi导入的Query,Path等等都是返回特殊类的函数