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 都是可选非必传
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
{ "item": { "name": "Foo", "description": "The pretender", "price": 42.0, "tax": 3.2 }, "user": { "username": "dave", "full_name": "Dave Grohl" } }
原文:https://www.cnblogs.com/poloyy/p/15310358.html