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

FastAPI 0.100.x与Pydantic v2重复查询参数模式验证失败问题

解决Pydantic v2 + FastAPI 0.100.x中列表查询参数的元素正则验证问题

修复后的代码

from fastapi import Query
from typing import Annotated
from pydantic import Pattern

# 替换为你的正则表达式
REGEX_EXPR = r"^[a-zA-Z0-9_-]+$"

@app.post("/my/endpoint")
async def my_endpoint_function(
    list_with_query_values: Annotated[
        list[Annotated[str, Pattern(REGEX_EXPR)]],
        Query()
    ]
):
    pass

或者使用StringConstraints实现相同效果:

from fastapi import Query
from typing import Annotated
from pydantic import StringConstraints

REGEX_EXPR = r"^[a-zA-Z0-9_-]+$"

@app.post("/my/endpoint")
async def my_endpoint_function(
    list_with_query_values: Annotated[
        list[Annotated[str, StringConstraints(pattern=REGEX_EXPR)]],
        Query()
    ]
):
    pass

问题原因

Pydantic v2重构了嵌套类型的验证流程,原写法中直接把pattern参数放在Query里,会被当作对整个列表对象的验证规则(而列表不是字符串类型,因此抛出TypeError)。现在需要明确将元素级别的验证约束绑定到列表的元素类型上:

  • 内层Annotated[str, Pattern(...)]负责校验列表中的每个字符串是否符合正则规则
  • 外层Query()仅负责处理查询参数的收集逻辑(比如多参数转列表、必填性、别名等)

这种写法既保留了你想要的简洁风格,又完全兼容Pydantic v2和新版FastAPI的验证机制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:53:10