Here is my React code. I’m parsing a CSV I upload to fileData. I’m just trying to print the data in the console for now in my Backend. The CSV probably has around 350 rows.
const [fileData, setFileData] = useState([])
const changeHandler = (event) => {
Papa.parse(event.target.files[0], {
header: true,
skipEmptyLines: true,
complete: function (results) {
setFileData(results.data)
},
});
};
async function postData() {
try{
console.log('File Data:', fileData)
const response = await axios.post(`${API_KEY}/uploadPlayerMins`, fileData)
console.log(response.data)
}
catch (error) {
console.error(error)
}
}
Here is the python code.
class PlayerInfo(BaseModel):
Mins: str
Player: str
@router.post("/uploadPlayerMins")
async def create_upload_file(player: PlayerInfo):
try:
print(player)
return JSONResponse(status_code=status.HTTP_200_OK, content=jsonable_encoder({ 'status': 'success',
'status_code': 200,
"message": 'Data has been uploaded successfully.'}))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
2
Answers
Looks like your route is expecting a Object type PlayerInfo:
async def create_upload_file(player: PlayerInfo)
but you are trying to send an array. Maybe you could change the expected value type. instead of PlayerInfo, use a dict
async def create_upload_file(player: Dict)
The error code 422 mean the interface of body that is defined in backend(python) is different between body that backend is received from frontend(react).
In your case, the interface of body in backend is PlayerInfo. So the body of request must be a dictionary like this:
But your frontend send request with body is an array of PlayerInfo.
To fix 422 error, you can change your code in python
Hope it’s helpfull.