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

使用curl向Python FastAPI POST JSON数据时遇解析错误求助

问题原因与解决方案

问题根源

你遇到的错误是因为Windows CMD环境不支持用单引号包裹JSON字符串。你当前的curl命令中,单引号会被当作请求体的一部分发送,实际传递给FastAPI的数据是'{"text":"Foo Bar"}'(包含首尾单引号),这不是合法的JSON格式,因此解析时抛出"Expecting value: line 1 column 1 (char 0)"错误。

解决方案

方案1:适配Windows CMD的curl命令

将单引号替换为双引号,并对JSON内部的双引号用\"转义:

curl -d "{\"text\":\"Foo Bar\"}" -H "Content-Type: application/json" -X POST http://localhost:5000

方案2:使用PowerShell执行命令

PowerShell支持单引号包裹字符串,直接运行你原来的命令即可:

curl -d '{"text":"Foo Bar"}' -H "Content-Type: application/json" -X POST http://localhost:5000

额外优化建议

你的FastAPI代码可以简化,不需要直接处理Request对象。FastAPI支持直接用dict或Pydantic模型接收JSON数据,这样能自动处理格式校验并返回标准错误:

from fastapi import FastAPI
import os
import uvicorn

app = FastAPI()

@app.post("/")
async def root(data: dict):
    return data

if __name__ == "__main__":
    prog = os.path.basename(__file__).replace(".py","")
    uvicorn.run("%s:app" % prog, host="127.0.0.1", port=5000, log_level="debug", reload=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:40:35