Fastapi: How to capture the whole body of POST, in a single JSON var

Created on 7 Sep 2019  路  6Comments  路  Source: tiangolo/fastapi

Description

How can I capture the whole body of a POST operation (posted as application/json) as a single JSON var, without necessarily knowing the incoming schema?

Additional context

Tried as:

from pydantic import BaseModel, Json

class DynamicSchema(BaseModel):
    item: Json

@router.post("/someurl")
async def someMethod(
    item: DynamicSchema
):

but I get a reply of:

{
    "detail": [
        {
            "loc": [
                "body",
                "item",
                "item"
            ],
            "msg": "field required",
            "type": "value_error.missing"
        }
    ]
}

for a submission of:

{
    "qwerty": "me",
    "more": "other",
    "another": {
        "dict": "q1"
    }
}

I've tried a ton of other different variations by I still get a validation error.

I though Body(..., embed=True) might help but I got nowhere with that either.

PS: The docs are not clear either on how to do something as simple as that (they are fantastic though for anything else I've looked).

question

Most helpful comment

Writing this for future reference: the solution to the initial question by @euri10 works. Code would be:

@router.post("/someurl")
async def someMethod(body: dict):
    return body

All 6 comments

you can try
body: Any = Body(...)
or body: dict

Yeah, this works...

I am 99.9% sure I tried this out, and it "didn't" work!

And I just found out that starting the apiserver with:

uvicorn apiserver.server:app --reload

does not always properly reload the server. Changes to the signature of the POST methodm through VSCode, does not automatically reload the server to the new code changes, keeping the old behavior. So I am sure I tried many different combos without manually reloading to the new code changes (trusting the server will pick them up)

I guess, I'll have to open a separate issue for this when I can create a minimum viable example.

Thanks!

That would be a uvicorn issue then.

I'm not using vscode so it may be irrelevant but the reloader keeps track of st_mtime so if a file changes but is not saved last modification time won't change and therefore won't reload.

Pycharm I think is saving changes automatically.

Thanks for the help here @euri10 ! :clap: :bow:

Thanks for reporting back and closing the issue @stratosgear :+1:

Writing this for future reference: the solution to the initial question by @euri10 works. Code would be:

@router.post("/someurl")
async def someMethod(body: dict):
    return body

Is it possible at all to pass both body and an extracted body parameter to an endpoint?

Was this page helpful?
0 / 5 - 0 ratings