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

FastAPI接口返回500错误的原因及修复方案

FastAPI接口返回500错误(ResponseValidationError)修复方案

问题场景

我定义了以下Pydantic数据库模型:

class NewsBase(BaseModel):
    title: str
    topic: str


class NewsCreate(NewsBase):
    datetime: datetime


class News(NewsBase):
    id: int
    datetime: datetime

    class Config:
        orm_mode = True

编写了查询接口:

@app.get("/news/find_by_topic/{topic}", response_model=schemas.News)
def find_news_by_topic(topic: str, db: Session = Depends(get_db)):
    db_news = crud.get_news_by_topic(db, topic=topic)
    if db_news is None:
        raise HTTPException(status_code=404, detail="This title is not found")
    return db_news

Crud层代码:

def get_news_by_topic(db: Session, topic: str):
    return db.query(models.News).filter(models.News.topic == topic).all()

调用接口后返回500错误,核心报错为fastapi.exceptions.ResponseValidationError。

错误原因

  1. 类型不匹配:Crud层用.all()返回的是新闻列表(即使仅一条数据),但接口指定response_model=schemas.News要求返回单个新闻对象,FastAPI无法完成列表到单个对象的转换,触发验证错误。
  2. 判断逻辑失效:.all()查询无结果时返回空列表[],而非None,导致原代码中if db_news is None的判断永远不会触发,空列表会被继续返回,进一步加剧验证错误。

修复方案

根据接口需求选择对应方案:

方案1:仅返回符合topic的第一条新闻

  • 修改Crud层代码,将.all()替换为.first():
def get_news_by_topic(db: Session, topic: str):
    return db.query(models.News).filter(models.News.topic == topic).first()
  • 接口判断逻辑保持不变,.first()无结果时返回None,会正确触发404异常。

方案2:返回所有符合topic的新闻

  • 修改接口的response_model为列表类型(需先导入List):
from typing import List

@app.get("/news/find_by_topic/{topic}", response_model=List[schemas.News])
def find_news_by_topic(topic: str, db: Session = Depends(get_db)):
    db_news = crud.get_news_by_topic(db, topic=topic)
    if not db_news:  # 空列表用`not`判断
        raise HTTPException(status_code=404, detail="No news found for this topic")
    return db_news
  • Crud层的.all()保持不变,确保返回列表数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:31:25