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

FastAPI接口else分支无法正确匹配ID返回404响应问题排查

FastAPI单帖子查询接口逻辑异常排查

问题现象

代码运行无语法报错,硬编码的my_posts列表中确实存在id为2的帖子数据,但访问路由http://127.0.0.1:8000/posts/2时,接口直接返回404错误响应,未返回预期的帖子数据。

问题复现代码

my_posts = [
    {
        "title":"Title of post 1",
        "content":"content of post 1",
        "id":1
    },
    {
        "title":"Title of post 2",
        "content":"content of post 2",
        "id":2
    }
]

@app.get("/posts/{id}")
def get_post(id:int):
    for p in my_posts:
        if p['id'] == id:
            return {"data":p}
        else:
            return {"detail":"404 error, data not found"}

根因分析

逻辑错误出在循环内的分支判断位置:

  • else分支直接和单次循环内的if判断绑定,只要遍历到的第一个元素和传入id不匹配,就会立刻触发return终止整个函数,列表内后续的元素完全不会被遍历。
  • 传入id=2发起请求时,循环第一次读取的是id=1的帖子,判断id不相等就直接走else分支返回404,根本没有执行到遍历第二条帖子的逻辑。

修复方案

将404返回逻辑移到整个for循环执行完成之后,只有遍历完所有帖子都没匹配到对应id时,才返回404:

@app.get("/posts/{id}")
def get_post(id:int):
    for p in my_posts:
        if p['id'] == id:
            return {"data":p}
    # 全量遍历完未触发return,说明无匹配数据
    return {"detail":"404 error, data not found"}

如果要符合标准HTTP状态码规范,推荐使用FastAPI内置的HTTPException抛出404异常,响应会自动携带正确的404状态码:

from fastapi import HTTPException, status

@app.get("/posts/{id}")
def get_post(id:int):
    for p in my_posts:
        if p['id'] == id:
            return {"data":p}
    raise HTTPException(
        status_code=status.HTTP_404_NOT_FOUND,
        detail="post not found"
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 08:24:10