Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

394
Visualizações
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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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
over 4 years ago · Santiago Trujillo Relatório

0

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):
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda