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

FastAPI中如何通过请求体发送三维浮点列表并保留Pydantic验证?

问题

我用FastAPI定义了如下接口:

@app.post(
    "/my_endpoint",
)
async def my_endpoint(
    my_matrix: list[list[list[float]]],
):
    print(my_matrix)

但不管是通过Swagger UI还是用Python的requests(TestClient)都没法成功发送请求,请求代码如下:

client = TestClient(app)
headers = {"accept": "application/json"}
params = {}
files = [
    ("my_matrix", (None, '[[[0.01, 0.32],[0.291, 0.239]]]')),
]

response = client.post(
    "/my_endpoint",
    params=params,
    files=files,
    headers=headers,
)

返回的错误信息:

[
 {
  'input': '[[[0.01, 0.32],[0.291, 0.239]]]',
  'loc': [
      'body',
      'my_matrix',
      0
  ],
  'msg': 'Input should be a valid list',
  'type': 'list_type',
  'url': 'https://errors.pydantic.dev/2.5/v/list_type'
 }
]

我知道可以通过JSON发送数据,但想了解能不能在保留Pydantic模型验证的同时,通过请求体发送这类数据。

解决方案

问题出在你用了files参数发送数据,FastAPI会把这种请求解析为multipart/form-data格式,此时传入的矩阵字符串会被当作单个字符串元素,而不是自动解析为嵌套列表,所以Pydantic验证失败。要保留验证同时用请求体发送,有两种可行方式:

方式1:用json参数发送(最推荐)

直接把嵌套列表作为JSON请求体发送,FastAPI会自动解析并触发Pydantic验证,接口无需修改:

client = TestClient(app)
headers = {"accept": "application/json"}
data = [[[0.01, 0.32],[0.291, 0.239]]]

response = client.post(
    "/my_endpoint",
    json=data,
    headers=headers,
)

Pydantic会正常校验list[list[list[float]]]类型,完全满足你的需求。

方式2:用表单参数配合显式解析(适合必须用表单的场景)

如果一定要用表单格式发送,需要修改接口,显式接收字符串后解析为列表,同时手动触发Pydantic验证:

from fastapi import Form
import json
from typing import List

@app.post("/my_endpoint")
async def my_endpoint(
    my_matrix_str: str = Form(...),
):
    try:
        my_matrix = json.loads(my_matrix_str)
        # 手动触发Pydantic类型校验
        validated_matrix: List[List[List[float]]] = my_matrix
        print(validated_matrix)
        return {"status": "success", "data": validated_matrix}
    except (json.JSONDecodeError, TypeError) as e:
        return {"status": "error", "msg": "Invalid matrix format"}

请求时用data参数发送字符串格式的矩阵:

client = TestClient(app)
headers = {"accept": "application/json"}
data = {
    "my_matrix_str": '[[[0.01, 0.32],[0.291, 0.239]]]'
}

response = client.post(
    "/my_endpoint",
    data=data,
    headers=headers,
)

这种方式能保留验证逻辑,但需要手动处理解析和异常,不如JSON方式简洁。

内容的提问来源于stack exchange,提问作者Aloïs de La Comble

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:31:10