Python: FastApi (Unprocessable Entity) error

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

  1. requests
  2. pydantic

Well, coming to the first case, 1.Request: you can use request with curl

curl -i -d "param1=value1&param2=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
  1. Pydantics as mentioned in @kamal's answer

A function parameters can be defined as in 3 types like path , singular types and model. Here you call the method using a JSON body and therefore it is likely a model parameter. Therefore in your code , define your input parameter as a model parameter.

Example -

from pydantic import BaseModel 
from fastapi import FastAPI

app = FastAPI()

class Data(BaseModel):
    user: str

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

Then you can call this as

  $.ajax({
         type: "post",
         url: "/names/",
         data: "{'user':'kamal'}",
         contentType: "application/json",  
         dataType: 'json', 
         success: function(data)
         { console.log(data); 

         }});