FastAPI(9)- 多个 Request Body
Path、Query、Request Body 混合使用
from fastapi import FastAPI, Path, Query from typing import Optional from pydantic import BaseModel import uvicorn 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(default=..., description="item_id", gt=1, lt=20, example=2), name: Optional[str] = Query(default=None, description="查询参数", min_length=0, max_length=20, example="示例值"), item: Optional[Item] = None ): results = {"item_id": item_id} if name: results.update({"name": name}) if item: results.update({"item": item}) return results if __name__ == "__main__": uvicorn.run(app="7_multiple_parameters:app", host="127.0.0.1", port=8080, reload=True, debug=True)
除了路径参数 item_id 是必传的,查询参数 name 和请求体 item 都是可选非必传
只传路径参数的请求结果
路径参数、查询参数、请求体均传递的请求结果
查看 Swagger API 文档
多个 Request Body
from typing import Optional from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() # 自定义模型类 1 class Item(BaseModel): name: str description: Optional[str] = None price: float tax: Optional[float] = None # 自定义模型类 2 class User(BaseModel): username: str full_name: Optional[str] = None @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item, # 指定第一个 Model 类型 user: User): # 指定第二个 Model 类型 results = { "item_id": item_id, "item": item, "user": user } return results
- 这种情况下,FastAPI 会注意到函数中有两个 Request Body,因为这 item、user 两个参数都指定了 Pydantic 模型
- FastAPi 将使用参数名作为 Request Body 中的键(字段名称)
期望得到的 Request Body
{ "item": { "name": "Foo", "description": "The pretender", "price": 42.0, "tax": 3.2 }, "user": { "username": "dave", "full_name": "Dave Grohl" } }
正确传参的请求结果
查看 Swagger API 文档