You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI联合使用Field和constr时出现JSON序列化错误如何解决?

错误原因

你错误地将constr返回的类型对象作为默认值传入了Field的第一个参数:

  • Field的第一个位置参数是字段的默认值,需要传入符合字段类型的有效值
  • constr(...)返回的是带约束的字符串类型对象,不是合法的字符串默认值
    Pydantic生成OpenAPI Schema时需要将字段默认值序列化到JSON结构中,类型对象无法被JSON序列化,因此抛出该错误。
解决方法

有两种等价的正确写法可以实现你要的「去除首尾空格、最小长度10、最大长度20」的约束效果:

方法1:直接使用constr作为字段类型

from fastapi import FastAPI
from pydantic import BaseModel, constr

app = FastAPI()

class CoolModel(BaseModel):
    # 直接将constr作为类型标注,不需要额外加Field
    this: constr(strip_whitespace=True, min_length=10, max_length=20)

@app.get("/", response_model=CoolModel)
async def something(some_model: CoolModel):
    return some_model

方法2:将约束参数全部传入Field

如果你需要用Field添加描述、示例等额外配置,可以把所有约束参数放到Field中,类型标注直接写str:

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class CoolModel(BaseModel):
    # 不需要使用constr,所有约束都可以直接传入Field
    this: str = Field(min_length=10, max_length=20, strip_whitespace=True)

@app.get("/", response_model=CoolModel)
async def something(some_model: CoolModel):
    return some_model

如果需要设置默认值,只需要把默认值作为第一个参数传入Field即可,比如默认值为"test_default"的写法:

this: str = Field("test_default", min_length=10, max_length=20, strip_whitespace=True)

内容的提问来源于stack exchange,提问作者Yash Nag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:06:01