Python: FastAPI error 422 with post request

Solution 1:

Straight from the documentation:

The function parameters will be recognized as follows:

  • If the parameter is also declared in the path, it will be used as a path parameter.
  • If the parameter is of a singular type (like int, float, str, bool, etc) it will be interpreted as a query parameter.
  • If the parameter is declared to be of the type of a Pydantic model, it will be interpreted as a request body."

So to create a POST endpoint that receives a body with a user field you would do something like:

from fastapi import FastAPI
from pydantic import BaseModel


app = FastAPI()


class Data(BaseModel):
    user: str


@app.post("/")
def main(data: Data):
    return data

Solution 2:

In my case, I was calling the python API from different python project like this

queryResponse = requests.post(URL, data= query)

I was using the data property, I changed it to json, then it worked for me

queryResponse = requests.post(URL, json = query)

Solution 3:

For POST Requests for taking in the request body, you need to do as follows

Create a Pydantic Base Model User

from pydantic import BaseModel

class User(BaseModel):
    user_name: str


@app.post("/")
def main(user: User):
   return user

Solution 4:

FastAPI is based on Python type hints so when you pass a query parameter it accepts key:value pair you need to declare it somehow.

Even something like this will work

from typing import Dict, Any
...
@app.post("/")
def main(user: Dict[Any, Any] = None):
    return user

Out: {"user":"Smith"}

But using Pydantic way more effective

class User(BaseModel):
    user: str

@app.post("/")
def main(user: User):
    return user

Out: {"user":"Smith"}