FastAPI单参数主体原因拼写验证错误

问题描述 投票:0回答:1

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

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

这是请求

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

{
  "t": 10
}

这是回应

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"
    }
  ]
}

但是,在尝试了许多样本后,我发现如果我有多个Body(),它们将不会出错。例如,

@app.post("/test-multi-mix")
async def test_multi_param(
    s: str = Body(...),
    t: int = Body(...),
):
    pass

请求

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

{
  "s": "test",
  "t": 10
}

响应

HTTP/1.1 200 OK
date: Fri, 22 May 2020 10:16:12 GMT
server: uvicorn
content-length: 4
content-type: application/json
connection: close

null

有人对我的实现有任何想法吗?有错吗这不是最佳实践吗?还是一个错误?

python http-post httprequest fastapi pydantic
1个回答
0
投票

这不是错误,它是Body的行为方式,它存在用于“扩展”请求参数,如何记录文档outlines

class Item(BaseModel):
    name: str

class User(BaseModel):
    username: str
    full_name: str = None


@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int,
    item: Item,
    user: User,
    importance: int = Body(..., gt=0),
    q: str = None
):
    pass

此视图的有效请求正文为:

{
    "item": {
        "name": "Foo",
        "tax": 3.2
    },
    "user": {
        "username": "dave",
        "full_name": "Dave Grohl"
    },
    "importance": 5
}

如果您真的想单独使用Body,则必须指定embed=True,该代码可以正常工作:

embed=True
© www.soinside.com 2019 - 2024. All rights reserved.