我想将 JSON 对象传递到 FastAPI 后端。这是我在前端应用程序中所做的事情:
data = {'labels': labels, 'sequences': sequences}
response = requests.post(api_url, data = data)
FastAPI 中的后端 API 如下所示:
@app.post("/api/zero-shot/")
async def Zero_Shot_Classification(request: Request):
data = await request.json()
但是,我收到此错误:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
您应该使用json
参数代替(这会改变Content-Type
标头至application/json
):
payload = {'labels': labels, 'sequences': sequences}
r = requests.post(url, json=payload)
not data
用于发送表单数据Content-Type
being application/x-www-form-urlencoded
默认情况下,或multipart/form-data
if files
也包含在请求中 - 除非您首先序列化 JSON 并手动设置Content-Type
标头至application/json
,如中所述这个答案:
payload = {'labels': labels, 'sequences': sequences}
r = requests.post(url, data=json.dumps(payload), headers={'Content-Type': 'application/json'})
另外,请查看文档关于在发送 JSON 请求正文时如何从使用 Pydantic 模型中受益,以及这个答案 and 这个答案有关如何定义需要 JSON 数据的端点的更多选项和示例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)