The Google Drive API supports several ways to prevent file modification, includingfile content restriction and prohibiting the option to download, print, or copyfiles.
Make files read-only with Drive content restrictions
You can add a content restriction to a Google Drive file to prevent users fromdoing the following:
- Modifying the title
- Making content edits
- Uploading a revision
- Adding or modifying comments
Applying content restrictions is a mechanism that allows the content of aDrive item to be made read-only without changing the item'saccess permissions. This means it'snot an access restriction. While users cannot modify the file's content, otheroperations are still allowed based on access level (for example, a user withedit access can still move an item or change its sharing settings).
To add or remove a content restriction on a file in Drive, a usermust have the associatedpermissions. For a file or folder inMy Drive or a shared drive with thecapabilities.canModifyEditorContentRestriction
, you must have role=writer
assigned. For a file or folder in My Drive or a shared drive withan ownerRestricted
content restriction, you must own the file or haverole=organizer
. To view an item with a content restriction, users must haverole=reader
or higher. For a complete list of roles, see . To change permissions on a file, seeChange permissions.
You can use the contentRestrictions.readOnly
boolean field on thefiles resource to seta content restriction. Note that setting a content restriction on an itemoverwrites the existing one.
Scenarios for content restrictions
A content restriction on a Drive item signals to users that thecontents shouldn't be changed. This can be for some of the following reasons:
- Pausing work on a collaborative document during review or audit periods.
- Setting an item to a finalized state, such as approved.
- Preventing changes during a sensitive meeting.
- Prohibiting external changes for workflows handled by automated systems.
- Restricting edits by Google Apps Script and Google Workspace Add-ons.
- Avoiding accidental edits to a document.
Note though that while content restrictions can help manage content, it's notmeant to prevent users with sufficient permissions from continuing to work on anitem. Additionally, it isn't a way to create an immutable record.Drive content restrictions are mutable, so a content restrictionon an item doesn't guarantee that the item never changes.
Manage files with content restrictions
Google Docs, Google Sheets, and Google Slides, as well as all other files,can contain content restrictions.
A content restriction on an item prevents changes to its title and content,including:
- Comments and suggestions (on Docs, Sheets,Slides, and binary files)
- Revisions of a binary file
- Text and formatting in Docs
- Text or formulas in Sheets, a Sheets layout,and instances in Sheets
- All content in Slides, as well as the order and number of theslides
Certain file types can't contain a content restriction. A few examples are:
- Google Forms
- Google Sites
- Google Drawings
- Shortcuts and third-party shortcuts. For more information, see Create ashortcut file to content stored by yourapp and Create a shortcut to aDrive file.
Add a content restriction
To add a file content restriction, use thefiles.update method with thecontentRestrictions.readOnly
field set to true
. Add an optional reason
forwhy you're adding the restriction, such as "Finalized contract." The followingcode sample shows how to add a content restriction:
Java
File updatedFile = new File() .setContentRestrictions( ImmutableList.of(new ContentRestriction().setReadOnly(true).setReason("Finalized contract."));File response = driveService.files().update("FILE_ID", updatedFile).setFields("contentRestrictions").execute();
Python
content_restriction = {'readOnly': True, 'reason':'Finalized contract.'}response = drive_service.files().update(fileId="FILE_ID", body = {'contentRestrictions' : [content_restriction]}, fields = "contentRestrictions").execute();
Node.js
/*** Set a content restriction on a file.* @return{obj} updated file**/async function addContentRestriction() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app const {GoogleAuth} = require('google-auth-library'); const {google} = require('googleapis'); const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'}); const service = google.drive({version: 'v3', auth}); const contentRestriction = { 'readOnly': True, 'reason': 'Finalized contract.', }; const updatedFile = { 'contentRestrictions': [contentRestriction], }; try { const response = await service.files.update({ fileId: 'FILE_ID', resource: updatedFile, fields: 'contentRestrictions', }); return response; } catch (err) { // TODO (developer) - Handle error throw err; }}
Replace FILE_ID with the fileId
of the file that you want tomodify.
When you run the sample code, the file is content restricted and a lock symbol(lock) appears beside the file name withinthe Google Drive user interface(UI). Thefile is now read-only.
Remove a content restriction
To remove a file content restriction, use the files.update
method with thecontentRestrictions.readOnly
field set to false
. The following code sampleshows how to remove a content restriction:
Java
File updatedFile =new File() .setContentRestrictions( ImmutableList.of(new ContentRestriction().setReadOnly(false));File response = driveService.files().update("FILE_ID", updatedFile).setFields("contentRestrictions").execute();
Python
content_restriction = {'readOnly': False}response = drive_service.files().update(fileId="FILE_ID", body = {'contentRestrictions' : [content_restriction]}, fields = "contentRestrictions").execute();
Node.js
/*** Remove a content restriction on a file.* @return{obj} updated file**/async function removeContentRestriction() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app const {GoogleAuth} = require('google-auth-library'); const {google} = require('googleapis'); const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'}); const service = google.drive({version: 'v3', auth}); const contentRestriction = { 'readOnly': False, }; const updatedFile = { 'contentRestrictions': [contentRestriction], }; try { const response = await service.files.update({ fileId: 'FILE_ID', resource: updatedFile, fields: 'contentRestrictions', }); return response; } catch (err) { // TODO (developer) - Handle error throw err; }}
Replace FILE_ID with the fileId
of the file that you want tomodify.
When you run the sample code, the file is no longer content restricted.
You can also use the Drive UI to remove a content restriction andallow content editing (provided you have the correct permissions). There are twooptions to do this:
In Drive, right-click the file with a content restriction andclick Unlock lock_open.
Open the file with a content restriction and click (Locked mode)lock >Unlock file.
Check for a content restriction
To check for a content restriction, use thefiles.get method with thecontentRestrictions
returned field. The following code sample shows how tocheck the status of a content restriction:
Java
File response = driveService.files().get("FILE_ID").setFields("contentRestrictions").execute();
Python
response = drive_service.files().get(fileId="FILE_ID", fields = "contentRestrictions").execute();
Node.js
/*** Get content restrictions on a file.* @return{obj} updated file**/async function fetchContentRestrictions() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app const {GoogleAuth} = require('google-auth-library'); const {google} = require('googleapis'); const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'}); const service = google.drive({version: 'v3', auth}); try { const response = await service.files.get({ fileId: 'FILE_ID', fields: 'contentRestrictions', }); return response; } catch (err) { // TODO (developer) - Handle error throw err; }}
Replace FILE_ID with the fileId
of the file that you want tocheck.
When you run the sample code, the method returns aContentRestrictionresource if present.
Add a content restriction only the file owner can modify
To add a file content restriction so only file owners can toggle the mechanism,use the files.update method withthe contentRestrictions.ownerRestricted
boolean field set to true
. Thefollowing code sample shows how to add a content restriction for file ownersonly:
Java
File updatedFile = new File() .setContentRestrictions( ImmutableList.of(new ContentRestriction().setReadOnly(true).setOwnerRestricted(true).setReason("Finalized contract."));File response = driveService.files().update("FILE_ID", updatedFile).setFields("contentRestrictions").execute();
Python
content_restriction = {'readOnly': True, 'ownerRestricted': True, 'reason':'Finalized contract.'}response = drive_service.files().update(fileId="FILE_ID", body = {'contentRestrictions' : [content_restriction]}, fields = "contentRestrictions").execute();
Node.js
/*** Set an owner restricted content restriction on a file.* @return{obj} updated file**/async function addOwnerRestrictedContentRestriction() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app const {GoogleAuth} = require('google-auth-library'); const {google} = require('googleapis'); const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/drive'}); const service = google.drive({version: 'v3', auth}); const contentRestriction = { 'readOnly': True, 'ownerRestricted': True, 'reason': 'Finalized contract.', }; const updatedFile = { 'contentRestrictions': [contentRestriction], }; try { const response = await service.files.update({ fileId: 'FILE_ID', resource: updatedFile, fields: 'contentRestrictions', }); return response; } catch (err) { // TODO (developer) - Handle error throw err; }}
Replace FILE_ID with the fileId
of the file that you want tomodify.
When you run the sample code, the file is content restricted and only fileowners can remove it. If you're the file owner, an active lock symbol (lock) appears beside the file name within the Drive user interface(UI). Ifyou're not the owner, the lock symbol is dimmed.
To remove the ownerRestricted
flag, use the files.update
method with thecontentRestrictions.ownerRestricted
field set to false
.
Content restriction capabilities
A files resource contains acollection of boolean capabilities
fields used to indicate whether an actioncan be performed on a file.
Content restrictions contain the following capabilities
:
capabilities.canModifyEditorContentRestriction
: Whether the current usercan add or modify a content restriction.capabilities.canModifyOwnerContentRestriction
: Whether the current usercan add or modify an owner content restriction.capabilities.canRemoveContentRestriction
: Whether the current user canremove the applied content restriction (if present).
For more information, seeCapabilities.
For an example of retrieving file capabilities
, see Verify userpermissions.
Prevent users from downloading, printing, or copying your file
You can limit how users with role=commenter
or role=reader
permissions candownload, print, and copy files within Drive,Docs, Sheets, and Slides.
To remove the options to download, print, and copy files, use thefiles.update method with thecopyRequiresWriterPermission
boolean field set to true
.