[SalesForce] Update Salesforce data using Apps Script

[{"message":"The Id field should not be specified in the sobject data.","errorCode":"INVALID_FIELD"}]
That's the error message. Any other way to do it? My Code:

function update() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var dataRange = ss.getDataRange();
  var data = getRowsData(sheet, dataRange,1);
  var runningLog = '<h1>Update Successful</h1><br>Updated following:<br><br>';
  for(var i = 1; i < data.length; i++){
    var payload =  JSON.stringify(
      {"Id" : data[i].id,
       "Name__c" : data[i].name,
       "Email__c" : data[i].email,
       "Ex_Id__c" : data[i].exid
      }
    );
    var getDataURL = getRestEndpoint()+"/services/data/v28.0/sobjects/"+getWhichObject()+"/";
    runningLog += UrlFetchApp.fetch(getDataURL,getUrlFetchPATCHOptions(payload)).getContentText();
  }

  SpreadsheetApp.getActiveSpreadsheet().show(HtmlService.createHtmlOutput(runningLog));
}
function getUrlFetchPATCHOptions(payload){
  var token = getSessionId();
  return {
    "method": "post",
    "contentType" : "application/json",
    "payload" : payload,
    "headers" : {
      "Authorization" : "OAuth " + token
    }
  }
}

Best Answer

A POST is used to insert a record and in that case the ID will be assigned once the record is inserted and so can't be specified.

A PATCH is used to update an existing record identified by the ID supplied. It sounds like that is what you want so change:

"method": "post"

to:

"method": "patch"

PS

As identified by orsan in the comments below and listed at the end of the Salesforce PATCH documentation, there is a workaround for libraries that don't support PATCH:

If you use an HTTP library that doesn't allow overriding or setting an arbitrary HTTP method name, you can send a POST request and provide an override to the HTTP method via the query string parameter _HttpMethod.

Related Topic