通过 Postman 将 JSON 数据发布到 FastAPI 后端时,值不是有效的字典

问题描述 投票:0回答:3
@app.post("/posts")
def post_req(payload: dict = Body(...)):
    print(payload)
    return {"Message": "Posted!!!"}

我正在使用上面的路径操作函数来接收POST请求,但是当我尝试使用Postman发出请求时,它说

value is not a valid dict

在 Postman 中,我在请求正文中发送以下内容:

{
    "title" : "This is title"
}

我在Postman中得到的回复如下:

{
    "detail": [
        {
            "loc": [
                "body"
            ],
            "msg": "value is not a valid dict",
            "type": "type_error.dict"
        }
    ]
}

VS Code 终端(服务器端)显示以下内容:

127.0.0.1:51397 - "POST /posts HTTP/1.1" 422 Unprocessable Entity
python json postman fastapi
3个回答
3
投票

定义

payload
Body
参数时,如下所示:

payload: dict = Body(...)

and 是端点中定义的 only

Body
参数,FastAPI 将期望
body
,例如:

{
  "some key": "some value"
}

由于您只有一个

Body
参数,因此您还可以使用 特殊
Body
参数
embed
:

payload: dict = Body(..., embed=True)

在这种情况下,FastAPI 会期望像这样的

body

{
  "payload": {"some key": "some value"}
}

请查看这个答案,以及这个答案这个答案了解更多详情。

通过 Postman 发送请求时

此外,

422 Unprocessable Entity
错误表明收到的
body
与预期格式不匹配。因此,请确保您以正确的方式通过 Postman 发布请求
body
。也就是说,转到
Body
->
raw
,然后从下拉列表中选择
JSON
以指示数据的格式。请查看答案这里这里了解更多详情。


1
投票

你需要做:

{
    "payload": {"title": "This is title"}
}

1
投票

选择您在邮递员中以 json 形式发送的数据类型。 这将 100% 解决您的错误。

© www.soinside.com 2019 - 2024. All rights reserved.