Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 259
Kosay Jabre Avatar asked Jun 08 '20 16:06

Kosay Jabre


People also ask

Can we send body in POST request?

So, by this example, it is clear that whenever we need to send a POST request, it should be accompanied by the Body. The body should be in the correct format and with the correct keys to get a correct response from the server.


1 Answers

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
like image 140
Gabriel Cappelli Avatar answered Oct 02 '22 18:10

Gabriel Cappelli