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

FastAPI GET方法开发搜索接口时出现422 Unprocessable Entity错误

图书搜索功能422 Unprocessable Entity报错排查

关联实现代码

路由层(ROUTERS)

@router.get('/search')
def search(query: Optional[str], db: Session = Depends(get_db)):
    return librarian.search_book(query, db)

业务逻辑层(LIBRARIAN)

def search_book(query: Optional[str], db: Session = Depends(get_db)):
    res = db.query(models.Book).filter(models.Book.title.contains(query)).all()
    return res

数据模型层(MODELS)

class Book(Base):
    __tablename__ = "book"

    id = Column(Integer, primary_key=True, index=True)
    isbn = Column(String)
    title = Column(String)
    description = Column(String)
    author = Column(String)
    status_peminjaman = Column(Boolean, default=False)
    tanggal_peminjaman = Column(Date, default=null, nullable=True)

报错根因

该报错由GET请求参数传递方式错误引发:

  • FastAPI会自动从URL查询字符串中解析GET接口声明的普通参数,不会主动解析GET请求的请求体内容
  • 若将query参数放在请求体中传递,FastAPI无法从预期位置获取到参数,就会触发422 Unprocessable Entity参数校验错误

修复方法

  • 符合HTTP规范的调用方式:将搜索关键词拼接在接口URL后传递,格式为/search?query=你要搜索的图书名,不要在GET请求中携带请求体
  • 若业务场景必须通过请求体传参,将接口请求方法改为@router.post('/search'),同时定义对应Pydantic模型接收请求体参数即可,注意这种方式不符合GET请求的语义规范,非必要不使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 20:01:02