在Pydantic模型中添加额外的JSON模式数据
您可以声明Pydantic模型的示例,这些示例将被添加到生成的JSON模式中。
示例代码
from fastapi import FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = Nonemodel_config = {"json_schema_extra": {"examples": [{"name": "Foo","description": "A very nice Item","price": 35.4,"tax": 3.2,}]}}@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):results = {"item_id": item_id, "item": item}return results
这样做的好处就是,我们在请求在线文档的时候,可以直接看到示例数据
效果
在Field字段中添加example
示例代码
from typing import Unionfrom fastapi import FastAPI
from pydantic import BaseModel, Fieldapp = FastAPI()class Item(BaseModel):name: str = Field(examples=["Foo"])description: Union[str, None] = Field(default=None, examples=["A very nice Item"])price: float = Field(examples=[35.4])tax: Union[float, None] = Field(default=None, examples=[3.2])@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):results = {"item_id": item_id, "item": item}return results
效果
请求体示例
from typing import Annotated, Unionfrom fastapi import Body, FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = None@app.put("/items/{item_id}")
async def update_item(item_id: int,item: Annotated[Item,Body(examples=[{"name": "Foo","description": "A very nice Item","price": 35.4,"tax": 3.2,}],),],
):results = {"item_id": item_id, "item": item}return results
效果也是一样的
你甚至可以定义多个示例
from typing import Annotated, Unionfrom fastapi import Body, FastAPI
from pydantic import BaseModelapp = FastAPI()class Item(BaseModel):name: strdescription: Union[str, None] = Noneprice: floattax: Union[float, None] = None@app.put("/items/{item_id}")
async def update_item(*,item_id: int,item: Annotated[Item,Body(examples=[{"name": "Foo","description": "A very nice Item","price": 35.4,"tax": 3.2,},{"name": "Bar","price": "35.4",},{"name": "Baz","price": "thirty five point four",},],),],
):results = {"item_id": item_id, "item": item}return results