FastAPI: how to read body as any valid json?

Alejandro Navas picture Alejandro Navas · Oct 15, 2020 · Viewed 9.4k times · Source

Sorry, not proficient in Python.

I haven't found the docs for that use case. How can I get the request body, ensure its a valid Json (any valid json, including numbers, string, booleans and nulls, not only objects and arrays) and get the actual Json. Using pydantic forces the Json to have a specific structure.

Answer

Yagiz Degirmenci picture Yagiz Degirmenci · Oct 15, 2020

You can find nearly everything inside the Request object

You are able to get request body with request.body()

from fastapi import Request, FastAPI

@app.post("/dummypath")
async def get_body(request: Request):
    return await request.json()