close

[Solved] Python: FastAPI error 422 with post request

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Python: FastAPI error 422 with post request in Python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Python: FastAPI error 422 with post request Error Occurs?

Today I get the following error Python: FastAPI error 422 with post request in Python.

How To Solve Python: FastAPI error 422 with post request Error ?

  1. How To Solve Python: FastAPI error 422 with post request Error ?

    To Solve Python: FastAPI error 422 with post request Error If the parameter is of a singular type (like int, float, str, bool, etc) it will be interpreted as a query parameter.

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


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 3

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)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment