javascriptgoogle-apps-scriptgoogle-drive-apihttp-posturlfetch

How to use Google App Script to send a file using POST request


I want to use Google Apps Script to integrate a Google Sheets with an API

This is the documentation from the API service:

curl --location --request POST 'https://apinew.socialhub.pro/api/sendMessage' \
--form 'api_token="SEU API_TOKEN AQUI"' \
--form 'phone="NUMERO DESTINO"' \
--form 'file=@"DIRETÓRIO DO ARQUIVO"' \
--form 'message="MENSAGEM"'

I have manage to create a script in Google App Script that works perfectly:

function send_message_teste(telephone,message) {
  var url = "https://apinew.socialhub.pro/api/sendMessage";
  
  telephone = telephone.toString();
  
  let request = {
                  "api_token":"MY_TOKEN",
                  "phone":telephone,
                  "message":message
                };
                
  let resquest_body = JSON.stringify(request);

  let config = {
    muteHttpExceptions: true,
    method: "post",
    headers: {
      "Content-Type": "application/json"
    },
    payload:resquest_body
  };
               

  let response = UrlFetchApp.fetch(url, config);
  var data = JSON.parse(response.getContentText());
  
  return response
}

My problem is that I can not make this work with a file. The API documentation has only the curl example. I have manage to translate this example to Google App Script, but I got stuck when trying to send a file through the API. Can anyone help me?


Solution

  • I believe your goal is as follows.

    I thought that when I saw your curl command, the request is multipart/form-data. But, in your showing script, it seems that the value is sent ad JSON data. I thought that this might be the reason for your current issue. When this is reflected in a sample script, how about the following sample script?

    Sample script:

    Please set the file ID of your file on Google Drive to fileId.

    function send_message_teste(telephone,message) {
      const fileId = "###"; // Please set your file ID of the file you want to upload.
    
      var url = "https://apinew.socialhub.pro/api/sendMessage";
      telephone = telephone.toString();
      let request = {
        "api_token": "MY_TOKEN",
        "phone": telephone,
        "message": message
      };
      const payload = { ...request, file: DriveApp.getFileById(fileId).getBlob() };
      let config = { muteHttpExceptions: true, payload };
      let response = UrlFetchApp.fetch(url, config);
      var data = JSON.parse(response.getContentText());
      return response;
    }
    

    Note:

    Reference: