· 约 2 分钟

09-FastAPI基础入门-请求体参数_Field类型注解

  • FastAPI
  • Python

学习目标

核心概念

Field 是给请求体模型中的字段增加元信息和校验规则的工具,和 PathQuery 的思路很像。

它适合做这些事:

代码示例

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class ItemCreate(BaseModel):
    name: str = Field(min_length=2, max_length=30, description="商品名称")
    price: float = Field(gt=0, description="商品价格,必须大于 0")
    stock: int = Field(default=0, ge=0, description="库存数量")


@app.post("/items")
def create_item(item: ItemCreate):
    return item.model_dump()

规则示例

实际意义

如果你不写这些规则,很多错误会拖到数据库层或业务层才暴露。
如果你在 Field 就写清楚,错误会更早、也更容易发现。

易错点

例如:

stock: int = Field(...)

这里 ... 表示必填。

我的补充

Field 的价值不仅是“防错”,还在于让接口文档更像正式产品文档。
后端给前端的合作体验,很多时候就体现在这些细节上。