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

如何向FastAPI的POST请求函数传递字符串数组?

FastAPI接收字符串数组报错TypeError: unhashable type: 'list'的解决方法

你的问题不是传递字符串数组的方式错误,而是返回数据的格式出了问题:

终端报错TypeError: unhashable type: 'list'是因为你在返回时写了return {list_names}——这里的大括号{}在Python里是创建集合的语法,而列表(list)是不可哈希的类型,不能作为集合的元素,所以触发了错误。

修正后的代码

你可以直接返回接收到的数组,或者用字典包裹数组(符合JSON格式要求),以下是两种可行的写法:

写法1:直接返回数组

from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: list[str]

app = FastAPI()

@app.post("/")
async def root(item: Item):
    # 不需要额外遍历复制,直接返回即可
    return item.name

写法2:返回字典格式(更清晰的JSON结构)

from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: list[str]

app = FastAPI()

@app.post("/")
async def root(item: Item):
    # 如需额外处理,处理后用字典返回
    list_names = [nm.upper() for nm in item.name]  # 示例:将元素转大写
    return {"names": list_names}

确认请求方式正确

你当前用Insomnia发送的POST请求JSON格式是完全正确的:

{
    "name": [
        "each",
        "single",
        "word"
    ]
}

运行命令uvicorn main:app --reload启动服务后,用这个请求就能正常接收并返回字符串数组了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:42:07