FastAPI学习-8.POST请求body中添加Field

前言

与使用 Query、Path 和 Body 在路径操作函数中声明额外的校验和元数据的方式相同,你可以使用 Pydantic 的 Field 在 Pydantic 模型内部声明校验和元数据。

Field 字段参数说明

关于 Field 字段参数说明

  • Field(None) 是可选字段,不传的时候值默认为None
  • Field(...) 是设置必填项字段
  • title 自定义标题,如果没有默认就是字段属性的值
  • description 定义字段描述内容
from pydantic import BaseModel, Field


class Item(BaseModel):
    name: str
    description: str = Field(None,
                             title="The description of the item",
                             max_length=10)
    price: float = Field(...,
                         gt=0,
                         description="The price must be greater than zero")
    tax: float = None


a = Item(name="yo yo",
         price=22.0,
         tax=0.9)
print(a.dict())  # {'name': 'yo yo', 'description': None, 'price': 22.0, 'tax': 0.9}

导入 Field

是从 pydantic 导入 Field

from typing import Optional

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[str] = Field(
        None, title="The description of the item", max_length=300
    )
    price: float = Field(..., gt=0, description="The price must be greater than zero")
    tax: Optional[float] = None


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item = Body(..., embed=True)):
    results = {"item_id": item_id, "item": item}
    return results

注意,Field 是直接从 pydantic 导入的,而不是像其他的(Query,Path,Body 等)都从 fastapi 导入。

总结
你可以使用 Pydantic 的 Field 为模型属性声明额外的校验和元数据。
你还可以使用额外的关键字参数来传递额外的 JSON Schema 元数据。

posted @   上海-悠悠  阅读(461)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-03-03 面试题-python 如何读取一个大于 10G 的txt文件?
点击右上角即可分享
微信分享提示