I’m hitting a snag with the Google Sheets API. When I try to add a protected range, I get this error:
HttpError 400
Invalid requests[0].addProtectedRange: No grid with id: 1
Here’s a simplified version of what I’m trying to do:
def protect_sheet_range(sheet_id):
api = setup_sheets_api()
protection = {
'addProtectedRange': {
'protectedRange': {
'range': {
'sheetId': 1,
'startRowIndex': 0,
'endRowIndex': 0,
'startColumnIndex': 0
},
'description': 'Keep headers safe',
'warningOnly': True
}
}
}
request_body = {'requests': [protection]}
api.spreadsheets().batchUpdate(spreadsheetId=sheet_id, body=request_body).execute()
Am I doing something wrong? Or could this be related to a known issue? I’m stumped and could use some help figuring this out. Thanks!
I’ve dealt with this exact issue before. The problem lies in the ‘sheetId’ parameter. It’s not referring to the spreadsheet ID, but rather to the individual sheet within the spreadsheet.
To resolve this, you need to fetch the correct sheetId first. Here’s how you can modify your code:
sheet_metadata = api.spreadsheets().get(spreadsheetId=sheet_id).execute()
sheet_id = sheet_metadata['sheets'][0]['properties']['sheetId']
protection = {
'addProtectedRange': {
'protectedRange': {
'range': {
'sheetId': sheet_id,
# rest of your code...
}
}
}
}
This should fix the ‘No grid with id: 1’ error. Remember, always fetch the sheetId dynamically to ensure you’re targeting the correct sheet.
I encountered a similar issue when working with the Sheets API recently. The problem likely stems from the ‘sheetId’ parameter in your range definition. This isn’t the same as the spreadsheet ID you’re using in the batchUpdate call.
Each sheet within a spreadsheet has its own unique ID, typically starting from 0 for the first sheet. Try changing ‘sheetId’: 1 to ‘sheetId’: 0 if you’re targeting the first sheet.
If that doesn’t work, you can fetch the correct sheet ID using the spreadsheets().get() method before applying the protection. This ensures you’re using the right ID:
sheet_metadata = api.spreadsheets().get(spreadsheetId=sheet_id).execute()
sheet_id = sheet_metadata['sheets'][0]['properties']['sheetId']
Then use this sheet_id in your range definition. This approach has solved the issue for me in the past. Hope it helps!
hey, i’ve run into this before. the problem is probably with the sheetId. it’s not the same as your spreadsheet ID. each sheet in the spreadsheet has its own ID, usually starting from 0.
try changing ‘sheetId’: 1 to ‘sheetId’: 0 for the first sheet. if that doesn’t work, you might need to fetch the actual sheet ID first. good luck!