Search code examples
google-apigoogle-sheets-api

How to use batchUpdate in Node.js


I am using the following method to access a Google Spreadsheet using Javascript to, for example, insert a row of data:

const Sheets = require("@googleapis/sheets");
const jwt = new Sheets.auth.JWT(xxemailxx, null, xxprivate keyxx, [...]);
await jwt.authorize();

const sheets = Sheets.sheets("v4");
sheets.spreadsheets.values.append({
    auth: jwt,
    spreadsheetId: "xxxxxxx",
    range: "Sheet1",
    resource: { values: [[1,2,3,4]]}
  }, (err, response) => {
   // ...callback
   }
});

Note that I pass the JWT in the API call. This method has worked well for some years. Now I want to use batchUpdate to append a block of rows. I can't find documentation for Node.js. The link in the @googleapis/sheets repo points to this and this which looks like it's for web service APIs. I tried various permutations to pass in a requestbody but was not successful.

What is a workable method to use the batchUpdate api? Is there documentation on batchUpdate more specific to Node.js?


Solution

  • RECOMMENDATION:

    Here's the sample syntax that you can use for batchUpdate:

     sheets.spreadsheets.values.batchUpdate({
      
      "spreadsheetId": 'xxxxxxxx',
      "resource": {
        "valueInputOption": "RAW",
        "data": [
          {
            "range": "A1:C3", //A1 Notation
            "values": [
                ["Hi", "Google", "Docs"],
                ["Hey", "please", "update"],
                [1, 2, 3]
            ]
          }
        ]
      }
    }, function(error, res){
      if (error) {
        console.log('Error: ' + error);
        return;
      }
      console.log(res);
    });
    

    Note: Regardless of the authentication you will use, I believe the responseBody syntax will be the same.

    References: