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

FastAPI POST请求无法获取numpy数组,遇404错误求助

问题分析与解决

1. 根路径404错误

你的代码里没有定义根路径(/)的路由处理函数,当前仅注册了/check(GET请求)和/predict(POST请求)两个接口。访问http://localhost:8000/时,FastAPI找不到对应处理逻辑,因此返回404。

若要让根路径可访问,添加根路由即可:

@app.get('/')
async def root():
    return {"message": "图像预测API已启动,使用POST /predict上传图片"}

2. 无法返回numpy数组的问题

FastAPI默认无法直接将numpy序列化为JSON格式,你的/predict接口直接返回numpy数组会触发内部错误。需将numpy数组转换为Python原生列表类型:

修改predict函数:

@app.post('/predict')
async def predict(file: UploadFile = File(...)):
    image = read_image(await file.read())
    # 将numpy数组转为可序列化的列表,同时返回图像形状信息
    return {
        "image_shape": image.shape,
        "image_data": image.tolist()
    }

验证步骤

  • 启动服务后,访问http://localhost:8000/check,应正常返回{"message":"hello world"},确认服务运行正常。
  • 通过FastAPI自带的文档界面http://localhost:8000/docs,或Postman、curl等工具,上传图片到/predict接口,即可获取转换后的图像数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 18:40:07