FastAPI 请求体
作者:互联网
多个参数
混用Path、Query和请求体参数
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.put("/items/{item_id}")
async def update_item(
*,
item_id: int = Path(..., title = "The ID of the item to get", ge=0, le=1000),
q: Optional[str] = None,
item: Optional[Item] = None
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
if item:
results.update({"item": item})
return results
多个请求体参数
上例中,路径操作预期JSON请求体中的Item
包含如下属性:
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
但也可以声明多个请求体参数,例如item
和user
:
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
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):
results = {"item_id": item_id, "item": item, "user": user}
return results
本例中,FastAPI能够识别函数中有多个请求体参数,因此,它把参数名作为请求体的键,并返回如下请求体:
{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
},
"user": {
"username": "dave",
"full_name": "Dave Grohl"
}
}
fastapi会自动转换请求中的数据,因此item
和user
参数会接收指定的内容。
标签:None,请求,FastAPI,results,item,str,Optional,id 来源: https://www.cnblogs.com/litianming/p/16224287.html