小编Pra*_* T.的帖子

FastAPI 单参数主体导致 Pydantic 验证错误

我有一个 POST FastAPI 方法。我不想构造类或查询字符串。所以,我决定应用Body()方法。

@app.post("/test-single-int")
async def test_single_int(
    t: int = Body(...)
):
    pass
Run Code Online (Sandbox Code Playgroud)

这是请求

POST http://localhost:8000/test-single-int/

{
  "t": 10
}
Run Code Online (Sandbox Code Playgroud)

这是回应

HTTP/1.1 422 Unprocessable Entity
date: Fri, 22 May 2020 10:00:16 GMT
server: uvicorn
content-length: 83
content-type: application/json
connection: close

{
  "detail": [
    {
      "loc": [
        "body",
        "s"
      ],
      "msg": "str type expected",
      "type": "type_error.str"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

但是,在尝试了许多样本后,我发现如果我有多个Body(). 例如,

POST http://localhost:8000/test-single-int/

{
  "t": 10
}
Run Code Online (Sandbox Code Playgroud)

要求

POST http://localhost:8000/test-multi-mix/

{
  "s": "test",
  "t": 10
} …
Run Code Online (Sandbox Code Playgroud)

python http-post httprequest pydantic fastapi

5
推荐指数
1
解决办法
3869
查看次数

标签 统计

fastapi ×1

http-post ×1

httprequest ×1

pydantic ×1

python ×1