多个请求体参数
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 模型参数),将使用参数名称作为请求体中的键(字段名称),并期望一个类似于以下内容的请求体
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
},
"user": {
"username": "dave",
"full_name": "Dave Grohl"
}
}
请求体中的单一值
假如为了拓展先前的模型,除了user和item之外,在请求体中增加一个字段importance,需要使用Body来声明,不然会被当做查询参数
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
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
},
"user": {
"username": "dave",
"full_name": "Dave Grohl"
},
"importance": 5
}
嵌入单个请求体实参
假如只有一个来自的模型Item,如果你希望它期望一个拥有 item
键并在值中包含模型内容的 JSON,就像在声明额外的请求体参数时所做的那样。比如下面这样的。
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
}
而不是这样的。
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
则可以使用一个特殊的 Body
参数 embed
文章来源:https://www.toymoban.com/news/detail-833593.html
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在模型内部进行声明校验和元数据文章来源地址https://www.toymoban.com/news/detail-833593.html
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
到了这里,关于fastApi笔记06-请求体-多个参数的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!