【发布时间】: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 answer 和this answer。当使用
payload: dict = Body(...)时,FastAPI 将期望一个像:{"some key": "some value"}这样的主体。 -
通过这些答案得到它谢谢。