Sheets API protected range fails with 'grid with id: 1 not found' error

I keep running into this error when trying to create protected ranges using the Google Sheets API. The error message says Invalid requests[0].addProtectedRange: No grid with id: 1.

I’m not sure what’s causing this. Maybe it’s the same problem others have faced with grid IDs not being found.

Here’s my code:

def create_protection_rules(sheet_id):
    sheets_service = initialize_service()
    
    protection_requests = [
        {
            "addProtectedRange": {
                'protectedRange': {
                    "range": {
                        "sheetId": 1,
                        "startRowIndex": 0,
                        "endRowIndex": 0,
                        "startColumnIndex": 0
                    },
                    "description": "Header row protection",
                    "warningOnly": True
                }
            }
        }
    ]
    
    request_body = {
        'requests': protection_requests
    }
    
    result = sheets_service.spreadsheets().batchUpdate(
        spreadsheetId=sheet_id,
        body=request_body
    ).execute()

Any ideas what might be wrong here?

u should double-check if there’s a tab with sheetId 1 in the sheet. Sometimes they get out of sync. Maybe run spreadsheets().get() to see the real sheetIds and update ur code accordingly.

The sheetId is for the specific worksheet tab, not the whole spreadsheet ID. New Google Sheets start with sheetId 0 for the first tab, not 1. I ran into this exact problem last month and wasted hours on it. You’ve got to grab the actual sheetId from your spreadsheet metadata first. Google assigns these IDs automatically - they can be any integer and won’t be sequential if you’ve added or deleted worksheets. Try switching your sheetId to 0 and see if that fixes it. Even better, use the spreadsheets().get() method to fetch the correct ID programmatically instead of hardcoding it.

Had this exact same issue on a data validation project. Yeah, it’s the sheetId reference, but here’s what really got me - when you create a new spreadsheet through code, the default sheet sometimes gets a random ID instead of 0. I had to fetch the spreadsheet metadata first and pull the sheetId from the sheets array. You’ll find it at response[‘sheets’][0][‘properties’][‘sheetId’] for the first tab. Another thing - if you’re using an existing spreadsheet where someone renamed or moved tabs around, the sheetId won’t be what you think it is. I always grab these IDs and store them in variables instead of hardcoding. Saves tons of debugging headaches.