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

FastAPI接口pytest测试返回404 Not Found问题求助

问题原因与解决方案

核心原因

你代码里没有为根路径/定义任何接口处理逻辑,FastAPI不会自动生成默认的根路由,所以当测试请求/时,服务找不到对应的处理函数,返回404错误。

修正后的代码

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

# 新增根路径的接口处理函数
@app.get("/")
def read_main():
    return {"message": "Hello World"}

client = TestClient(app)

def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello World"}

说明

添加@app.get("/")装饰器和对应的read_main函数后,FastAPI会将根路径/绑定到这个处理函数上,测试请求时就能正确返回200状态码和预期的JSON数据,测试即可通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:32:01