Python: FastAPI error 422 with post request
Python: FastAPI error 422 with post request
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
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)
Python: FastAPI error 422 with post request
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