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

FastAPI结合Pydantic Schema用response_model返回时出现ValidationError问题

问题分析与解决步骤

错误原因

  1. response_model 与返回结构不匹配:你设置的response_model=Retrieval,但实际返回的是{"myres": results},而Retrieval仅定义了url字段。Pydantic会尝试将返回的字典解析为Retrieval实例,但该字典没有url字段,因此触发field required校验错误。
  2. Pydantic配置项错误:Retrieval的Config中写的是orm_model = True,但Pydantic v1的正确配置项是orm_mode = True,该配置用于将SQLAlchemy ORM对象转换为Pydantic模型,写错会导致ORM对象无法被正确解析。
  3. 缺少顶层响应模型:你期望返回包含myres列表的结构,但当前仅定义了单个条目的Retrieval模型,没有匹配顶层结构的模型。

解决方法

  1. 修正Pydantic配置项:将Retrieval的Config中的orm_model改为orm_mode。
  2. 定义顶层响应模型:创建包含myres字段的模型,该字段类型为List[Retrieval],匹配你期望的返回结构。
  3. 更新接口的response_model:将接口的response_model改为新定义的顶层模型。
  4. 保持返回结构与模型一致:继续返回{"myres": results},FastAPI会自动将SQLAlchemy ORM对象列表转换为Retrieval实例列表。

修正后的完整代码

from fastapi import FastAPI, status, Depends
from typing import Optional, List
from sqlalchemy.orm import Session
from pydantic import BaseModel

from .database import get_db
import models

class InputSchema(BaseModel):
    url: str
    param1: Optional[str] 
    # ...

class Retrieval(BaseModel):
    url: str  # url是主键,非空

    class Config:
        orm_mode = True  # 修正配置项名称

# 新增顶层响应模型,匹配期望的返回结构
class RetrievalResponse(BaseModel):
    myres: List[Retrieval]

@app.post("/get_something", status_code=status.HTTP_201_CREATED, response_model=RetrievalResponse)
async def get_some(input_params: InputSchema, db: Session = Depends(get_db)):
    query = db.query(models.Entries).filter(models.Entries.param1 == input_params.param1)
    results = query.all()
    return {"myres": results}

效果验证

修正后接口会返回符合预期的JSON结构:

{"myres": [{"url": "www.stackoverflow.com"}, {"url":"www.github.com"}]}

内容的提问来源于stack exchange,提问作者skna.1000

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:24:53