调用/api/contest/problems接口返回422错误的原因排查
问题:POST请求
/api/contest/problems返回422错误,提示contest_id无法解析为整数 向/api/contest/problems发送POST请求时,收到422(无法处理的实体)错误,提示contest_id无法解析为整数,但实际请求中contest_id是整数类型。以下是相关信息及错误成因分析:
错误响应
{ "detail": [ { "type": "int_parsing", "loc": [ "path", "contest_id" ], "msg": "Input should be a valid integer, unable to parse string as an integer", "input": "problems", "url": "https://errors.pydantic.dev/2.5/v/int_parsing" } ] }
相关代码与配置
端点代码
@router.get("/api/contest/problems", tags=["Contest Problem"]) def get_all_contest_problems(db: Session = Depends(get_db)): contest_problems = db.query(ContestProblem).all() if not contest_problems: raise HTTPException(status_code=404, detail="Contest Problems Not Found") return {"status" : "ok","data" : contest_problems}
数据库模型
class Contest(Base): __tablename__ = "contests" id = Column(Integer, primary_key=True, index=True, autoincrement=True) # some attribute created_at = Column(DateTime, default=lambda: datetime.utcnow() + timedelta(hours=7)) class ContestProblem(Base): __tablename__ = "contest_problems" id = Column(Integer, primary_key=True, index=True, autoincrement=True) contest_id = Column(Integer, ForeignKey("contests.id")) title = Column(String(255)) # some attribute updated_at = Column(DateTime, default=lambda: datetime.utcnow() + timedelta(hours=7)) back_populates="contest_problems")
SQL Schema
CREATE TABLE `contest_problems` ( `id` bigint(20) UNSIGNED NOT NULL, `contest_id` bigint(20) UNSIGNED NOT NULL, `title` varchar(255) NOT NULL, -- some attribute `updated_at` timestamp NULL DEFAULT NULL ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci;
错误成因分析
- 路由匹配错误:你的代码中只定义了
GET /api/contest/problems的端点,但你发送的是POST请求。此时FastAPI会在所有POST路由中寻找匹配项,而你的项目中应该存在另一个类似POST /api/contest/{contest_id}的路由定义——这个路由的路径参数contest_id被期望是整数,但当你请求/api/contest/problems时,FastAPI会把路径中的problems当作contest_id的输入值,自然无法将字符串解析为整数,从而抛出422错误。 - 请求方法不匹配:现有端点是GET方法,但你使用POST请求访问,这本身就不符合路由定义,导致FastAPI无法匹配到正确的处理函数,进而误匹配到其他带路径参数的路由。
- 额外注意:数据库模型中
ContestProblem类的back_populates语句存在语法错误(多了闭合括号),但这不是当前422错误的直接原因,修复后可避免后续ORM操作问题。
内容的提问来源于stack exchange,提问作者Papazy
相关产品推荐
相关产品推荐

