When I use GET request to send data to the server it works fine, but when use POST request it throws "422 Unprocessable Entity" error.
This is my Ajax request code:
var newName = "Bhanuka";
//do your own request an handle the results
$.ajax({
type: "post",
url: "/names/",
data: {d:newName},
dataType: 'json',
success: function(data){
console.log(data);
}
});
and this is my FastAPI server side code:
from fastapi import FastAPI, Request,Body
from pydantic import BaseModel
from fastapi.templating import Jinja2Templates
from fastapi.encoders import jsonable_encoder
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/items/{id}")
async def read_item(request: Request, id: str):
return templates.TemplateResponse("item.html", {"request": request, "id": id})
@app.post("/names/")
async def create_item(d:str):
return d
@app.get("/items11/{item_id}")
def read_item22(item_id: int, q: str ):
return {"item_id": item_id, "q": q}
It is because the data you are sending is json. and the POST request api is expecting str.
If the formats doesn't match during the api calls, it raises the Unprocessable Entity error.
You can deal it using
Well, coming to the first case, 1.Request: you can use request with curl
curl -i -d "param1=value1¶m2=value2" http://localhost:8000/check
to the below code for example:
from fastapi import FastAPI, Request
from fastapi.encoders import jsonable_encoder
app = FastAPI()
@app.post('/check')
async def check(request: Request):
da = await request.form()
da = jsonable_encoder(da)
print(da)
return da
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With