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

如何在FastAPI中通过Path参数接收ArrayList输入?

FastAPI路径参数接收列表报错解决方案

问题原因

FastAPI的路径参数仅支持标量类型(如str、int、float等单个值类型),无法直接将路径参数声明为list。因为URL路径中的每个占位符对应单个字符串片段,框架无法自动将其解析为列表,因此触发断言错误:AssertionError: Path params must be of one of the supported types。

解决方案

方案1:路径参数传递逗号分隔字符串,手动转换为列表

将列表元素用逗号拼接成字符串作为路径参数,在接口函数内拆分并转换为目标类型:

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_ids}")
def read_items(item_ids: str):
    # 拆分字符串并转换为整数列表,可根据实际需求修改类型(如str)
    item_id_list = list(map(int, item_ids.split(",")))
    return {"item_ids": item_id_list}

请求示例:GET /items/1,2,3,接口会返回{"item_ids": [1,2,3]}。

方案2:改用查询参数接收列表(推荐)

REST规范中,多值参数通常通过查询参数传递,FastAPI原生支持查询参数接收列表:

from fastapi import FastAPI, Query
from typing import List

app = FastAPI()

@app.get("/items/")
def read_items(item_ids: List[int] = Query(...)):
    return {"item_ids": item_ids}

请求示例:GET /items/?item_ids=1&item_ids=2&item_ids=3 或 GET /items/?item_ids=1,2,3,两种方式FastAPI都会自动解析为整数列表。

内容的提问来源于stack exchange,提问作者Vinuta Basavaraj Hiremath

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:08:19