Search code examples
jsonfastapipydantic

How to read body as any valid json?


I haven't found the docs for that use case. How can I get the request body, ensure it's 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.


Solution

  • You can find nearly everything inside the Request object

    You are able to get request body with request.json(), which will give you the parsed JSON as dictionary.

    from fastapi import Request, FastAPI
    
    @app.post("/dummypath")
    async def get_body(request: Request):
        return await request.json()
    

    If you want access the body as string, you can use request.body()