Search code examples
pythonjsonpostmanfastapi

Value is not a valid dict when posting JSON data through Postman to FastAPI backend


@app.post("/posts")
def post_req(payload: dict = Body(...)):
    print(payload)
    return {"Message": "Posted!!!"}

I am using the above path operation function to receive POST requests, but when I am trying to make a request using Postman, it says value is not a valid dict.

In Postman I am sending the below in the request body:

{
    "title" : "This is title"
}

The response I get in Postman is as follows:

{
    "detail": [
        {
            "loc": [
                "body"
            ],
            "msg": "value is not a valid dict",
            "type": "type_error.dict"
        }
    ]
}

VS Code terminal (server side) is showing this:

127.0.0.1:51397 - "POST /posts HTTP/1.1" 422 Unprocessable Entity

Solution

  • When defining your payload Body parameter like this:

    payload: dict = Body(...)
    

    and is the only Body parameter defined in your endpoint, FastAPI will expect a body like:

    {
      "some key": "some value"
    }
    

    Since you have a single Body parameter, you could also use the special Body parameter embed:

    payload: dict = Body(..., embed=True)
    

    in which case, FastAPI would expect a body like:

    {
      "payload": {"some key": "some value"}
    }
    

    Please have a look at this answer, as well as this answer and this answer for more details.

    When sending the request through Postman

    Also, the 422 Unprocessable Entity error shows that the body received doesn't match the expected format. Hence, please make sure you are posting the request body through Postman in the right way. That is, go to Body -> raw, and select JSON from the dropdown list to indicate the format of your data. Please take a look at the answers here and here for more details.