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

如何使用FastAPI返回未包裹在列表/数组中的独立JSON响应?

实现FastAPI返回多行独立JSON对象

要满足返回多个未被数组包裹的独立JSON对象(每行一个)的需求,你需要绕过FastAPI默认的JSON序列化逻辑,手动构造响应内容:

方法一:使用PlainTextResponse返回拼接内容

通过PlainTextResponse直接返回拼接好的多行JSON字符串:

from fastapi import FastAPI
from fastapi.responses import PlainTextResponse
import json

app = FastAPI()

@app.get("/", response_class=PlainTextResponse)
def read_root():
    data_1 = {"items": 10}
    data_2 = {"order": "shelf", "amount": 100}
    data_3 = {"id": 100, "date": "2022-01-01", "status": "X"}
    
    # 逐个序列化对象后用换行符拼接
    json_lines = [json.dumps(obj) for obj in [data_1, data_2, data_3]]
    return "\n".join(json_lines)

方法二:自定义响应类适配JSON媒体类型

如果希望响应的Content-Type标记为application/json(兼容部分客户端对媒体类型的要求),可以自定义响应类:

from fastapi import FastAPI
from fastapi.responses import Response
import json

app = FastAPI()

class NewlineDelimitedJSONResponse(Response):
    media_type = "application/json"

    def render(self, content: list) -> bytes:
        json_lines = [json.dumps(item) for item in content]
        return "\n".join(json_lines).encode("utf-8")

@app.get("/", response_class=NewlineDelimitedJSONResponse)
def read_root():
    data_1 = {"items": 10}
    data_2 = {"order": "shelf", "amount": 100}
    data_3 = {"id": 100, "date": "2022-01-01", "status": "X"}
    return [data_1, data_2, data_3]

关键说明

  • 这种换行分隔的JSON(NDJSON格式)不符合标准JSON规范,标准JSON要求根节点必须是单个对象或数组,但多数日志处理工具、特定客户端可以兼容该格式。
  • OpenAPI规范默认不支持此类响应结构,自动生成的API文档无法正确识别响应内容,需手动补充说明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 15:45:05