I’m building a simple API to test a database. When I use GET request everything works fine, but if I change to POST, I get 422 Unprocessable Entity error.
Here is the FastAPI code:
from fastapi import FastAPI
app = FastAPI()
@app.post("/")
def main(user):
return user
Here is my JavaScript request:
let axios = require('axios')
data = {
user: 'smith'
}
axios.post('http://localhost:8000', data)
.then(response => (console.log(response.url)))
Your FastAPI POST endpoint is missing a request body model or a way to tell FastAPI to expect JSON input. That’s why you get 422 Unprocessable Entity — FastAPI doesn’t know how to parse the user parameter.
How to fix it:
Use a Pydantic model to define the expected request body, like this:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class UserRequest(BaseModel):
user: str
@app.post("/")
def main(user: UserRequest):
return user
Now FastAPI knows to expect JSON with a user field and will parse it correctly.
Your JavaScript and Python requests sending JSON are fine.
Summary:
Define a Pydantic model for your POST body.
Use that model as the parameter in your endpoint.
Then your POST requests will work without 422 errors.