多个请求体参数
python
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
class User(BaseModel):
username: str
full_name: str | None = None
@app.put("/items")
async def update_item(item: Item, user: User):
results = {"item": item, "user": user}
return results
当函数有多个请求实体(多个 Pydantic 模型参数),将使用参数名称作为请求体中的键(字段名称),并期望一个类似于以下内容的请求体
python
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
},
"user": {
"username": "dave",
"full_name": "Dave Grohl"
}
}
请求体中的单一值
假如为了拓展先前的模型,除了user和item之外,在请求体中增加一个字段importance,需要使用Body来声明,不然会被当做查询参数
python
from fastapi import FastAPI, Body
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
class User(BaseModel):
username: str
full_name: str | None = None
@app.put("/items")
async def update_item(item: Item, user: User, importance: int = Body()):
results = {"item": item, "user": user, "importance": importance}
return results
python
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
},
"user": {
"username": "dave",
"full_name": "Dave Grohl"
},
"importance": 5
}
嵌入单个请求体实参
假如只有一个来自的模型Item,如果你希望它期望一个拥有 item
键并在值中包含模型内容的 JSON,就像在声明额外的请求体参数时所做的那样。比如下面这样的。
python
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
}
而不是这样的。
python
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
则可以使用一个特殊的 Body
参数 embed
python
from typing import Annotated
from fastapi import Body, FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
results = {"item_id": item_id, "item": item}
return results
声明模型属性
和使用Query,Path,Body在路径操作函数中声明参数校验和元数据的方式相同,可以使Pydantic 的Field在模型内部进行声明校验和元数据
python
from typing import Annotated
from fastapi import Body, FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = Field(
default=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 = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Annotated[Item, Body(embed=True)]):
results = {"item_id": item_id, "item": item}
return results