skip to Main Content

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.

2

Answers


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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search