pythonreactjsbackendfastapireact-fullstack

How to send an array to the backend with React and FastAPI. I keep getting error code 422


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))

Here is an image of what the CSV looks like.


Solution

  • 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:

    {
     'Mins': ' ',
     'Player': ' ',
    }
    

    But your frontend send request with body is an array of PlayerInfo.

    To fix 422 error, you can change your code in python

    async def create_upload_file(player: List[PlayerInfo]):
    

    Hope it's helpfull.