This is my FastAPI script, I am doing basic lesson to make the POST API as simple as possible.
class Item(BaseModel):
test_param:str
@app.post('/myapi')
async def myapi(item:Item):
print(item)
return {"myapi":"OK"}
Then my script is like this:
var formData = new FormData();
formData.append('test_param',"1");
axios.post("/myapi",formData
,{headers: {'Content-Type': 'application/form-data'}}).then(res=>{
console.log(res);
});
When calling API, it shows the error 422 Unprocessable Entity
.
I guess there is some discrepancy in API and script, however where should I fix?
I updated the script ,for not using Model thanks to @M.O.
from typing import Annotated
@app.post('/myapi')
async def get myapi(test_param:Annotated[str,Form(default="test")]):
print(test_param)
return {"myapi":"OK"}
however this shows the error FastAPI POST 422 Unprocessable Entity
and this error, it says there is no field, but i have test_param in Form data
6
The 422 error occurs because FastAPI expects JSON data by default when using Pydantic models, but you’re sending Form data. There are two ways to fix this:
Send JSON data:
axios.post("/myapi",
{ test_param: "1" }, // Send as JSON object
{ headers: { 'Content-Type': 'application/json' }}
).then(res => {
console.log(res);
});
Or if you specifically need to use Form data, modify your FastAPI endpoint to accept form data:
from fastapi import Form
@app.post('/myapi')
async def myapi(test_param: str = Form(...)): # Use Form instead of Pydantic model
return {"myapi": "OK"}
The first approach is simpler and more commonly used for API development. The 422 error happens because FastAPI can’t automatically parse the Form data into your Pydantic model.
Also, note that ‘application/form-data’ is incorrect in your headers. The correct MIME type would be ‘multipart/form-data’, but since we’re recommending JSON, use ‘application/json’ instead.
codex is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2