Protect file content

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

A content restriction isn't an access restriction. While users cannot modify thefile's content, other operations are still allowed, based on their access level.For example, a user with edit access can still move an item or change itssharing settings.

To add or remove a content restriction on a file in Drive, a usermust have the associatedpermissions. For afile or folder in My Drive or a shared drive with thecapabilities.canModifyEditorContentRestriction, you must haverole=writerassigned. For a file or folder in My Drive or a shared drive withanownerRestricted 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, seeRoles andpermissions. To update permissions on a file, seeUpdate permissions.

You can use thecontentRestrictions.readOnly boolean field on thefiles resource to set a contentrestriction. Note that setting a content restriction on an item overwrites theexisting 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
Important: The preceding doesn't include the results of calculations inSheets, so the displayed contents of a sheet with a contentrestriction might change if there are formulas in a sheet that referenceexternal data sources.

Certain file types can't contain a content restriction. A few examples are:

Add a content restriction

To add a file content restriction, use thefiles.update method with thecontentRestrictions.readOnly field set totrue. Add an optionalreason forwhy you're adding the restriction, such as "Finalized contract." The followingcode sample shows how to add a content restriction:

Java

FileupdatedFile=newFile().setContentRestrictions(ImmutableList.of(newContentRestriction().setReadOnly(true).setReason("Finalized contract."));Fileresponse=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**/asyncfunctionaddContentRestriction(){// Get credentials and build service// TODO (developer) - Use appropriate auth mechanism for your appconst{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive'});constservice=google.drive({version:'v3',auth});constcontentRestriction={'readOnly':True,'reason':'Finalized contract.',};constupdatedFile={'contentRestrictions':[contentRestriction],};try{constresponse=awaitservice.files.update({fileId:'FILE_ID',resource:updatedFile,fields:'contentRestrictions',});returnresponse;}catch(err){// TODO (developer) - Handle errorthrowerr;}}

ReplaceFILE_ID with thefileId of the file that you want tomodify.

When you run the sample code, the file is content restricted and a lock symbol() appears beside the filename withintheGoogle Drive user interface(UI). The file is now read-only.

A file with a content restriction within a Drive file list.
Figure 1. A file with a content restriction within a Drive file list.

Remove a content restriction

To remove a file content restriction, use thefiles.update method with thecontentRestrictions.readOnly field set tofalse. The following code sampleshows how to remove a content restriction:

Java

FileupdatedFile=newFile().setContentRestrictions(ImmutableList.of(newContentRestriction().setReadOnly(false));Fileresponse=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**/asyncfunctionremoveContentRestriction(){// Get credentials and build service// TODO (developer) - Use appropriate auth mechanism for your appconst{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive'});constservice=google.drive({version:'v3',auth});constcontentRestriction={'readOnly':False,};constupdatedFile={'contentRestrictions':[contentRestriction],};try{constresponse=awaitservice.files.update({fileId:'FILE_ID',resource:updatedFile,fields:'contentRestrictions',});returnresponse;}catch(err){// TODO (developer) - Handle errorthrowerr;}}

ReplaceFILE_ID with thefileId 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:

  1. In Drive, right-click the file with a content restriction andclickUnlock.

    Remove a file content restriction within a Drive file list.
    Figure 2. Remove a file content restriction within a Drive file list.
  2. Open the file with a content restriction and click(Locked mode)>Unlock file.

    Remove a file content restriction within a document.
    Figure 3. Remove a file content restriction within a document.

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

Fileresponse=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**/asyncfunctionfetchContentRestrictions(){// Get credentials and build service// TODO (developer) - Use appropriate auth mechanism for your appconst{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive'});constservice=google.drive({version:'v3',auth});try{constresponse=awaitservice.files.get({fileId:'FILE_ID',fields:'contentRestrictions',});returnresponse;}catch(err){// TODO (developer) - Handle errorthrowerr;}}

ReplaceFILE_ID with thefileId of the file that you want tocheck.

When you run the sample code, the method returns aContentRestriction resource 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 thefiles.update method with thecontentRestrictions.ownerRestricted boolean field set totrue. The followingcode sample shows how to add a content restriction for file owners only:

Java

FileupdatedFile=newFile().setContentRestrictions(ImmutableList.of(newContentRestriction().setReadOnly(true).setOwnerRestricted(true).setReason("Finalized contract."));Fileresponse=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**/asyncfunctionaddOwnerRestrictedContentRestriction(){// Get credentials and build service// TODO (developer) - Use appropriate auth mechanism for your appconst{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive'});constservice=google.drive({version:'v3',auth});constcontentRestriction={'readOnly':True,'ownerRestricted':True,'reason':'Finalized contract.',};constupdatedFile={'contentRestrictions':[contentRestriction],};try{constresponse=awaitservice.files.update({fileId:'FILE_ID',resource:updatedFile,fields:'contentRestrictions',});returnresponse;}catch(err){// TODO (developer) - Handle errorthrowerr;}}

ReplaceFILE_ID with thefileId 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 (

To remove theownerRestricted flag, use thefiles.update method with thecontentRestrictions.ownerRestricted field set tofalse.

Important: A My Drive file has a single owner so only they canmodify the content restriction. A shared drive owns the shared drive file, soany user withrole=organizer permissions on the shared drive can modify orremove theownerRestricted flag.

Content restriction capabilities

Afiles resource contains a collection of booleancapabilities fields used to indicate whether an action can be performed on afile.

Content restrictions contain the followingcapabilities:

  • capabilities.canModifyEditorContentRestriction: Whether the current usercan add or modify acontent restriction.
  • capabilities.canModifyOwnerContentRestriction: Whether the current usercan add or modify anowner content restriction.
  • capabilities.canRemoveContentRestriction: Whether the current user canremove the appliedcontent restriction (if present).

For more information, seeUnderstand filecapabilities.

For an example of retrieving filecapabilities, seeGet file capabilities.

Prevent users from downloading, printing, or copying your file

You can limit how users can download, print, and copy files withinDrive, Docs, Sheets, andSlides.

To determine whether the user can change owner or organizer-applied downloadrestrictions of a file, check thecapabilities.canChangeItemDownloadRestriction boolean field. Ifcapabilities.canChangeItemDownloadRestriction is set totrue, downloadrestrictions can be applied to the file. For more information, seeUnderstandfile capabilities.

To apply download restrictions to a file, set thedownloadRestrictions field using thefiles.update method. You can set the fieldusing theDownloadRestrictionsMetadataobject.

TheDownloadRestrictionsMetadata object has two fields:itemDownloadRestriction andeffectiveDownloadRestrictionWithContext. Bothfields are readable but only theitemDownloadRestriction can be set. TheitemDownloadRestriction field returns aDownloadRestriction object. TheDownloadRestrictionobject has two separate boolean fields:restrictedForReaders andrestrictedForWriters.

When setting theitemDownloadRestriction field the download restriction of thefile is applied directly by the owner or organizer. It doesn't account forshared drive settings or data loss prevention (DLP) rules. For more information,seeAbout DLP.

If you update theitemDownloadRestriction field by setting therestrictedForWriters field totrue, it implies thatrestrictedForReadersistrue. Similarly, settingrestrictedForWriters totrue andrestrictedForReaders tofalse is equivalent to setting bothrestrictedForWriters andrestrictedForReaders totrue.

For theeffectiveDownloadRestrictionWithContext field the download restrictionis applied to the file and it accounts for all restriction settings and DLPrules.

TheeffectiveDownloadRestrictionWithContext field can be set to eitherrestrictedForWriters orrestrictedForReaders. If there's any download orcopy restriction settings for the corresponding roles from file settings, shareddrive settings, or DLP rules (including those ones with context), then the valueis set totrue, otherwise it'sfalse.

Backward compatibility

We recommend that you use theDownloadRestriction object toenforce how users can download, print, and copy files.

If you want to use thecopyRequiresWriterPermissionboolean field, the functionality is different for both reading from and writingto the field.

The retrieved value of thecopyRequiresWriterPermission field reflects whetherusers with therole=commenter orrole=reader permission can download, print,or copy files within Drive. The field value reflects thecombination of file settings, shared drive settings, or DLP rules. However,context evaluation for DLP rules isn't included.

Setting thecopyRequiresWriterPermission field tofalse updates both therestrictedForWriters andrestrictedForReaders fields tofalse. This meansdownload or copy restriction settings are removed for all users.

Warning: You should only use the legacycopyRequiresWriterPermission fieldor theDownloadRestrictionobject to set download, print, and copy restrictions. The fields are not meantto be used together as the two field values might conflict.

Fields that control download, print, and copy features

The following table listsfiles resource fieldsthat affect download, print, and copy functionality:

FieldDescriptionVersion
capabilities.canCopyWhether the current user can copy a file.v2 & v3
capabilities.canDownloadWhether the current user can download a file.v2 & v3
capabilities.canChangeCopyRequiresWriterPermissionWhether the current user can change thecopyRequiresWriterPermission restriction of a file.v2 & v3
capabilities.canChangeItemDownloadRestrictionWhether the current user can change the download restriction of a file.v3 only
copyRequiresWriterPermissionWhether the options to copy, print, or download this file, should be disabled for readers and commenters.v2 & v3
downloadRestrictionsThe download restrictions applied on a file.v3 only
Note: Within thefiles resource several download and copy fields are marked asdeprecated. This means the field is obsolete. However, a deprecated field mightstill be available and functional through the deprecated phase. Continued orfuture use of deprecated fields is discouraged. Developers should plan tomigrate to the preferred alternative mentioned in the deprecated field'sdescription.

Related topics

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-11 UTC.