Sub topic 12
Protected ranges in the Sheets API
This chapter assumes you can protect ranges in the Google Sheets interface and read basic JavaScript. You should also know how Apps Script protections work, covered in the earlier chapters. Here you will see how the same ideas map onto the Sheets API, which you call over HTTP (or through a client library) instead of from inside a spreadsheet.
Why use the API instead of Apps Script
Apps Script runs inside Google's environment and is usually bound to one spreadsheet. The Sheets API is a REST interface. You can call it from any server, command-line tool, or scheduled job. That makes it a good fit when you must apply the same protections to many spreadsheets, for example every file created from a template.
The two approaches describe the same object, a protected range. They differ in how you name things:
| Concept | Apps Script | Sheets API |
|---|---|---|
| Range location | `getRange('A1:E1')` (A1 notation) | `GridRange` with numeric indexes |
| Sheet reference | Sheet object | `sheetId` (a number) |
| Create | `range.protect()` | `addProtectedRange` request |
| Change | `setDescription()`, `addEditor()` | `updateProtectedRange` request |
| Remove | `protection.remove()` | `deleteProtectedRange` request |
| Read | `sheet.getProtections()` | `spreadsheets.get`, field `sheets.protectedRanges` |
| Whole sheet | `sheet.protect()` | A protected range with no row or column bounds |
The protected range resource
In the API, one protection is a ProtectedRange object. These are its main fields:
protectedRangeId: a number the API assigns. You need it to update or delete the protection later.range: aGridRangethat says which cells are protected.namedRangeId: an alternative torange. The protection follows a named range.description: a label shown in the protection list.warningOnly: iftrue, editors see a confirmation prompt but are not blocked.requestingUserCanEdit: whether the user who makes the request can edit the protection. The API returns this value, and the default isfalseunless you add yourself to the editors.unprotectedRanges: a list ofGridRangeobjects that stay editable inside a protected sheet.editors: an object withusers,groups, anddomainUsersCanEdit.
How a GridRange counts cells
A GridRange does not use A1 notation. It uses zero-based start indexes and exclusive end indexes. This is the most common source of mistakes.
startRowIndexis zero-based and inclusive.endRowIndexis exclusive.startColumnIndexandendColumnIndexfollow the same rule.sheetIdis the numeric ID of the tab, not its name or position.
So A1:E1 becomes rows 0 to 1 and columns 0 to 5. Row 1 is index 0. Column E is the fifth column, so its index is 4, and the exclusive end is 5.
If you leave out an index, the bound is open. A range with only sheetId covers the entire sheet. A range with startRowIndex 0 and endRowIndex 1 but no column indexes covers all of row 1, however many columns exist.
Adding a protected range
You send protection changes through spreadsheets.batchUpdate. The body holds a requests array, and each item holds exactly one request type.
{
"requests": [
{
"addProtectedRange": {
"protectedRange": {
"range": {
"sheetId": 0,
"startRowIndex": 0,
"endRowIndex": 1,
"startColumnIndex": 0,
"endColumnIndex": 5
},
"description": "Header row",
"warningOnly": false,
"editors": {
"users": ["[email protected]"]
}
}
}
}
]
}This protects A1:E1 on the sheet with ID 0. Only the listed users can edit it, plus the owner of the file. The response includes an addProtectedRange reply with the full protectedRange, including its new protectedRangeId. Save that ID if you plan to modify the protection later.
Who ends up able to edit
The editors field replaces the whole editor list. You do not add one user at a time. If you send users: ["[email protected]"], that is the entire list of named users, along with any groups you list. Two rules from earlier chapters still hold:
- A person must already have edit access to the spreadsheet. Naming a viewer in
editorsdoes not make them an editor of the file. - The file owner can always edit a protected range.
For a warning-only protection, you leave out editors. The API ignores editor lists when warningOnly is true, because everyone with edit access can already change the cells after confirming the prompt.
Protecting a whole sheet with exceptions
To protect a sheet, give the range only a sheetId. To keep input cells open, add unprotectedRanges.
{
"requests": [
{
"addProtectedRange": {
"protectedRange": {
"range": {
"sheetId": 123456789
},
"description": "Budget sheet",
"unprotectedRanges": [
{
"sheetId": 123456789,
"startRowIndex": 1,
"endRowIndex": 20,
"startColumnIndex": 1,
"endColumnIndex": 2
}
]
}
}
}
]
}The unprotected range covers rows 2 to 20 of column B, which is B2:B20 in A1 notation. It matches the Apps Script example from the previous chapter. Each unprotected range must lie on the same sheet as the protection.
Updating a protected range
To change a protection, use updateProtectedRange. You must pass the protectedRangeId and a fields mask. The mask lists which properties to overwrite. Properties not in the mask stay as they were.
{
"requests": [
{
"updateProtectedRange": {
"protectedRange": {
"protectedRangeId": 1234567,
"description": "Header row (locked)",
"warningOnly": true
},
"fields": "description,warningOnly"
}
}
]
}A frequent error is sending a fields value of *. That replaces every property, so any field you omitted from the body, such as editors, is cleared. List the fields by name instead.
Deleting a protected range
Deletion needs only the ID.
{
"requests": [
{
"deleteProtectedRange": {
"protectedRangeId": 1234567
}
}
]
}If the ID does not exist, the whole batchUpdate request fails. Batches are atomic: when one request in the array is invalid, none of them are applied.
Listing protections for an audit
Protections are part of the sheet metadata. You read them with spreadsheets.get and a field mask, which keeps the response small.
GET https://sheets.googleapis.com/v4/spreadsheets/SPREADSHEET_ID?fields=sheets(properties(sheetId,title),protectedRanges)Each sheet in the response carries a protectedRanges array. A sheet with no protections has no such array, so code that reads it must handle a missing value.
A complete script in Node.js
The following program adds a protection and then lists every protection in the file. It uses the official googleapis package. It assumes you have created credentials and authorized an account that can edit the spreadsheet.
const { google } = require('googleapis');
async function main() {
const spreadsheetId = process.env.SPREADSHEET_ID;
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});
const sheets = google.sheets({ version: 'v4', auth });
const addResponse = await sheets.spreadsheets.batchUpdate({
spreadsheetId,
requestBody: {
requests: [
{
addProtectedRange: {
protectedRange: {
range: {
sheetId: 0,
startRowIndex: 0,
endRowIndex: 1,
startColumnIndex: 0,
endColumnIndex: 5,
},
description: 'Header row',
warningOnly: false,
editors: { users: [process.env.OWNER_EMAIL] },
},
},
},
],
},
});
const created = addResponse.data.replies[0].addProtectedRange.protectedRange;
console.log('Created protection', created.protectedRangeId);
const listResponse = await sheets.spreadsheets.get({
spreadsheetId,
fields: 'sheets(properties(sheetId,title),protectedRanges)',
});
for (const sheet of listResponse.data.sheets) {
const protections = sheet.protectedRanges || [];
for (const p of protections) {
console.log(
`${sheet.properties.title} | id=${p.protectedRangeId} | ` +
`${p.description || '(no description)'} | warningOnly=${Boolean(p.warningOnly)}`
);
}
}
}
main().catch((err) => {
console.error(err.message);
process.exit(1);
});Set SPREADSHEET_ID and OWNER_EMAIL in your environment first. The GoogleAuth class reads credentials from Application Default Credentials. If the account is a service account, share the spreadsheet with its email address as an editor, or the call fails with a permission error.
Request flow
Common errors and gotchas
- Off-by-one ranges. Treating
endRowIndexas inclusive protects one row or column too many. Always check by converting back to A1 notation. - Wrong
sheetId. Using the tab position instead of the real ID protects the wrong sheet, or fails if no tab has that ID. - Lost editors on update. An overly broad
fieldsmask can wipe the editor list. Name each field. - Locking yourself out. If you set
editorswithout including your own account,requestingUserCanEditisfalsefor you. You can still edit the file if you are its owner, but a collaborator in that position cannot change the protection afterward. - Permission errors. The caller needs edit access to the file. A caller with only view access gets a 403 response.
- Atomic batches. One bad request stops the whole batch, so a typo in a late request undoes earlier valid requests.
- Assuming security. The API creates the same protection as the interface. Everything in the limits chapter still applies: protection does not hide data, and users with edit access can still copy values, import the sheet elsewhere, or change the file's structure in ways the protection does not block.
Choosing between Apps Script and the API
| Situation | Better choice |
|---|---|
| One spreadsheet, logic tied to its menus or triggers | Apps Script |
| Many files, scheduled or external automation | Sheets API |
| You need to react to user edits as they happen | Apps Script |
| Your own app already has Google credentials | Sheets API |
Both methods produce identical protections, so you can create a protection in one and manage it in the other.
Exercise
You want to protect cells C3:D10 on a sheet whose ID is 42. Write the GridRange. Then explain what happens if you send an updateProtectedRange request with fields set to "*" and a body that contains only protectedRangeId and description.
Show answer
The GridRange is {"sheetId": 42, "startRowIndex": 2, "endRowIndex": 10, "startColumnIndex": 2, "endColumnIndex": 4}. Row 3 has index 2, and the exclusive end index 10 covers row 10. Column C has index 2, and the exclusive end 4 covers column D. With fields set to "*", every property of the protection is overwritten by the body, and the body has no range, editors, or warningOnly value. The protection loses those settings, so the update can fail or leave a protection with no editor list. Use a mask such as "description" so only that property changes.
Exercise
A batchUpdate contains three requests: a valid addProtectedRange, a valid updateProtectedRange, and a deleteProtectedRange with an ID that does not exist. What is the state of the spreadsheet afterward, and how would you find the IDs you need before building such a request?
Show answer
The spreadsheet is unchanged. A batchUpdate is atomic, so the invalid delete makes the whole request fail and the first two requests are not applied. To find real IDs, call spreadsheets.get with fields set to "sheets(properties(sheetId,title),protectedRanges)" and read each protectedRangeId from the response.