learn from https://fastapi.tiangolo.com/zh/tutorial/body-multiple-params/
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
class Item1(BaseModel):
name: str
price: float
description: Optional[str] = None
tax: Optional[float]
@app.put("/items/{item_id}")
async def update_item(
*,
item_id: int = Path(..., title="id of item to get", ge=0, le=1000),
q: Optional[str] = None,
item: Optional[Item1] = None,
):
res = {"item_id": item_id}
if q:
res.update({"q": q})
if item:
res.update({"item": item})
return res
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
description: Optional[str] = None
tax: Optional[float]
class User(BaseModel):
username: str
full_name: Optional[str] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User):
res = {"item_id" : item_id, "item" : item, "user": user}
return res
varname : type = Body(...)
,如果不这么写,会被作为查询参数 ?varname=xxx
from fastapi import Body
class Item(BaseModel):
name: str
price: float
description: Optional[str] = None
tax: Optional[float]
class User(BaseModel):
username: str
full_name: Optional[str] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item, user: User, importance : int = Body(...)):
res = {"item_id" : item_id, "item" : item, "user": user}
return res
现在可以写在请求体内:
由于默认情况下单一值被解释为查询参数,因此你不必显式地添加 Query,你可以仅执行操作:q: str = None
如果你只有一个请求体参数
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
res = {"item_id" : item_id, "item" : item}
return res
你的请求体需要写成如下形式:
如果你想写成 带 key 的 json 形式,添加一个传入参数 embed,item: Item = Body(..., embed=True)
可以使用 Pydantic
的 Field
在 Pydantic 模型
内部声明校验和元数据
from fastapi import FastAPI, Path, Body
from typing import Optional
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
name: str
price: float = Field(..., gt=0, description="price must be greater than 0")
description: Optional[str] = Field(None, title="description of item", max_length=30)
tax: Optional[float] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
res = {"item_id" : item_id, "item" : item}
return res
Field
的工作方式和 Query、Path 和 Body 相同,包括它们的参数等等也完全相同
将一个属性定义为拥有子元素的类型,如 list
class Item(BaseModel):
name: str
price: float = Field(..., gt=0, description="price must be greater than 0")
description: Optional[str] = Field(None, title="description of item", max_length=30)
tax: Optional[float] = None
tags: list = [] # 没有声明元素类型
from typing import List
tags: List[str] = []
from fastapi import FastAPI, Path, Body
from typing import Optional, List, Set
from pydantic import BaseModel, Field
app = FastAPI()
class Image(BaseModel):
url:str
name: str
class Item(BaseModel):
name: str
price: float = Field(..., gt=0, description="price must be greater than 0")
description: Optional[str] = Field(None, title="description of item", max_length=30)
tax: Optional[float] = None
tags: Set[str] = []
image: Optional[Image] = None
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
res = {"item_id" : item_id, "item" : item}
return res
HttpUrl
,检查是不是有效的 URLfrom pydantic import BaseModel, Field, HttpUrl
app = FastAPI()
class Image(BaseModel):
url: HttpUrl
name: str
则上面的输入应改的地方 "url":"http://www.michael.com",
否则不是有效的 URL
image: Optional[List[Image]] = None
输入需要改为
@app.post("/images/multiple/")
async def create_multiple_images(images: List[Image]):
return images
from typing import Optional, List, Set, Dict
@app.post("/index-weights/")
async def create_index_weights(weights: Dict[int, float]):
# key 为 int, value 为浮点
return weights
请记住 JSON 仅支持将 str
作为键。 但是 Pydantic 具有自动转换数据的功能。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有