Home > Back-end >  Calling FASTAPI to upload file from phone React Native
Calling FASTAPI to upload file from phone React Native

Time:07-09

I have a FASTAPI which accepts file as input in Heroku. I wanted to call the API from React Native app which user can select image from phone and pass it as a body. However, I have met an issue {"detail": [{"loc": [Array], "msg": "field required", "type": "value_error.missing"}]}. I wanted to know how should I structure the body and the requirements to be pass to the API. Here are the image info that I have:enter image description here

FastAPI Python

@app.post("/receiptOcr")
async def main(file: UploadFile = File(...)):

React Native

const chooseFromLibrary = () => {
    ImagePicker.openPicker({
      width: 300,
      height: 400,
      cropping: false,
    }).then(image => {
      console.log(image);
      hi(image.path);
    });
  };
  const hi = async imagepath => {
    let response = await fetch(
      'https://receipt-ocr-heroku.herokuapp.com/receiptOcr',
      {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({file: imagepath}),
      },
    );
    console.log(response);
    let result = await response.json();
    console.log(result);
  };

CodePudding user response:

If you look into the automatic generated FastAPI swagger (127.0.0.1:8000/docs), you'll see that you have to use multipart-form to upload this.

FastAPI Swagger

To upload this from Angular you will have to use FormData as per the example below.

const chooseFromLibrary = () => {
  ImagePicker.openPicker({ 
    width: 300,
    height: 400,
    cropping: false,
  }).then(image => {
    console.log(image);
    hi(image);
  });
};

const hi = async image => {
  let uploadForm = new FormData();
  uploadForm.append("file", image);
  let response = await fetch(
    'https://receipt-ocr-heroku.herokuapp.com/receiptOcr',
    {
      method: 'POST',
      body: uploadForm,
    }
  );
  console.log(response);
  let result = await response.json();
  console.log(result);
};
  • Related