【问题标题】:Value is not a valid dict when posting JSON data through Postman to FastAPI backend通过 Postman 将 JSON 数据发布到 FastAPI 后端时,值不是有效的字典
【发布时间】:2022-10-18 19:52:26
【问题描述】:
@app.post("/posts")
def post_req(payload: dict = Body(...)):
    print(payload)
    return {"Message": "Posted!!!"}

我正在使用上面的路径操作函数来接收 POST 请求,但是当我尝试使用 Postman 发出请求时,它会显示value is not a valid dict

在邮递员中,我在请求正文中发送以下内容:

{
    "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

【问题讨论】:

  • 我经历了它,当我使用 str 而不是 dict 时,选项 2 对我有用,你能告诉我为什么 dict 向我显示错误。
  • 请确保您通过 Postman 以正确的方式发布请求。看看this answerthis answer。当使用payload: dict = Body(...) 时,FastAPI 将期望一个像:{"some key": "some value"} 这样的主体。
  • 通过这些答案得到它谢谢。

标签: python postman fastapi


【解决方案1】:

像这样定义 payload Body 参数时:

payload: dict = Body(...)

由于它是端点中唯一的 Body 参数,FastAPI 将期望 body 像:

{
  "some key": "some value"
}

由于您只有一个 body 参数,因此您也可以使用 special Body parameter embed

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

在这种情况下,FastAPI 会期望 body 像:

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

请查看this answer,以及this answerthis answer 了解更多详情。

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

【讨论】:

    【解决方案2】:

    你需要做:

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

    【讨论】:

    • 这也行不通。
    【解决方案3】:

    如果选择的响应类型不是 json,则可能会出现此错误。 enter image description here

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 2022-08-09
      • 2022-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      相关资源
      最近更新 更多