可以通过使用 Pydantic 的 Field
类来指定字段的别名(alias),从而修改 json 输出的字段名称。例如:
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class ItemOut(BaseModel):
name: str
description: str
price: float
tax: float = Field(..., alias="sales_tax")
@app.post("/items/")
async def create_item(item: ItemOut):
return {"item": item}
在上面的示例中,ItemOut
的 tax
字段通过 Field
类的 alias
参数指定了别名 sales_tax
,因此在输出 json 中该字段的名称将为 sales_tax
而不是 tax
。
另外,还可以使用 Pydantic 的 schema_extra
参数来指定整个模型的别名,例如:
class ItemOut(BaseModel):
name: str
description: str
price: float
tax: float
class Config:
schema_extra = {
"example": {
"name": "Foo",
"description": "Bar",
"price": 10.0,
"sales_tax": 1.5
}
}
在上面的示例中,通过在 Config
中使用 schema_extra
参数,并给出包含别名的示例 json 数据,可以让 FastAPI 自动生成正确的 API 文档,并在文档中使用别名。