from typing import Optional import uvicorn from fastapi import Body, 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, importance: int = Body(...) ): results = {"item_id": item_id, "item": item, "user": user, "importance": importance} return results if __name__ == "__main__": uvicorn.run(app="8_Body:app", host="127.0.0.1", port=8080, reload=True, debug=True)
{ "item": { "name": "Foo", "description": "The pretender", "price": 42.0, "tax": 3.2 }, "user": { "username": "dave", "full_name": "Dave Grohl" }, "importance": 5 }
Request Body 中多了个 importance
from typing import Optional import uvicorn from fastapi import Body, FastAPI, Path, Query 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("/item_all/{item_id}") async def update_item( *, item_id: int = Path(default=..., description="路径参数", gt=0, lt=10), address: str = Query(default=None, description="查询参数", max_length=10), item: Item, user: User, importance: int = Body(default=..., description="请求体", ge=1, le=5) ): results = { "item_id": item_id, "address": address, "item": item, "user": user, "importance": importance } return results
当函数只有一个参数指定了 Pydantic Model 且没有其他 Body 参数时,传参的时候请求体可以不指定参数名
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, item: Item): ...
期望得到的请求体
{ "name": "Foo", "description": "The pretender", "price": 42.0, "tax": 3.2 }
默认并不需要指定 item 为字段名
那假设想指定 item 为请求体的字段名呢?就是通过 embed 参数达到目的了
from typing import Optional from fastapi import Body, FastAPI 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, # 将 embed 设置为 True item: Item = Body(..., embed=True)): results = {"item_id": item_id, "item": item} return results
{ "item": { "name": "Foo", "description": "The pretender", "price": 42.0, "tax": 3.2 } }
原文:https://www.cnblogs.com/poloyy/p/15311416.html