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

如何在FastAPI中接收多个字典(JSON)格式的Article数组作为输入?

FastAPI接收JSON数组请求体的解决方案

问题场景

需要让FastAPI接口接收Postman传入的JSON数组格式请求体,结构如下:

[
    {
        "articleUuid": "1",
        "articleContent": "test post matching specific"
    },
    {
        "articleUuid": "2",
        "articleContent": "wregryujtyjyuj"
    }
]

现有代码仅支持单个Article对象的请求体,无法处理数组输入,需调整接口定义。

解决方案

1. 导入必要类型

从typing模块导入List,用于定义数组类型的请求体。

2. 修改接口请求体类型

将接口参数的类型从单个Article改为List[Article],保留Body(...)声明(也可省略,FastAPI会自动识别请求体)。

3. 遍历处理每个对象

调整业务逻辑,遍历传入的数组,逐个处理每个Article对象,收集结果后统一返回。

完整代码示例

from fastapi import FastAPI, Body
from pydantic import BaseModel
from typing import List

app = FastAPI()

class Article(BaseModel):
    articleUuid: str
    articleContent: str

# 示例业务处理函数
def response(uuid: str, content: str):
    return {
        "articleUuid": uuid,
        "processedContent": content.upper(),
        "status": "success"
    }

@app.post("/classify")
async def classification(requests: List[Article] = Body(...)):
    results = []
    for article in requests:
        print(article.articleContent)
        result = response(article.articleUuid, article.articleContent)
        results.append(result)
    return results

测试注意事项

在Postman中发送请求时:

  • 请求方法选择POST,URL填写http://localhost:8000/classify
  • 请求体选择raw,格式切换为JSON
  • 粘贴目标JSON数组内容后发送请求,接口会返回每个对象的处理结果列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 11:12:40