How to use sheet ID in Google Sheets API?

Daniel picture Daniel · Oct 22, 2018 · Viewed 8.8k times · Source

Google Sheets document can contain some sheets. First is default and '0'. Generally for any sheet there is address like this:

https://docs.google.com/spreadsheets/d/(spreadsheetId)/edit#gid=(sheetId)

with both spreadsheetId and sheetId.

But in API documentation there is no mention of how to use sheetId. I can only read and edit default sheet for given spreadsheetId.

If in request from code presented in exemplary link I added sheetId property I got error:

{ 
    message: 'Invalid JSON payload received. Unknown name "sheetId": Cannot bind query parameter. Field \'sheetId\' could not be found in request message.',
    domain: 'global',
    reason: 'badRequest' 
}

How to get access to other sheets than default in Google Sheets API and read or update fields in them?

Answer

TheMaster picture TheMaster · Oct 22, 2018

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.

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