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

FastAPI接口接收list[str]类型字段时返回422错误(提示Input should be a valid list)

FastAPI接口接收list[str]类型字段时返回422错误(提示Input should be a valid list)

问题描述

我用的是FastAPI v0.111.0和Pydantic v2.0.0,定义了下面的Pydantic类:

class Index(File):
    indexes: list[str] | None = Field(default_factory=list, description="List of indexes")

class File:
   id: str = Field("", description="poc id")

对应的路由代码是这样的:

approuter.post("/router")
async def test(data: Index = Depends()):
    try:
        return {"message": f"Success"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

我用VSCode的REST Client发了下面的请求:

POST localhost:5001/router
Content-Type: application/json

{
"indexes":["Test1", "Test2"]
"id": "1"
}

结果收到了422错误,提示**"Input should be a valid list"**,试了好几种JSON写法都没用,想问问怎么解决这个问题?

问题排查与解决办法

咱们一步一步来排查,几个常见的坑你看看有没有踩:

1. JSON语法错误(最容易忽略的点)

你发送的JSON里,"indexes":["Test1", "Test2"]这一行末尾少了个逗号!JSON里键值对之间必须用逗号分隔,正确的JSON应该是这样:

{
  "indexes": ["Test1", "Test2"],
  "id": "1"
}

这个小错误会导致FastAPI没法正确解析请求体,直接触发验证失败,先把这个改了试试。

2. Pydantic模型没继承BaseModel

你的File类没有继承pydantic.BaseModel啊!Pydantic的模型必须继承这个基类才能被识别,不然它根本不知道这是个要验证的模型,子类Index自然也会出问题。修改后的模型应该是:

from pydantic import BaseModel, Field

class File(BaseModel):
   id: str = Field("", description="poc id")

class Index(File):
    indexes: list[str] | None = Field(default_factory=list, description="List of indexes")

这是Pydantic的基础要求,没继承的话字段验证逻辑根本跑不起来。

3. 路由接收请求体的方式不对

你用Depends()来接收Index类型的参数,但FastAPI接收JSON请求体的标准方式是直接把模型作为参数,不需要加Depends()。修改后的路由代码:

@approuter.post("/router")
async def test(data: Index):
    try:
        return {"message": "Success"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

虽然Depends()在某些场景下能用,但直接传模型才是正确接收JSON请求体的做法,这样能保证请求体被正确解析和验证。

总结

按这几个步骤调整后应该就能解决问题了:

  • 修正请求JSON的语法,补上缺失的逗号
  • 确保所有Pydantic模型都继承BaseModel
  • 调整路由参数,直接用模型接收请求体(去掉Depends())

备注:内容来源于stack exchange,提问作者James Jordan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:43:09