简体   繁体   中英

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.

If I send {"foo": "bar"} , I want to get {"foo": "bar"} back. But I also want to be able to send {"foo1": "bar1", "foo2": "bar2"} and get that back.

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:

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. For example, the following valid JSON inputs would fail:

  • 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:

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. When I used it, FastApi was expecting the input from the query arguments, not from the request body.

The =None makes it accept null and also an empty body. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM