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

如何在FastAPI中根据条件返回纯文本或JSON?

解决FastAPI同一接口返回JSON与纯文本的问题

可以实现,核心思路是根据条件返回不同类型的Response对象,而非直接返回字典或文本。这样既能保证JSON格式正常返回,也能让纯文本内容以正确格式输出。

代码示例

from fastapi import FastAPI, JSONResponse, PlainTextResponse

app = FastAPI()

@app.post("/instance/new", tags=["instance"])
async def MyFunction(condition: bool):
    if condition:
        return JSONResponse(content={"key": "value"})
    else:
        some_big_plain_text = "这里是大段纯文本内容..."
        return PlainTextResponse(content=some_big_plain_text)

说明

  • 当condition为True时,返回JSONResponse,FastAPI会自动设置Content-Type: application/json,确保JSON格式正确。
  • 当condition为False时,返回PlainTextResponse,此时Content-Type会被设置为text/plain,大段纯文本会以友好的格式输出。
  • 这种方式避免了指定单一响应类型导致的冲突,完全适配两种返回场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:35:55