How to use sheet ID in Google Sheets API?

Sheet name is the easiest way to access a specific sheet. As written here, range parameter can include sheet names like,

Sheet1!A1

If you must use a sheet id instead of sheet name, You can use any of the alternate end points which uses dataFilter, like spreadsheets.values.batchUpdateByDataFilter instead of spreadsheets.values.batchUpdate. You can then use sheetId in request body at data.dataFilter.gridRange.sheetId. An example of using such a filter with sheetId is provided by another answer here by ztrat4dkyle.

However, developer metadata is the preferred method of permanently associating objects(sheets/ranges/columns) to variables, where user modifications are expected on such objects.


Essentially we need to use dataFilters to target a specific sheet by ID.

@TheMaster pointed me in the right direction but I found the answers confusing so I just want to share my working example for Node.js.

Here's how to get the value of cell B2 from a sheet that has ID 0123456789

const getValueFromCellB2 = async () => {
  const SPREADSHEET_ID = 'INSERT_SPREADSHEET_ID';
  const SHEET_ID = 0123456789;
  // TODO: replace above values with real IDs.
  const google = await googleConnection();
  const sheetData = await google.spreadsheets.values
    .batchGetByDataFilter({
      spreadsheetId: SPREADSHEET_ID,
      resource: {
        dataFilters: [
          {
            gridRange: {
              sheetId: SHEET_ID,
              startRowIndex: 1,
              endRowIndex: 2,
              startColumnIndex: 1,
              endColumnIndex: 2,
            },
          },
        ],
      },
    })
    .then((res) => res.data.valueRanges[0].valueRange.values);

  return sheetData[0][0];
}

// There are many ways to auth with Google... Here's one:
const googleConnection = async () => {
  const auth = await google.auth.getClient({
    keyFilename: path.join(__dirname, '../../secrets.json'),
    scopes: 'https://www.googleapis.com/auth/spreadsheets',
  });

  return google.sheets({version: 'v4', auth});
}

To simply read data we're using batchGetByDataFilter where dataFilters is an array of separate filter objects. The gridRange filter (one of many) allows us to specify a sheetId and range of cells to return.