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
相关产品推荐
相关产品推荐

