简体   繁体   English

FastAPI/Pydantic 接受任意发布请求正文?

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

I want to create a FastAPI endpoint that just accepts an arbitrary post request body and returns it.我想创建一个 FastAPI 端点,它只接受任意发布请求正文并返回它。

If I send {"foo": "bar"} , I want to get {"foo": "bar"} back.如果我发送{"foo": "bar"} ,我想找回{"foo": "bar"} But I also want to be able to send {"foo1": "bar1", "foo2": "bar2"} and get that back.但我也希望能够发送{"foo1": "bar1", "foo2": "bar2"}并将其取回。

I tried:我试过了:

from fastapi import FastAPI
app = FastAPI()

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

But that returns an empty dictionary, no matter what I send it.但无论我发送什么,它都会返回一个空字典。

Any ideas?有任何想法吗?

You can use type hint Dict[Any, Any] to tell FastAPI you're expecting any valid JSON:你可以使用类型提示 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

The accepted answer works as long as the input is wrapped in a dictionary.只要输入包含在字典中,接受的答案就有效。 That is: started with a { and ends with a } .即:以{开头,以}结尾。 However, that does not cover all valid JSON inputs.但是,这并不涵盖所有有效的 JSON 输入。 For example, the following valid JSON inputs would fail:例如,以下有效的 JSON 输入将失败:

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

In order to have a truly generic JSON input accepted by the endpoint, the following would work:为了让端点接受一个真正通用的 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

Just using Any did not work for some reason.由于某种原因,仅使用Any不起作用。 When I used it, FastApi was expecting the input from the query arguments, not from the request body.当我使用它时,FastApi 期待来自查询 arguments 的输入,而不是来自请求正文的输入。

The =None makes it accept null and also an empty body. =None使它接受null和一个空的主体。 You can leave that part off and then the request body will be required to be not empty/null.您可以关闭该部分,然后要求请求正文不为空/空。

If you are using Python3.10 then you can get rid of the Union and write the definition as:如果您使用的是 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