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

Question:

@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
Asked By: BumbleBee

||

Answers:

You need to do:

{
    "payload": {"title": "This is title"}
}
Answered By: Tom McLean

When defining your payload Body parameter like this:

payload: dict = Body(...)

and since it is the only Body parameter 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.

Answered By: Chris

Select data type that you are sending as json in postman.
This will 100% resolve your error.

Answered By: Amit gupta
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.