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

FastAPI返回{"posts": posts}触发list类型验证错误排查

解决FastAPI返回{"posts": posts}时的"value is not a valid list"错误

问题原因

你路由中指定的response_model = List[schemas.PostResponseSchema]要求接口返回列表类型的数据,但你实际返回的是包含posts字段的字典{"posts": posts},字典与列表类型不匹配,触发了类型验证错误。

直接返回posts能正常运行,是因为db.query(models.Post).all()返回的本身就是列表,完全符合List[schemas.PostResponseSchema]的类型要求,FastAPI可以正确完成序列化。

解决办法

办法1:修改响应模型适配字典返回格式

如果需要保持{"posts": posts}的返回结构,需创建新的响应模型类包裹列表:

from pydantic import BaseModel
from typing import List
import schemas

class PostListResponseSchema(BaseModel):
    posts: List[schemas.PostResponseSchema]
    
    class Config:
        orm_mode = True

然后更新路由的response_model:

@router.get('', response_model = schemas.PostListResponseSchema)
def get_posts(db : Session = Depends(get_db)):
    posts = db.query(models.Post).all()
    return {"posts" : posts}

办法2:保持原响应模型,直接返回列表

如果不需要字典包裹,直接返回查询到的posts列表即可:

@router.get('', response_model = List[schemas.PostResponseSchema])
def get_posts(db : Session = Depends(get_db)):
    posts = db.query(models.Post).all()
    return posts

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:55:14