如何将 JSON 数据发布到 FastAPI 并在端点内检索 JSON 数据?

MGL*_*don 7 python rest fastapi streamlit

我想将 JSON 对象传递到 FastAPI 后端。这是我在前端应用程序中所做的事情:

data = {'labels': labels, 'sequences': sequences}
response = requests.post(api_url, data = data)
Run Code Online (Sandbox Code Playgroud)

FastAPI 中的后端 API 如下所示:

@app.post("/api/zero-shot/")
async def Zero_Shot_Classification(request: Request):
    data = await request.json()
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 7

您应该改用该json参数(这会将Content-Type标头更改为application/json):

\n
payload = {\'labels\': labels, \'sequences\': sequences}\nr = requests.post(url, json=payload)\n
Run Code Online (Sandbox Code Playgroud)\n

默认情况下, notdata用于发送表单数据,或者if也包含在 request\xe2\x80\x94 中,除非您首先序列化 JSON 并手动将标头设置为,如本答案中所述Content-Typeapplication/x-www-form-urlencodedmultipart/form-datafilesContent-Typeapplication/json中所述:

\n
payload = {\'labels\': labels, \'sequences\': sequences}\nr = requests.post(url, data=json.dumps(payload), headers={\'Content-Type\': \'application/json\'})\n
Run Code Online (Sandbox Code Playgroud)\n

另外,请查看有关如何在发送 JSON 请求正文时从使用 Pydantic 模型中受益的文档,以及此答案此答案,以获取有关如何定义期望 JSON 数据的端点的更多选项和示例。

\n