簡體   English   中英

FastAPI/Pydantic 接受任意發布請求正文?

[英]FastAPI/Pydantic accept arbitrary post request body?

我想創建一個 FastAPI 端點,它只接受任意發布請求正文並返回它。

如果我發送{"foo": "bar"} ,我想找回{"foo": "bar"} 但我也希望能夠發送{"foo1": "bar1", "foo2": "bar2"}並將其取回。

我試過了:

from fastapi import FastAPI
app = FastAPI()

app.post("/")
async def handle(request: BaseModel):
    return request

但無論我發送什么,它都會返回一個空字典。

有任何想法嗎?

你可以使用類型提示 Dict[Any, Any] 告訴 FastAPI 你期待任何有效的 JSON:

from typing import Any, Dict
from fastapi import FastAPI

app = FastAPI()

@app.post("/")
async def handle(request: Dict[Any, Any]):
    return request

只要輸入包含在字典中,接受的答案就有效。 即:以{開頭,以}結尾。 但是,這並不涵蓋所有有效的 JSON 輸入。 例如,以下有效的 JSON 輸入將失敗:

  • true / false
  • 1.2
  • null
  • "text"
  • [1,2,3]

為了讓端點接受一個真正通用的 JSON 輸入,可以使用以下方法:

from typing import Any, Dict, List, Union
from fastapi import FastAPI

app = FastAPI()

@app.post("/")
async def handle(request: Union[List,Dict,Any]=None):
    return request

由於某種原因,僅使用Any不起作用。 當我使用它時,FastApi 期待來自查詢 arguments 的輸入,而不是來自請求正文的輸入。

=None使它接受null和一個空的主體。 您可以關閉該部分,然后要求請求正文不為空/空。

如果您使用的是 Python3.10,那么您可以擺脫Union並將定義編寫為:

async def handle(request: List | Dict | Any = None):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM