Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

393
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!