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

如何创建可接收二进制数据POST请求的FastAPI端点

解决方案:接收纯二进制请求体的FastAPI端点

要适配你提供的客户端请求方式(直接将二进制数据放入请求体,而非表单),需要避免使用File/UploadFile(这些依赖表单格式),而是直接读取原始请求体。以下两种方法都能实现需求:

方法1:使用Request对象获取原始二进制数据

直接通过Request对象读取请求体的原始字节,这种方式更灵活,能获取更多请求上下文:

from fastapi import APIRouter, Request, status

router = APIRouter()

@router.post(
    '/upload/',
    status_code=status.HTTP_201_CREATED,
)
async def upload_binary(param1: str, param2: str, request: Request):
    # 读取二进制请求体
    binary_data = await request.body()
    
    # 示例:将数据保存到文件
    with open("received_file.bin", "wb") as f:
        f.write(binary_data)
    
    return {
        "status": "success",
        "param1": param1,
        "param2": param2,
        "received_data_size": f"{len(binary_data)} bytes"
    }

方法2:使用Body参数绑定二进制请求体

通过Annotated和Body指定媒体类型为二进制,让FastAPI直接将请求体解析为bytes类型:

from fastapi import APIRouter, Body, status
from typing import Annotated

router = APIRouter()

@router.post(
    '/upload/',
    status_code=status.HTTP_201_CREATED,
)
def upload_binary(
    param1: str,
    param2: str,
    data: Annotated[bytes, Body(media_type="application/octet-stream")]
):
    # 示例:处理二进制数据
    with open("received_file.bin", "wb") as f:
        f.write(data)
    
    return {
        "status": "success",
        "param1": param1,
        "param2": param2,
        "received_data_size": f"{len(data)} bytes"
    }

为什么之前的方法会返回422错误?

你尝试的三种方式都不符合请求格式:

  • 方法1:data: bytes,FastAPI默认会将其当作JSON请求体中的字段,而客户端发送的是纯二进制,因此解析失败。
  • 方法2/3:File()和UploadFile都依赖表单格式(multipart/form-data),但客户端并未发送表单数据,导致服务器期望与实际请求不匹配。

以上两种方案都能完美适配你提供的requests客户端代码,无需修改客户端逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 05:27:40