Search code examples
pythonpostmanfastapihttp-status-code-422

Why does a ValidationError 422 occur when sending a POST request to a FastAPI app through Postman?


I cannot seem to send a POST request to a FastAPI app through Postman.

  • FastAPI version 0.89.1
  • Python version 3.10.9
from fastapi import FastAPI
from fastapi.params import Body
from pydantic import BaseModel

app = FastAPI()

class Post(BaseModel):
    title : str
    content : str

@app.get("/")
async def root():
    return {"message": "Hello."}

@app.post("/createposts/")
def create_posts(new_post:Post):
    print(new_post.title)
    return  {"new_post":f"title:"[new_post.title]}

I got the following error

INFO:     Finished server process [44982]
INFO:     Started server process [45121]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:64722 - "POST /createposts/ HTTP/1.1" 422 Unprocessable Entity

I'm following a tutorial and I cannot seem to find answers from other users.

I tried using the dict: Body(...) input argument instead.

I am also using Postman and this is the error:

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

Here's a screenshot of my request on Postman.

screenshot of Postman

I made a POST request to the URL with the POST endpoint:

{
 "title":"a",
 "content":"b"
}

Solution

  • In Postman, you need to set the Body to be of type JSON.

    In your screenshot, you have it set to Text:

    screenshot of Postman, Body set to Text

    It should be set to JSON:

    screenshot of Postman, Body set to JSON

    And it should work as expectedNote 1, as shown in the screenshot.

    As MatsLindh said in the comments, you can open the panel for the Code Snippet section to check how exactly Postman converts your request:

    screenshot of Postman, Code snippet shows JSON

    It should show

    --header 'Content-Type: application/json' 
    

    for JSON. You probably have it as

    --header 'Content-Type: text/plain'
    

    for text, which FastAPI cannot parse properly.


    Note 1
    It's unrelated to the validation error, but you have a typo in the f-string on your endpoint. The closing double-quote on the value is misplaced.

    This:

    return  {"new_post":f"title:"[new_post.title]}
    

    should be:

    return  {"new_post": f"title:[{new_post.title}]"}