[go: up one dir, main page]

0% found this document useful (0 votes)
14 views91 pages

Google Drive API Operations

The document provides an overview of files and folders in Google Drive, detailing how they are organized, owned, and manipulated through the Google Drive API. It explains the differences between My Drive and shared drives, outlines various file types, and describes file characteristics such as access proposals, metadata, and permissions. Additionally, it includes guidance on creating folders, uploading files, and moving files between folders using code samples.

Uploaded by

luis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views91 pages

Google Drive API Operations

The document provides an overview of files and folders in Google Drive, detailing how they are organized, owned, and manipulated through the Google Drive API. It explains the differences between My Drive and shared drives, outlines various file types, and describes file characteristics such as access proposals, metadata, and permissions. Additionally, it includes guidance on creating folders, uploading files, and moving files between folders using code samples.

Uploaded by

luis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

6/27/25, 10:02 AM Files and folders overview | Google Drive | Google for Developers

Files and folders overview


Google Drive organizes files in collections, describes files by types, and provides specific
attributes for each file to facilitate file manipulation.

The Google Drive API represents files stored on Drive as a files


(/workspace/drive/api/reference/rest/v3/files) resource.

Note: Folders are treated as a type of file. For more details about folders, see File types (#types).

Ownership
Drive organizes files based on the user's relationship with the content and its storage
location. Collections are specified as part of the file's metadata to show which group of files
the file is stored with inside Drive. The main difference between My Drive and shared drive
collections is file ownership. A single user is the owner of files in their My Drive, whereas a
group or organization owns files in a shared drive.

My Drive

Each user has a "root" folder called "My Drive" that functions as their primary
hierarchy, and consists of everything that descends from this root folder. The user is
the primary owner of this folder.

Shared drives

A shared drive (/workspace/drive/api/guides/about-shareddrives) is an organizational


structure within Drive that lives parallel to My Drive. You can organize an individual file
within a shared drive or My Drive, but not both. However, Drive shortcuts
(/workspace/drive/api/guides/shortcuts) can be used to point to files or folders from
shared drives to My Drive, or the other way around.

File types
Drive describes files by types. This list shows all available file types:

Blob

https://developers.google.com/workspace/drive/api/guides/about-files 1/5
6/27/25, 10:02 AM Files and folders overview | Google Drive | Google for Developers

A file that contains text or binary content such as images, videos, and PDFs.

Folder

A container you can use to organize other types of files on Drive. Folders are files that
only contain metadata, and have the MIME type application/vnd.google-
apps.folder. For more information, see Create and populate folders
(/workspace/drive/api/guides/folder).

Note: A single file stored on My Drive can be in multiple folders. A single file stored on
a shared drive (/workspace/drive/api/guides/about-shareddrives) can only have one parent
folder.

Google Workspace document

A file that a Google Workspace application creates, such as Google Docs, Sheets, or
Slides. The MIME type format is application/vnd.google-apps.*app* where app is
the application name (such as application/vnd.google-apps.spreadsheet for a
Sheets file). For a list of Drive and Google Workspace-specific MIME types, see
Google Workspace and Google Drive supported MIME types
(/workspace/drive/api/guides/mime-types).

Shortcut

A metadata-only file that points to another file on Drive. The shortcut file MIME type is
application/vnd.google-apps.shortcut. For more information, see Create a
shortcut to a Drive file (/workspace/drive/api/guides/shortcuts).

Third-party shortcut

A metadata-only file that links to content stored on a third-party storage system. The
third-party shortcut file MIME type is application/vnd.google-apps.drive-sdk.
For more information, see Create a shortcut file to content stored by your app
(/workspace/drive/api/guides/third-party-shortcuts).

Note: You cannot upload or download folders, Google Workspace documents, shortcuts, and third-party
shortcuts to or from Drive. However, if they use compatible formats you can upload or export Google
Workspace documents. For example, you can create a Docs document when you import a PDF. Similarly,
you can export a Google Slides presentation as a Microsoft PowerPoint file.

File characteristics

https://developers.google.com/workspace/drive/api/guides/about-files 2/5
6/27/25, 10:02 AM Files and folders overview | Google Drive | Google for Developers

This list shows some characteristics of a Drive file:

Access proposal

A proposal from a requester to an approver to grant a recipient access to a Drive item.


For more information, see List and resolve pending access proposals
(/workspace/drive/api/guides/manage-sharing#access-proposals).

Content

The binary or text body of the file. Some content examples you can store in Drive are
images, videos, text, and PDFs.

File ID

A unique, opaque ID for each file. File IDs are stable throughout the life of the file, even
if the file name changes. Search expressions (/workspace/drive/api/guides/search-files)
are used to locate files by name, type, content, parent container, owner, or other
metadata.

Metadata

Data describing the contents of the file. This data includes the name, type, creation,
and modification times. Some metadata fields, such as the name, are user-agnostic
and appear the same for each user. Other fields, such as capabilities and
viewedByMeDate contain user-specific values. File types, such as images and videos,
contain additional metadata extracted from EXIF and other embedded metadata. For
more information, see Manage file metadata (/workspace/drive/api/guides/file).

Permission

An access grant for a user, group, domain, or the world to access a file or a folder
hierarchy. Users control who can access a file with the access control list (ACL),
which is a list of permissions for the file. For more information, see Share files, folders
and drives (/workspace/drive/api/guides/manage-sharing).

Revision history

The record of changes to the file content only, not the file metadata. For more details
about revisions, see Changes and revisions overview
(/workspace/drive/api/guides/change-overview).

Thumbnail

https://developers.google.com/workspace/drive/api/guides/about-files 3/5
6/27/25, 10:02 AM Files and folders overview | Google Drive | Google for Developers

A graphical representation of a file. Drive automatically generates thumbnails for


many common file types. For shortcuts and other file types that Drive can't render, you
can provide a thumbnail image. For more information, see Upload thumbnails
(/workspace/drive/api/guides/file#upload-thumbnails).

File organization
The Drive API organizes files into storage locations, called spaces, and collections, called
corpora.

Spaces

Specific storage locations that are isolated from each other. All content in Drive is
stored in one of these two defined spaces: drive and appDataFolder.

drive: Includes all user-visible files created in Drive. PDFs, documents, Google
Docs, shortcuts, and other content the user uploads is located in the drive
space.

appDataFolder: Includes per-user application data. Applications typically store


configuration files and other data not intended to be directly accessible by
users.

Files cannot move between spaces.

Corpora

Collections of files used to narrow the scope of file and folder searches. The corpora
for Drive are: user, domain, drive, and allDrives.

user: Includes all files created by and opened by the user in "My Drive", and
those shared directly with the user in "Shared with me."

drive: Includes all files contained in a single shared drive, as indicated by the
driveId.

domain: Includes all searchable files shared with the user's domain.

allDrives: Includes all files in shared drives where the user is a member, and all
files in "My Drive" and "Shared with me." Use the allDrives corpora with caution
as it has a broad scope and can affect performance. When possible, use user or
drive instead of allDrives for efficiency.

Files can move freely between corpora as permissions and ownership change.

https://developers.google.com/workspace/drive/api/guides/about-files 4/5
6/27/25, 10:02 AM Files and folders overview | Google Drive | Google for Developers

Related topics
Here are a few next steps you might take:

Learn how to Create and manage files (/workspace/drive/api/guides/create-file).

Learn how to Create and populate folders (/workspace/drive/api/guides/folder).

Learn how to Upload file data (/workspace/drive/api/guides/manage-uploads).

Learn how to Download and export files (/workspace/drive/api/guides/manage-downloads).

Learn how to Store application-specific data (/workspace/drive/api/guides/appdata).

Learn how to Display the Google Picker (/workspace/drive/api/guides/picker) on a page.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/about-files 5/5
6/27/25, 10:09 AM Create and populate folders | Google Drive | Google for Developers

Create and populate folders


Folders are files that only contain metadata and can be used to organize files in Google
Drive. They have the following properties:

A folder is a file with the MIME type (/workspace/drive/api/guides/mime-types)


application/vnd.google-apps.folder and it has no extension.

The alias root can be used to refer to the root folder anywhere a file ID is provided.

For more information about Drive folder limits, see File and folder limits (#folder-limits).

This guide explains how to perform some basic folder-related tasks.

Create a folder
To create a folder, use the files.create() (/workspace/drive/api/reference/rest/v3/files/create)
method with the mimeType of application/vnd.google-apps.folder and a name. The
following code sample shows how to create a folder using a client library:

Note: If you're using the older Drive API v2, use the files.insert
(/workspace/drive/api/v2/reference/files/insert) method. You can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

Java (#java)Python (#python)Node.jsPHP (#php).NET (#.net)


(#node.js)

drive/snippets/drive_v3/file_snippets/create_folder.js

com/googleworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/create_folder.js)

/**
* Create a folder and prints the folder ID
* @return{obj} folder Id
* */
async function createFolder() {
// Get credentials and build service
// TODO (developer) - Use appropriate auth mechanism for your app

const {GoogleAuth} = require('google-auth-library');

https://developers.google.com/workspace/drive/api/guides/folder 1/8
6/27/25, 10:09 AM Create and populate folders | Google Drive | Google for Developers

const {google} = require('googleapis');

const auth = new GoogleAuth({


scopes: 'https://www.googleapis.com/auth/drive',
});
const service = google.drive({version: 'v3', auth});
const fileMetadata = {
name: 'Invoices',
mimeType: 'application/vnd.google-apps.folder',
};
try {
const file = await service.files.create({
requestBody: fileMetadata,
fields: 'id',
});
console.log('Folder Id:', file.data.id);
return file.data.id;
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}

Create a file in a specific folder


To create a file in a specific folder, use the files.create()
(/workspace/drive/api/reference/rest/v3/files/create) method and specify the folder ID in the
parents property of the file.

The parents property holds the ID of the parent folder containing the file. The parents
property can be used when creating files in a top-level folder or any other folder.

A file can only have one parent folder. Specifying multiple parents isn't supported. If the
parents field isn't specified, the file is placed directly in the user's My Drive folder.

The following code sample shows how to create a file in a specific folder using a client
library:

Note: If you're using the older Drive API v2, use the files.insert
(/workspace/drive/api/v2/reference/files/insert) method. You can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

https://developers.google.com/workspace/drive/api/guides/folder 2/8
6/27/25, 10:09 AM Create and populate folders | Google Drive | Google for Developers

Java (#java)Python (#python)Node.jsPHP (#php).NET (#.net)


(#node.js)

drive/snippets/drive_v3/file_snippets/upload_to_folder.js

/googleworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/upload_to_folder.js)
m/googleworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/upload_to_folder.js)

/**
* Upload a file to the specified folder
* @param{string} folderId folder ID
* @return{obj} file Id
* */
async function uploadToFolder(folderId) {
const fs = require('fs');
const {GoogleAuth} = require('google-auth-library');
const {google} = require('googleapis');
// Get credentials and build service
// TODO (developer) - Use appropriate auth mechanism for your app
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/drive',
});
const service = google.drive({version: 'v3', auth});

// TODO(developer): set folder Id


// folderId = '1lWo8HghUBd-3mN4s98ArNFMdqmhqCXH7';
const fileMetadata = {
name: 'photo.jpg',
parents: [folderId],
};
const media = {
mimeType: 'image/jpeg',
body: fs.createReadStream('files/photo.jpg'),
};

try {
const file = await service.files.create({
requestBody: fileMetadata,
media: media,
fields: 'id',
});
console.log('File Id:', file.data.id);
return file.data.id;
} catch (err) {
// TODO(developer) - Handle error
throw err;

https://developers.google.com/workspace/drive/api/guides/folder 3/8
6/27/25, 10:09 AM Create and populate folders | Google Drive | Google for Developers

}
}

Move files between folders


To move files, you must update the ID of the parents property.

To add or remove parents for an existing file, use the files.update()


(/workspace/drive/api/reference/rest/v3/files/update) method with either the addParents and
removeParents query parameters.

A file can only have one parent folder. Specifying multiple parents isn't supported.

Warning: Even though a folder is a type of file, you can't move a folder from My Drive into a shared drive
by updating the addParents parameter. Attempting to do so returns a
teamDrivesFolderMoveInNotSupported HTTP status code response. For more information and
potential workarounds, see Resolve errors
(/workspace/drive/api/guides/handle-errors#move-folders-into-shared-drive)

The following code sample shows how to move a file between folders using a client library:

Java (#java)Python (#python)Node.jsPHP (#php).NET (#.net)


(#node.js)

drive/snippets/drive_v3/file_snippets/move_file_to_folder.js

oogleworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/move_file_to_folder.js)

/**
* Change the file's modification timestamp.
* @param{string} fileId Id of the file to move
* @param{string} folderId Id of the folder to move
* @return{obj} file status
* */
async function moveFileToFolder(fileId, folderId) {
const {GoogleAuth} = require('google-auth-library');
const {google} = require('googleapis');

// Get credentials and build service


// TODO (developer) - Use appropriate auth mechanism for your app
const auth = new GoogleAuth({

https://developers.google.com/workspace/drive/api/guides/folder 4/8
6/27/25, 10:09 AM Create and populate folders | Google Drive | Google for Developers

scopes: 'https://www.googleapis.com/auth/drive',
});
const service = google.drive({version: 'v3', auth});

try {
// Retrieve the existing parents to remove
const file = await service.files.get({
fileId: fileId,
fields: 'parents',
});

// Move the file to the new folder


const previousParents = file.data.parents
.join(',');
const files = await service.files.update({
fileId: fileId,
addParents: folderId,
removeParents: previousParents,
fields: 'id, parents',
});
console.log(files.status);
return files.status;
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}

Note: If you're using the earlier Drive API v2, the children
(/workspace/drive/api/reference/rest/v2/children) and parents
(/workspace/drive/api/reference/rest/v2/parents) resources can also facilitate the reorganization of
files and folders.

File and folder limits


Drive files and folders have some storage limits.

User-item limit
Each user can have up to 500 million items that were created by that account. When the
limit is reached, the user can no longer create or upload items in Drive. They can still view

https://developers.google.com/workspace/drive/api/guides/folder 5/8
6/27/25, 10:09 AM Create and populate folders | Google Drive | Google for Developers

and edit existing items. To create files again, users must permanently delete items or use a
different account. For more information, see Trash or delete files and folders
(/workspace/drive/api/guides/delete).

Objects that count toward this limit are:

Items created or uploaded by the user in Drive

Items created by the user but now owned by someone else

Items in the trash

Shortcuts

Third-party shortcuts

Objects that don't count toward this limit are:

Permanently-deleted items

Items shared with the user but owned by someone else

Items owned by the user but created by someone else

Attempts to add more than 500 million items returns an


activeItemCreationLimitExceeded
(/workspace/drive/api/guides/handle-errors#active-item-limit) HTTP status code response.

Note that service accounts can't own any files. Instead, they must upload files and folders
into shared drives, or use OAuth 2.0 to upload items on behalf of a human user.

Folder-item limit
Each folder in a user's My Drive has a limit of 500,000 items. This limit doesn't apply to the
root folder of My Drive. Items that count toward this limit are:

Folders

Files. All file types, regardless of file ownership.

Shortcuts. Counts as a single item within a folder, even if the item it points to isn't
within that folder. For more information, see Create a shortcut to a Drive file
(/workspace/drive/api/guides/shortcuts).

Third-party shortcuts. Counts as a single item within a folder, even if the item it points
to isn't within that folder. For more information, see Create a shortcut file to content
stored by your app (/workspace/drive/api/guides/third-party-shortcuts).

https://developers.google.com/workspace/drive/api/guides/folder 6/8
6/27/25, 10:09 AM Create and populate folders | Google Drive | Google for Developers

For more information about folder limits, see Folder limits in Google Drive
(https://support.google.com/a/answer/2490100#limits).

Folder-depth limit
A user's My Drive can't contain more than 100 levels of nested folders. This means that a
child folder cannot be stored under a folder that's more than 99 levels deep. This limitation
only applies to child folders. A child file with a MIME type
(/workspace/drive/api/guides/mime-types) other than application/vnd.google-apps.folder
is exempt from this limitation.

For example, in the following diagram a new folder can be nested inside folder number 99
but not inside folder number 100. However, folder number 100 can store files like any other
Drive folder:

Attempts to add more than 100 levels of folders returns a


myDriveHierarchyDepthLimitExceeded
(/workspace/drive/api/guides/handle-errors#nested-folder-levels) HTTP status code response.

Note: There's no files (/workspace/drive/api/reference/rest/v3/files) field in the Google Drive API that
can return the depth of a folder. To determine the folder depth, you must manually ascend the folder
hierarchy.

https://developers.google.com/workspace/drive/api/guides/folder 7/8
6/27/25, 10:09 AM Create and populate folders | Google Drive | Google for Developers

Related topics
Create and manage files (/workspace/drive/api/guides/create-file)

Manage file metadata (/workspace/drive/api/guides/file)

File and folder limits in shared drives


(/workspace/drive/api/guides/manage-shareddrives#folder-limits)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-18 UTC.

https://developers.google.com/workspace/drive/api/guides/folder 8/8
6/27/25, 10:09 AM Migrate to Drive API v3 | Google Drive | Google for Developers

Migrate to Drive API v3


If you are currently using Drive API v2, you can migrate to v3.

You should review the V2 to v3 reference (/workspace/drive/api/guides/v2-to-v3-reference) for a


complete map of all resource differences between versions.

The {drive_api_short} version is set differently for each language:

For Java, you download the v3 library. See Drive API client library for Java
(https://github.com/googleapis/google-api-java-client-services/tree/main/clients/google-api-
services-drive/v3)

. For an example, see Java Quickstart (/workspace/drive/api/quickstart/java).

For JavaScript, you define the version with the Discovery docs URL. For an example,
see Browser Quickstart (/workspace/drive/api/quickstart/js).

var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/driv

For Python, you specify the version when you build the service object. For an example,
see Python Quickstart (/workspace/drive/api/quickstart/python).

service = build('drive', 'v3', credentials=creds)

For Node.js, you define the version when you set the google.drive constructor. For an
example, see Node.js Quickstart (/workspace/drive/api/quickstart/nodejs).

const drive = google.drive({version: 'v3', auth});

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/migrate-to-v3 1/1
6/27/25, 10:07 AM Download and export files | Google Drive | Google for Developers

Download and export files


The Google Drive API supports several types of download and export actions, as listed in
the following table:

Download actions Blob file content using the files.get method with the alt=media
URL parameter.

Blob file content at an earlier version using the revisions.get


method with the alt=media URL parameter.

Blob file content in a browser using the webContentLink field.

Blob file content using the files.download method during long-


running operations. This is the only way to download Google Vids
files.

Export actions Google Workspace document content in a format that your app can
handle, using the files.export method.

Google Workspace document content in a browser using the export


Links field.

Google Workspace document content at an earlier version in a


browser using the exportLinks field.

Google Workspace document content using the files.download


method during long-running operations.

Before you download or export file content, verify that users can download the file using the
capabilities.canDownload field on the files (/workspace/drive/api/reference/rest/v3/files)
resource.

For descriptions of the file types mentioned here, including blob and Google Workspace
files, see File types (/workspace/drive/api/guides/about-files#types).

The rest of this guide provides detailed instructions for performing these types of download
and export actions.

Download blob file content


To download a blob file stored on Drive, use the files.get
(/workspace/drive/api/v3/reference/files/get) method with the ID of the file to download and the

https://developers.google.com/workspace/drive/api/guides/manage-downloads#node.js 1/7
6/27/25, 10:07 AM Download and export files | Google Drive | Google for Developers

alt=media URL parameter. The alt=media URL parameter tells the server that a download
of content is being requested as an alternative response format.

The alt=media URL parameter is a system parameter


(https://cloud.google.com/apis/docs/system-parameters) available across all Google REST APIs.
If you use a client library for the Drive API, you don't need to explicitly set this parameter.

The following code sample shows how to use the files.get method to download a file
with the Drive API client libraries.

Note: If you're using the older Drive API v2, you can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

Java (#java)Python (#python)Node.jsPHP (#php).NET (#.net)


(#node.js)

drive/snippets/drive_v3/file_snippets/download_file.js

om/googleworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/download_file.js)

/**
* Downloads a file
* @param{string} realFileId file ID
* @return{obj} file status
* */
async function downloadFile(realFileId) {
// 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});

fileId = realFileId;
try {
const file = await service.files.get({
fileId: fileId,
alt: 'media',
});
console.log(file.status);

https://developers.google.com/workspace/drive/api/guides/manage-downloads#node.js 2/7
6/27/25, 10:07 AM Download and export files | Google Drive | Google for Developers

return file.status;
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}

This code sample uses a library method that adds the alt=media URL parameter to the
underlying HTTP request.

File downloads started from your app must be authorized with a scope that allows read
access to the file content. For example, an app using the drive.readonly.metadata scope
isn't authorized to download the file contents. This code sample uses the restricted “drive”
file scope that allows users to view and manage all of your Drive files. To learn more about
Drive scopes, refer to Choose Google Drive API scopes
(/workspace/drive/api/guides/api-specific-auth).

Users with edit permissions can restrict downloading by read-only users through setting the
copyRequiresWriterPermission (/workspace/drive/api/v3/reference/files) field to false.

Files identified as abusive (https://support.google.com/docs/answer/148505) (such as harmful


software) are only downloadable by the file owner. Additionally, the get query parameter
acknowledgeAbuse=true must be included to indicate that the user has acknowledged the
risk of downloading potentially unwanted software or other abusive files. Your application
should interactively warn the user before using this query parameter.

Partial download
Partial download involves downloading only a specified portion of a file. You can specify the
portion of the file you want to download by using a byte range
(https://www.rfc-editor.org/rfc/rfc9110.html#name-byte-ranges) with the Range header. For
example:

Range: bytes=500-999

Note: Partial downloads are not supported while exporting Google Workspace documents.

https://developers.google.com/workspace/drive/api/guides/manage-downloads#node.js 3/7
6/27/25, 10:07 AM Download and export files | Google Drive | Google for Developers

Download blob file content at an earlier version


To download the content of blob files at an earlier version, use the revisions.get
(/workspace/drive/api/v3/reference/revisions/get) method with the ID of the file to download, the
ID of the revision, and the alt=media URL parameter. The alt=media URL parameter tells
the server that a download of content is being requested as an alternative response format.
Similar to files.get, the revisions.get method also accepts the optional query
parameter acknowledgeAbuse and the Range header. For more information on downloading
revisions, see Manage file revisions (/workspace/drive/api/guides/manage-revisions).

The request protocol is shown here.

GET https://www.googleapis.com/drive/v3/files/{FILE_ID edit}/revisions/{REVISION

Download blob file content in a browser


To download the content of blob files stored on Drive within a browser, instead of through
the API, use the webContentLink (/workspace/drive/api/v3/reference/files#webContentLink) field
of the files (/workspace/drive/api/v3/reference/files) resource. If the user has download
access to the file, a link for downloading the file and its contents is returned. You can either
redirect a user to this URL, or offer it as a clickable link.

Download blob file content during long-running operations


To download the content of blob files during long-running operations, use the
files.download (/workspace/drive/api/v3/reference/files/download) method with the ID of the
file to download. You can optionally set the ID of the revision. This is the only way to
download Google Vids files. For more information, see Manage long-running operations
(/workspace/drive/api/guides/long-running-operations).

Export Google Workspace document content


To export Google Workspace document byte content, use the files.export
(/workspace/drive/api/v3/reference/files/export) method with the ID of the file to export and the

https://developers.google.com/workspace/drive/api/guides/manage-downloads#node.js 4/7
6/27/25, 10:07 AM Download and export files | Google Drive | Google for Developers

correct MIME type (/workspace/drive/api/guides/ref-export-formats). Exported content is limited


to 10 MB.

The following code sample shows how to use the files.export method to export a
Google Workspace document in PDF format using the Drive API client libraries:

Note: If you're using the older Drive API v2, you can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

Java (#java)Python (#python)Node.jsPHP (#php).NET (#.net)


(#node.js)

drive/snippets/drive_v3/file_snippets/export_pdf.js

b.com/googleworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/export_pdf.js)

/**
* Download a Document file in PDF format
* @param{string} fileId file ID
* @return{obj} file status
* */
async function exportPdf(fileId) {
const {GoogleAuth} = require('google-auth-library');
const {google} = require('googleapis');

// Get credentials and build service


// TODO (developer) - Use appropriate auth mechanism for your app
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/drive',
});
const service = google.drive({version: 'v3', auth});

try {
const result = await service.files.export({
fileId: fileId,
mimeType: 'application/pdf',
});
console.log(result.status);
return result;
} catch (err) {
// TODO(developer) - Handle error
throw err;

https://developers.google.com/workspace/drive/api/guides/manage-downloads#node.js 5/7
6/27/25, 10:07 AM Download and export files | Google Drive | Google for Developers

}
}

This code sample uses the restricted drive scope that allows users to view and manage all
of your Drive files. To learn more about Drive scopes, refer to Choose Google Drive API
scopes (/workspace/drive/api/guides/api-specific-auth).

The code sample also declares the export MIME type as application/pdf. For a complete
list of all export MIME types supported for each Google Workspace document, refer to
Export MIME types for Google Workspace documents
(/workspace/drive/api/guides/ref-export-formats).

Export Google Workspace document content in a browser


To export Google Workspace document content within a browser, use the exportLinks
(/workspace/drive/api/v3/reference/files#exportLinks) field of the files
(/workspace/drive/api/v3/reference/files) resource. Depending on the document type, a link to
download the file and its contents is returned for every MIME type available. You can either
redirect a user to a URL, or offer it as a clickable link.

Export Google Workspace document content at an earlier


version in a browser
To export Google Workspace document content at an earlier version within a browser, use
the revisions.get (/workspace/drive/api/v3/reference/revisions/get) method with the ID of the
file to download and the ID of the revision to generate an export link from which you can
perform the download. If the user has download access to the file, a link for downloading
the file and its contents is returned. You can either redirect a user to this URL, or offer it as a
clickable link.

Export Google Workspace document content during long-


running operations
To export Google Workspace document content during long-running operations, use the
files.download (/workspace/drive/api/v3/reference/files/download) method with the ID of the

https://developers.google.com/workspace/drive/api/guides/manage-downloads#node.js 6/7
6/27/25, 10:07 AM Download and export files | Google Drive | Google for Developers

file to download and the ID of the revision. For more information, see Manage long-running
operations (/workspace/drive/api/guides/long-running-operations).

Related topics
Protect file content (/workspace/drive/api/guides/content-restrictions)

Export MIME types for Google Workspace documents


(/workspace/drive/api/guides/ref-export-formats)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/manage-downloads#node.js 7/7
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

Upload file data


The Google Drive API lets you upload file data when you create or update a File
(/workspace/drive/api/reference/rest/v3/files). For information about how to create a metadata-
only file, such as a folder, see Create metadata-only files
(/workspace/drive/api/guides/create-file#create-metadata-file).

There are three types of uploads you can perform:

Simple upload (uploadType=media): Use this upload type to transfer a small media
file (5 MB or less) without supplying metadata. To perform a simple upload, refer to
Perform a simple upload (#simple).

Multipart upload (uploadType=multipart): "Use this upload type to transfer a small


file (5 MB or less) along with metadata that describes the file, in a single request. To
perform a multipart upload, refer to Perform a multipart upload (#multipart).

Resumable upload (uploadType=resumable): Use this upload type for large files
(greater than 5 MB) and when there's a high chance of network interruption, such as
when creating a file from a mobile app. Resumable uploads are also a good choice for
most applications because they also work for small files at a minimal cost of one
additional HTTP request per upload. To perform a resumable upload, refer to Perform
a resumable upload (#resumable).

The Google API client libraries implement at least one of these types of uploads. Refer to
the client library documentation (/workspace/drive/api/guides/downloads) for additional details
about how to use each of the types.

Note: In the Drive API documentation, media refers to all available files with MIME types supported for
upload to Drive. For a list of supported MIME types, refer to Google Workspace and Drive supported
MIME types (/workspace/drive/api/guides/mime-types).

Note: Users can upload any file type to Drive using the Drive UI and Drive attempts to detect and
automatically set the MIME type. If the MIME type can't be detected, the MIME type is set to
application/octet-stream.

Use PATCH vs. PUT

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 1/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

As a refresher, the HTTP verb PATCH supports a partial file resource update whereas the
HTTP verb PUT supports full resource replacement. Note that PUT can introduce breaking
changes when adding a new field to an existing resource.

When uploading a file resource, use the following guidelines:

Use the HTTP verb documented on the API reference for the initial request of a
resumable upload or for the only request of a simple or multipart upload.

Use PUT for all subsequent requests for a resumable upload once the request has
started. These requests are uploading content no matter the method being called.

Perform a simple upload


To perform a simple upload, use the files.create
(/workspace/drive/api/reference/rest/v3/files/create) method with uploadType=media.

Note: If you're using the older Drive API v2, use the files.insert
(/workspace/drive/api/v2/reference/files/insert) method. You can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

The following shows how to perform a simple upload:

HTTP
(#http)

1. Create a POST request to the method's /upload URI with the query parameter of
uploadType=media:

POST https://www.googleapis.com/upload/drive/v3/files?
uploadType=media

2. Add the file's data to the request body.

3. Add these HTTP headers:

Content-Type. Set to the MIME media type of the object being uploaded.

Content-Length. Set to the number of bytes you upload. If you use


chunked transfer encoding, this header is not required.

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 2/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

4. Send the request. If the request succeeds, the server returns the HTTP 200 OK
status code along with the file's metadata. {HTTP}

star Note: To update an existing file, use PATCH.

When you perform a simple upload, basic metadata is created and some attributes are
inferred from the file, such as the MIME type or modifiedTime. You can use a simple
upload in cases where you have small files and file metadata isn't important.

Perform a multipart upload


A multipart upload request lets you upload metadata and data in the same request. Use this
option if the data you send is small enough to upload again, in its entirety, if the connection
fails.

To perform a multipart upload, use the files.create


(/workspace/drive/api/reference/rest/v3/files/create) method with uploadType=multipart.

Note: If you're using the older Drive API v2, use the files.insert
(/workspace/drive/api/v2/reference/files/insert) method. You can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

The following shows how to perform a multipart upload:

Java (#java)Python (#python)Node.jsPHP (#php).NET (#.net)HTTP (#http)


(#node.js)

drive/snippets/drive_v3/file_snippets/upload_basic.js

com/googleworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/upload_basic.js)

/**
* Insert new file.
* @return{obj} file Id
* */
async function uploadBasic() {
const fs = require('fs');
const {GoogleAuth} = require('google-auth-library');
const {google} = require('googleapis');

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 3/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

// Get credentials and build service


// TODO (developer) - Use appropriate auth mechanism for your app
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/drive',
});
const service = google.drive({version: 'v3', auth});
const requestBody = {
name: 'photo.jpg',
fields: 'id',
};
const media = {
mimeType: 'image/jpeg',
body: fs.createReadStream('files/photo.jpg'),
};
try {
const file = await service.files.create({
requestBody,
media: media,
});
console.log('File Id:', file.data.id);
return file.data.id;
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}

When creating files, they should specify a file extension in the file's name field. For example,
when creating a photo JPEG file, you might specify something like "name": "photo.jpg"
in the metadata. Subsequent calls to files.get
(/workspace/drive/api/reference/rest/v3/files/get) return the read-only fileExtension property
containing the extension originally specified in the name field.

Perform a resumable upload


A resumable upload lets you resume an upload operation after a communication failure
interrupts the flow of data. Because you don't have to restart large file uploads from the
start, resumable uploads can also reduce your bandwidth usage if there's a network failure.

Resumable uploads are useful when your file sizes might vary greatly or when there's a fixed
time limit for requests (such as mobile OS background tasks and certain App Engine
requests). You might also use resumable uploads for situations where you want to show an
upload progress bar.

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 4/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

A resumable upload consists of several high-level steps:

1. Send the initial request and retrieve the resumable session URI.

2. Upload the data and monitor upload state.

3. (optional) If the upload is disturbed, resume the upload.

Send the initial request


To initiate a resumable upload, use the files.create
(/workspace/drive/api/reference/rest/v3/files/create) method with uploadType=resumable.

Note: If you're using the older Drive API v2, use the files.insert
(/workspace/drive/api/v2/reference/files/insert) method. You can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

HTTP
(#http)

1. Create a POST request to the method's /upload URI with the query parameter of
uploadType=resumable:

POST https://www.googleapis.com/upload/drive/v3/files?
uploadType=resumable

If the initiation request succeeds, the response includes a 200 OK HTTP status
code. In addition, it includes a Location header that specifies the resumable
session URI:

HTTP/1.1 200 OK
Location: https://www.googleapis.com/upload/drive/v3/files?uploadTy
Content-Length: 0

Save the resumable session URI so you can upload the file data and query the
upload status. A resumable session URI expires after one week.

star Note: To update an existing file, use PUT.

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 5/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

2. If you have metadata for the file, add the metadata to the request body in JSON
format. Otherwise, leave the request body empty.

3. Add these HTTP headers:

X-Upload-Content-Type. Optional. Set to the MIME type of the file data,


which is transferred in subsequent requests. If the MIME type of the data
is not specified in the metadata or through this header, the object is
served as application/octet-stream.

X-Upload-Content-Length. Optional. Set to the number of bytes of file


data, which is transferred in subsequent requests.

Content-Type. Required if you have metadata for the file. Set to


application/json; charset=UTF-8.

Content-Length. Required unless you use chunked transfer encoding.


Set to the number of bytes in the body of this initial request.

4. Send the request. If the session initiation request succeeds, the response
includes a 200 OK HTTP status code. In addition, the response includes a
Location header that specifies the resumable session URI. Use the resumable
session URI to upload the file data and query the upload status. A resumable
session URI expires after one week.

5. Copy and save the resumable session URL.

6. Continue to Upload the content (#uploading).

Upload the content


There are two ways to upload a file with a resumable session:

Upload content in a single request: Use this approach when the file can be uploaded
in one request, if there's no fixed time limit for any single request, or you don't need to
display an upload progress indicator. This approach is best because it requires fewer
requests and results in better performance.

Upload the content in multiple chunks: Use this approach if you must reduce the
amount of data transferred in any single request. You might need to reduce data
transferred when there's a fixed time limit for individual requests, as can be the case
for certain classes of App Engine requests. This approach is also useful if you must
provide a customized indicator to show the upload progress.

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 6/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

1. Create a PUT request to the resumable session URI.

2. Add the chunk's data to the request body. Create chunks in multiples of 256 KB
(256 x 1024 bytes) in size, except for the final chunk that completes the upload.
Keep the chunk size as large as possible so that the upload is efficient.

3. Add these HTTP headers:

Content-Length. Set to the number of bytes in the current chunk.

Content-Range. Set to show which bytes in the file you upload. For
example, Content-Range: bytes 0-524287/2000000 shows that you
upload the first 524,288 bytes (256 x 1024 x 2) in a 2,000,000 byte file.

4. Send the request, and process the response. If the upload request is
interrupted, or if you receive a 5xx response, follow the procedure in Resume
an interrupted upload (#resume-upload).

5. Repeat steps 1 through 4 for each chunk that remains in the file. Use the Range
header in the response to determine where to start the next chunk. Don't
assume that the server received all bytes sent in the previous request.

When the entire file upload is complete, you receive a 200 OK or 201 Created
response, along with any metadata associated with the resource.

Resume an interrupted upload


If an upload request is terminated before a response, or if you receive a 503 Service
Unavailable response, then you must resume the interrupted upload.

HTTP
(#http)

1. To request the upload status, create an empty PUT request to the resumable
session URI.

2. Add a Content-Range header to indicate that the current position in the file is
unknown. For example, set the Content-Range to */2000000 if your total file
length is 2,000,000 bytes. If you don't know the full size of the file, set the
Content-Range to */*.

3. Send the request.

4. Process the response:

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 7/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

A 200 OK or 201 Created response indicates that the upload was


completed, and no further action is necessary.

A 308 Resume Incomplete response indicates that you must continue to


upload the file.

A 404 Not Found response indicates the upload session has expired and
the upload must be restarted from the beginning.

5. If you received a 308 Resume Incomplete response, process the Range header
of the response to determine which bytes the server has received. If the
response doesn't have a Range header, no bytes have been received. For
example, a Range header of bytes=0-42 indicates that the first 43 bytes of the
file were received and that the next chunk to upload would start with byte 44.

6. Now that you know where to resume the upload, continue to upload the file
beginning with the next byte. Include a Content-Range header to indicate
which portion of the file you send. For example, Content-Range: bytes 43-
1999999 indicates that you send bytes 44 through 2,000,000.

Handle media upload errors


When you upload media, follow these best practices to handle errors:

For 5xx errors, resume or retry uploads that fail due to connection interruptions. For
further information on handling 5xx errors, refer to 500, 502, 503, 504 errors
(/workspace/drive/api/guides/handle-errors#5xx-errors).

For 403rate limit errors, retry the upload. For further information about handling
403 rate limit errors, refer to 403 error: rateLimitExceeded
(/workspace/drive/api/guides/handle-errors#rate-limit).

For any 4xx errors (including 403) during a resumable upload, restart the upload.
These errors indicate the upload session has expired and must be restarted by
requesting a new session URI (#resumable). Upload sessions also expire after one
week of inactivity.

Import to Google Docs types


When you create a file in Drive, you might want to convert the file into a Google Workspace
file type, such as Google Docs or Sheets. For example, maybe you want to transform a

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 8/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

document from your favorite word processor into a Docs to take advantage of its features.

To convert a file to a specific Google Workspace file type, specify the Google Workspace
mimeType when creating the file.

Note: If you're using the older Drive API v2, include the files.insert convert
(/workspace/drive/api/reference/rest/v2/files/insert#query-parameters) query parameter and specify
the Google Workspace mimeType when creating the file.

The following shows how to convert a CSV file to a Google Workspace sheet:

Note: If you're using the older Drive API v2, you can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

Java (#java)Python (#python)Node.jsPHP (#php).NET (#.net)


(#node.js)

drive/snippets/drive_v3/file_snippets/upload_with_conversion.js

eworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/upload_with_conversion.js)

/**
* Upload file with conversion
* @return{obj} file Id
* */
async function uploadWithConversion() {
const fs = require('fs');
const {GoogleAuth} = require('google-auth-library');
const {google} = require('googleapis');
// Get credentials and build service
// TODO (developer) - Use appropriate auth mechanism for your app
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/drive',
});
const service = google.drive({version: 'v3', auth});
const fileMetadata = {
name: 'My Report',
mimeType: 'application/vnd.google-apps.spreadsheet',
};
const media = {
mimeType: 'text/csv',
body: fs.createReadStream('files/report.csv'),

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 9/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

};

try {
const file = await service.files.create({
requestBody: fileMetadata,
media: media,
fields: 'id',
});
console.log('File Id:', file.data.id);
return file.data.id;
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}

To see if a conversion is available, check the about


(/workspace/drive/api/reference/rest/v3/about#resource) resource's importFormats array before
creating the file. Supported conversions are available dynamically in this array. Some
common import formats are:

From To

Microsoft Word, OpenDocument Text, HTML, RTF, plain text Google Docs

Microsoft Excel, OpenDocument Spreadsheet, CSV, TSV, plain Google Sheets


text

Microsoft PowerPoint, OpenDocument Presentation Google Slides

JPEG, PNG, GIF, BMP, PDF Google Docs (embeds the image in a
Doc)

Plain text (special MIME type), JSON Google Apps Script

When you upload and convert media during an update request to a Docs, Sheets, or Slides
file, the full contents of the document are replaced.

When you convert an image to a Docs, Drive uses Optical Character Recognition (OCR) to
convert the image to text. You can improve the quality of the OCR algorithm by specifying
the applicable BCP 47 (https://tools.ietf.org/html/bcp47) language code in the ocrLanguage
(/workspace/drive/api/reference/rest/v3/files/create#query-parameters) parameter. The extracted
text appears in the Doc alongside the embedded image.

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 10/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

Use a pre-generated ID to upload files


The Drive API lets you retrieve a list of pre-generated file IDs that are used to upload and
create resources. Upload and file creation requests can use these pre-generated IDs. Set
the id field in the file metadata.

To create pre-generated IDs, call files.generateIds


(/workspace/drive/api/reference/rest/v3/files/generateIds) with the number of IDs to create.

You can safely retry uploads with pre-generated IDs if there's an indeterminate server error
or timeout. If the file was successfully created, subsequent retries return a HTTP 409 error
and they don't create duplicate files.

Note: Pre-generated IDs aren't supported for built-in Google Docs creation, or uploads where conversion
to built-in Docs format is requested.

Define indexable text for unknown file types

Note: Beginning October 31, 2022, indexable text can be shown in result snippets and affects search
results in more places, including Cloud Search and the search overlay in Drive and Gmail.

Users can use the Drive UI to find document content. You can also use files.list
(/workspace/drive/api/reference/rest/v2/files/list) and the fullText field to search for content
from your app. For more information, see Search for files and folders
(/workspace/drive/api/guides/search-files).

Drive automatically indexes documents for search when it recognizes the file type, including
text documents, PDFs, images with text, and other common types. If your app saves other
types of files (such as drawings, video, and shortcuts), you can improve the discoverability
by supplying indexable text in the contentHints.indexableText field of the file.

For more information about indexable text, see Manage file metadata
(/workspace/drive/api/guides/file#indexable-text).

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 11/12
6/27/25, 10:07 AM Upload file data | Google Drive | Google for Developers

Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its


affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/manage-uploads#http---multiple-requests 12/12
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

Share files, folders, and drives


Every Google Drive file, folder, and shared drive have associated permissions
(/workspace/drive/api/reference/rest/v3/permissions) resources. Each resource identifies the
permission for a specific type (user, group, domain, anyone) and role (owner, organizer,
fileOrganizer, writer, commenter, reader). For example, a file might have a permission
granting a specific user (type=user) read-only access (role=reader) while another
permission grants members of a specific group (type=group) the ability to add comments
to a file (role=commenter).

For a complete list of roles and the operations permitted by each, refer to Roles and
permissions (/workspace/drive/api/guides/ref-roles).

Note: The list of all permission resources associated with a file, folder, or shared drive, is known as an
Access Control List (ACL).

How permissions work


Permission lists for a folder propagate downward. All child files and folders inherit
permissions from the parent. Whenever permissions or the hierarchy is changed, the
propagation occurs recursively through all nested folders. For example, if a file exists in a
folder and that folder is then moved within another folder, the permissions on the new
folder propagate to the file. If the new folder grants the file user a new role, such as "writer,"
it overrides their old role.

Conversely, if a file inherits role=writer from a folder, and is moved to another folder that
provides a "reader" role, the file now inherits role=reader.

Inherited permissions can't be removed from a file or folder in a shared drive. Instead these
permissions must be adjusted on the direct or indirect parent from which they were
inherited. Inherited permissions can be removed from items under "My Drive" or "Shared
with me."

Conversely, inherited permissions can be overridden on a file or folder in My Drive. So, if a


file inherits role=writer from a My Drive folder, you can set role=reader on the file to
lower its permission level.

https://developers.google.com/workspace/drive/api/guides/manage-sharing 1/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

Warning: In "My Drive" and "Shared with me," propagation might stop if a different user owns the child file
or folder and the file or folder has more restrictive permissions that override the propagation. For
example, a parent folder might have type=group and role=commenter, but a child folder has
type=group (with the same email) and role=reader. Since reader is more restrictive than commenter,
the child folder's permission overrides propagation from the parent folder.

Understand file capabilities


The permissions (/workspace/drive/api/reference/rest/v3/permissions) resource doesn't
ultimately determine the current user's ability to perform actions on a file or folder. Instead,
the files (/workspace/drive/api/reference/rest/v3/files) resource contains a collection of
boolean capabilities fields used to indicate whether an action can be performed on a file
or folder. The Google Drive API sets these fields based on the current user's permissions
resource associated with the file or folder.

For example, when Alex logs into your app and tries to share a file, Alex's role is checked for
permissions on the file. If the role allows them to share a file, the capabilities related to
the file, such as canShare, are filled in relative to the role. If Alex wants to share the file, your
app checks the capabilities to ensure canShare is set to true.

For an example of retrieving file capabilities, see Get file capabilities (#get-capabilities).

Get file capabilities


When your app opens a file, it should check the file's capabilities and render the UI to reflect
the permissions of the current user. For example, if the user doesn't have a canComment
capability on the file, the ability to comment should be disabled in the UI.

To check the capabilities, call the get() (/workspace/drive/api/reference/rest/v3/files/get)


method on the files (/workspace/drive/api/reference/rest/v3/files) resource with the fileId
path parameter and the fields parameter set to the capabilities field. For further
information on returning fields using the fields parameter, see Return specific fields
(/workspace/drive/api/guides/fields-parameter).

The following code sample shows how to verify user permissions. The response returns a
list of capabilities the user has on the file. Each capability corresponds to a fine-grained
action that a user can take. Some fields are only populated for items in shared drives.

Request

https://developers.google.com/workspace/drive/api/guides/manage-sharing 2/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

GET https://www.googleapis.com/drive/v3/files/FILE_ID edit?fields=capabilities

Response

{
"capabilities": {
"canAcceptOwnership": false,
"canAddChildren": false,
"canAddMyDriveParent": false,
"canChangeCopyRequiresWriterPermission": true,
"canChangeSecurityUpdateEnabled": false,
"canComment": true,
"canCopy": true,
"canDelete": true,
"canDownload": true,
"canEdit": true,
"canListChildren": false,
"canModifyContent": true,
"canModifyContentRestriction": true,
"canModifyLabels": true,
"canMoveChildrenWithinDrive": false,
"canMoveItemOutOfDrive": true,
"canMoveItemWithinDrive": true,
"canReadLabels": true,
"canReadRevisions": true,
"canRemoveChildren": false,
"canRemoveMyDriveParent": true,
"canRename": true,
"canShare": true,
"canTrash": true,
"canUntrash": true
}
}

Scenarios for sharing Drive resources


There are five different types of sharing scenarios:

1. To share a file in My Drive, the user must have role=writer or role=owner.

https://developers.google.com/workspace/drive/api/guides/manage-sharing 3/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

If the writersCanShare (/workspace/drive/api/reference/rest/v3/files) boolean value


is set to false for the file, the user must have role=owner.

If the user with role=writer has temporary access governed by an expiration


date and time, they can't share the file. For more information, see Set an
expiration date to limit file access (#expiration-date).

2. To share a folder in My Drive, the user must have role=writer or role=owner.

If the writersCanShare boolean value is set to false for the file, the user must
have the more permissive role=owner.

Temporary access (governed by an expiration date and time) isn't allowed on My


Drive folders with role=writer. For more information, see Set an expiration
date to limit file access (#expiration-date).

3. To share a file in a shared drive, the user must have role=writer,


role=fileOrganizer, or role=organizer.

The writersCanShare setting doesn't apply to items in shared drives. It's


treated as if it's always set to true.

4. To share a folder in a shared drive, the user must have role=organizer.

If the sharingFoldersRequiresOrganizerPermission restriction on a shared


drive is set to false, users with role=fileOrganizer can share folders in that
shared drive.

5. To manage shared drive membership, the user must have role=organizer. Only
users and groups can be members of shared drives.

Create a permission
The following two fields are necessary when creating a permission:

type (/workspace/drive/api/reference/rest/v3/permissions): The type identifies the


permission scope (user, group, domain, or anyone). A permission with type=user
applies to a specific user whereas a permission with type=domain applies to
everyone in a specific domain.

role (/workspace/drive/api/reference/rest/v3/permissions): The role field identifies


operations the type can perform. For example, a permission with type=user and
role=reader grants a specific user read-only access to the file or folder. Or, a
permission with type=domain and role=commenter lets everyone in the domain add

https://developers.google.com/workspace/drive/api/guides/manage-sharing 4/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

comments to a file. For a complete list of roles and the operations permitted by each,
refer to Roles and permissions (/workspace/drive/api/guides/ref-roles).

When you create a permission where type=user or type=group, you must also provide an
emailAddress (/workspace/drive/api/reference/rest/v3/permissions) to tie the specific user or
group to the permission.

When you create a permission where type=domain, you must also provide a domain
(/workspace/drive/api/reference/rest/v3/permissions) to tie a specific domain to the permission.

To create a permission:

1. Use the create() (/workspace/drive/api/reference/rest/v3/permissions/create) method with


the fileId path parameter for the associated file or folder.

2. In the request body, specify the type and role.

3. If type=user or type=group, provide an emailAddress. If type=domain, provide a


domain.

The following code sample shows how to create a permission. The response returns an
instance of a Permission (/workspace/drive/api/reference/rest/v3/permissions#Permission)
resource, including the assigned permissionId.

Request

POST https://www.googleapis.com/drive/v3/files/FILE_ID edit/permissions

{
"requests": [
{
"type": "user",
"role": "commenter",
"emailAddress": "alex@altostrat.com"
}
]
}

Response

https://developers.google.com/workspace/drive/api/guides/manage-sharing 5/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

{
"kind": "drive#permission",
"id": "PERMISSION_ID edit",
"type": "user",
"role": "commenter"
}

Use target audiences


Target audiences are groups of people—such as departments or teams—that you can
recommend for users to share their items with. You can encourage users to share items
with a more specific or limited audience rather than your entire organization. Target
audiences can help you improve the security and privacy of your data, and make it easier for
users to share appropriately. For more information, see About target audiences
(https://support.google.com/a/answer/9934697).

To use target audiences:

1. In the Google Admin console, go to Menu menu > Directory > Target audiences.
Go to Target audiences (https://admin.google.com/ac/targetaudiences)

You must be signed in using an account with super administrator


(https://support.google.com//a/answer/2405986#super_admin) privileges for this task.

2. In the Target audiences list, click the name of the target audience. To create a target
audience, see Create a target audience (https://support.google.com/a/answer/9935192)

3. Copy the unique ID from the target audience URL:


https://admin.google.com/ac/targetaudiences/ID.

4. Create a permission (#create-permission) with type=domain, and set the domain field to
ID.audience.googledomains.com.

To view how users interact with target audiences, see User experience for link sharing
(https://support.google.com/a/answer/9934697#ue).

List all permissions

https://developers.google.com/workspace/drive/api/guides/manage-sharing 6/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

Use the list() (/workspace/drive/api/reference/rest/v3/permissions/list) method on the


permissions (/workspace/drive/api/reference/rest/v3/permissions) resource to retrieve all
permissions for a file, folder, or shared drive.

The following code sample shows how to get all permissions. The response returns a list of
permissions.

Request

GET https://www.googleapis.com/drive/v3/files/FILE_ID edit/permissions

Response

{
"kind": "drive#permissionList",
"permissions": [
{
"id": "PERMISSION_ID edit",
"type": "user",
"kind": "drive#permission",
"role": "commenter"
}
]
}

Update permissions
To update permissions on a file or folder, you can change the assigned role. For more
information on finding the role source, see Determine the role source (#role-source).

1. Call the update() (/workspace/drive/api/reference/rest/v3/permissions/update) method on


the permissions (/workspace/drive/api/reference/rest/v3/permissions) resource with the
permissionId path parameter set to the permission to change and the fileId path
parameter set to the associated file, folder, or shared drive. To find the permissionId,
use the list() (/workspace/drive/api/reference/rest/v3/permissions/list) method on the
permissions resource with the fileId path parameter.

https://developers.google.com/workspace/drive/api/guides/manage-sharing 7/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

star Note: The permissionId represents the user or group to which the permission is granted, such as
alex@altostrat.com or hiking-club@altostrat.com. The permissionId remains the same for
that user or group across all files, folders, and shared drives.

2. In the request, identify the new role.

You can grant permissions on individual files or folders in a shared drive even if the user or
group is already a member. For example, Alex has role=commenter as part of their
membership to a shared drive. However, your app can grant Alex role=writer for a file in a
shared drive. In this case, because the new role is more permissive than the role granted
through their membership, the new permission becomes the effective role for the file or
folder.

The following code sample shows how to change permissions on a file or folder from
commenter to writer. The response returns an instance of a permissions resource.

Request

PATCH https://www.googleapis.com/drive/v3/files/FILE_ID edit/permissions/PERMISS

{
"requests": [
{
"role": "writer"
}
]
}

Response

{
"kind": "drive#permission",
"id": "PERMISSION_ID edit",
"type": "user",
"role": "writer"
}

https://developers.google.com/workspace/drive/api/guides/manage-sharing 8/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

Determine the role source


To change the role on a file or folder, you must know the source of the role. For shared
drives, the source of a role can be based on membership to the shared drive, the role on a
folder, or the role on a file.

To determine the role source for a shared drive, or items within that drive, call the get()
(/workspace/drive/api/reference/rest/v3/permissions/get) method on the permissions
(/workspace/drive/api/reference/rest/v3/permissions) resource with the fileId and
permissionId path parameters, and the fields parameter set to the permissionDetails
field.

To find the permissionId, use the list()


permissions resource
(/workspace/drive/api/reference/rest/v3/permissions/list) method on the
with the fileId path parameter. To fetch the permissionDetails field on the list request,
set the fields parameter to permissions/permissionDetails.

This field enumerates all inherited and direct file permissions for the user, group, or domain.

The following code sample shows how to determine the role source. The response returns
the permissionDetails of a permissions (/workspace/drive/api/reference/rest/v3/permissions)
resource. The inheritedFrom field provides the ID of the item from which the permission is
inherited.

Request

GET https://www.googleapis.com/drive/v3/files/FILE_ID edit/permissions/PERMISSIO

Response

{
"permissionDetails": [
{
"permissionType": "member",
"role": "commenter",
"inheritedFrom": "INHERITED_FROM_ID edit",
"inherited": true
},
{
"permissionType": "file",
"role": "writer",

https://developers.google.com/workspace/drive/api/guides/manage-sharing 9/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

"inherited": false
}
]
}

Update multiple permissions with batch requests


We strongly recommend using batch requests
(/workspace/drive/api/guides/performance#batch-requests) to modify multiple permissions.

The following is an example of performing a batch permission modification with a client


library.

Note: If you're using the older Drive API v2, you can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

Java (#java)Python (#python)Node.jsPHP (#php).NET (#.net)


(#node.js)

drive/snippets/drive_v3/file_snippets/share_file.js

ub.com/googleworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/share_file.js)

/**
* Batch permission modification
* @param{string} fileId file ID
* @param{string} targetUserEmail username
* @param{string} targetDomainName domain
* @return{list} permission id
* */
async function shareFile(fileId, targetUserEmail, targetDomainName) {
const {GoogleAuth} = require('google-auth-library');
const {google} = require('googleapis');

// Get credentials and build service


// TODO (developer) - Use appropriate auth mechanism for your app
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/drive',
});
const service = google.drive({version: 'v3', auth});
const permissionIds = [];

https://developers.google.com/workspace/drive/api/guides/manage-sharing 10/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

const permissions = [
{
type: 'user',
role: 'writer',
emailAddress: targetUserEmail, // 'user@partner.com',
},
{
type: 'domain',
role: 'writer',
domain: targetDomainName, // 'example.com',
},
];
// Note: Client library does not currently support HTTP batch
// requests. When possible, use batched requests when inserting
// multiple permissions on the same item. For this sample,
// permissions are inserted serially.
for (const permission of permissions) {
try {
const result = await service.permissions.create({
resource: permission,
fileId: fileId,
fields: 'id',
});
permissionIds.push(result.data.id);
console.log(`Inserted permission id: ${result.data.id}`);
} catch (err) {
// TODO(developer): Handle failed permissions
console.error(err);
}
}
return permissionIds;
}

Delete a permission
To revoke access to a file or folder, call the delete()
(/workspace/drive/api/reference/rest/v3/permissions/delete) method on the permissions
(/workspace/drive/api/reference/rest/v3/permissions) resource with the fileId and the
permissionId path parameters set to delete the permission.

For items in "My Drive," it's possible to delete an inherited permission. Deleting an inherited
permission revokes access to the item and child items, if any.

https://developers.google.com/workspace/drive/api/guides/manage-sharing 11/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

For items in a shared drive, inherited permissions cannot be revoked. Update or delete the
permission on the parent file or folder instead.

The delete() method is also used to delete permissions directly applied to a shared drive
file or folder.

The following code sample shows how to revoke access by deleting a permissionId. If
successful, the response body is empty. To confirm the permission is removed, use the
list() (/workspace/drive/api/reference/rest/v3/permissions/list) method on the permissions
resource with the fileId path parameter.

Request

DELETE https://www.googleapis.com/drive/v3/files/FILE_ID edit/permissions/PERMIS

Set an expiration date to limit file access


When you're working with people on a sensitive project, you might want to restrict their
access to certain files in Drive after a period of time. For files in My Drive, you can set an
expiration date to limit or remove access to that file.

To set the expiration date:

Use the create() (/workspace/drive/api/reference/rest/v3/permissions/create) method on


the permissions (/workspace/drive/api/reference/rest/v3/permissions) resource and set
the expirationTime (/workspace/drive/api/reference/rest/v3/permissions) field (along with
the other required fields). For more information, see Create a permission
(#create-permission).

Use the update() (/workspace/drive/api/reference/rest/v3/permissions/update) method on


the permissions resource and set the expirationTime field (along with the other
required fields). For more information, see Update permissions (#update-permissions).

The expirationTime field denotes when the permission expires using RFC 3339 date-time
(https://datatracker.ietf.org/doc/html/rfc3339). Expiration times have the following restrictions:

They can only be set on user and group permissions.

Time must be in the future.

The time cannot be more than a year in the future.

https://developers.google.com/workspace/drive/api/guides/manage-sharing 12/13
6/27/25, 10:06 AM Share files, folders, and drives | Google Drive | Google for Developers

Note: If you're using the older Drive API v2, use the expirationDate
(/workspace/drive/api/reference/rest/v2/permissions) field. Learn how to migrate to Drive API v3
(/workspace/drive/api/guides/migrate-to-v3).

For more information about expiration date, see the following articles:

Set an expiration date for file access


(https://support.google.com/a/users/answer/13005112#set-expiration-date)

Add an expiry date (https://support.google.com/drive/answer/7166529#addexpiration)

Related topics
Manage pending access proposals (/workspace/drive/api/guides/pending-access)

Manage folders with limited and expansive access


(/workspace/drive/api/guides/limited-expansive-access)

Transfer file ownership (/workspace/drive/api/guides/transfer-file)

Protect file content (/workspace/drive/api/guides/content-restrictions)

Access link-shared drive files using resource keys


(/workspace/drive/api/guides/resource-keys)

Roles and permissions (/workspace/drive/api/guides/ref-roles)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-10 UTC.

https://developers.google.com/workspace/drive/api/guides/manage-sharing 13/13
6/27/25, 10:06 AM Search for files and folders | Google Drive | Google for Developers

Search for files and folders


The Google Drive API supports several ways to search files and folders.

You can use the files.list (/workspace/drive/api/reference/rest/v3/files/list) method to return


all or some of a Drive user's files and folders. The files.list method can also be used to
retrieve the fileId required for some resource methods (such as files.get
(/workspace/drive/api/reference/rest/v3/files/get) and files.update
(/workspace/drive/api/reference/rest/v3/files/update)).

Search for all files and folders on the current user's My Drive

Use the files.list method without any parameters to return all files and folders.

GET https://www.googleapis.com/drive/v3/files

Search for specific files or folders on the current user's My


Drive
To search for a specific set of files or folders, use the query string q field with the
files.list (/workspace/drive/api/reference/rest/v3/files/list) method to filter the files to return
by combining one or more search terms.

A query string contains the following three parts:

query_term operator values

Where:

query_term is the query term or field to search upon.

operator specifies the condition for the query term.

values are the specific values you want to use to filter your search results.

https://developers.google.com/workspace/drive/api/guides/search-files 1/6
6/27/25, 10:06 AM Search for files and folders | Google Drive | Google for Developers

To view the query terms and operators that you can use filter files and folders, see Search
query terms and operators (/workspace/drive/api/guides/ref-search-terms#file-properties).

For example, the following query string filters the search to only return folders by setting the
MIME type:

q: mimeType = 'application/vnd.google-apps.folder'

For more information on MIME types, see Google Workspace and Google Drive supported
MIME types (/workspace/drive/api/guides/mime-types).

Query string examples


The following table lists examples of some basic query strings. The actual code differs
depending on the client library you use for your search.

Important: The following query terms use fields from the Drive API v3
(/workspace/drive/api/reference/rest/v3). Some resource fields changed between v2 and v3. For
example, files.name replaces files.title. If you're using Drive API v2
(/workspace/drive/api/reference/rest/v2), adjust these queries to use the v2 fields. For more
information, see Drive API v2 and v3 comparison reference
(/workspace/drive/api/guides/v2-to-v3-reference).

You must also escape special characters in your file names to make sure the query works
correctly. For example, if a filename contains both an apostrophe (') and a backslash ("\")
character, use a backslash to escape them: name contains 'quinn\'s paper\\essay'.

Note: These examples use the unencoded q parameter, where name = 'hello' is encoded as
name+%3d+%27hello%27. Client libraries handle this encoding automatically.

What you want to query Example

Files with the name "hello" name = 'hello'

Files with a name containing the words "hello" and name contains 'hello' and name
"goodbye" contains 'goodbye'

https://developers.google.com/workspace/drive/api/guides/search-files 2/6
6/27/25, 10:06 AM Search for files and folders | Google Drive | Google for Developers

What you want to query Example

Files with a name that does not contain the word not name contains 'hello'
"hello"

Files that contain the text "important" and in the fullText contains 'important' and
trash trashed = true

Files that contain the word "hello" fullText contains 'hello'

Files that don't have the word "hello" not fullText contains 'hello'

Files that contain the exact phrase "hello world" fullText contains '"hello world"'

Files with a query that contains the "\" character (for fullText contains '\\authors'
example, "\authors")

Files that are folders mimeType = 'application/vnd.google-


apps.folder'

Files that are not folders mimeType != 'application/vnd.google-


apps.folder'

Files modified after a given date (default time zone modifiedTime > '2012-06-04T12:00:00'
is UTC)

Image or video files modified after a specific date modifiedTime > '2012-06-04T12:00:00'
and (mimeType contains 'image/' or
mimeType contains 'video/')

Files that are starred starred = true

Files within a collection (for example, the folder ID in '1234567' in parents


the parents collection)

Files in an application data folder 'appDataFolder' in parents


(/workspace/drive/api/guides/appdata) in a
collection

Files for which user "test@example.org" is the 'test@example.org' in owners


owner

Files for which user "test@example.org" has write 'test@example.org' in writers


permission

Files for which members of the group 'group@example.org' in writers


"group@example.org" have write permission

Files shared with the authorized user with "hello" in sharedWithMe and name contains 'hello'
the name

https://developers.google.com/workspace/drive/api/guides/search-files 3/6
6/27/25, 10:06 AM Search for files and folders | Google Drive | Google for Developers

What you want to query Example

Files with a custom file property visible to all apps properties has { key='mass' and
value='1.3kg' }

Files with a custom file property private to the appProperties has { key='additionalID'
requesting app and value='8e8aceg2af2ge72e78' }

Files that have not been shared with anyone or visibility = 'limited'
domains (only private, or shared with specific users
or groups)

Filter search results with a client library


The following code sample shows how to use a client library to filter search results to file
names and IDs of JPEG files. This sample uses the mimeType query term to narrow results
to files of type image/jpeg. It also sets spaces to drive to further narrow the search to the
Drive space (/workspace/drive/api/guides/about-files#org). When nextPageToken returns null,
there are no more results.

Note: If you're using the older Drive API v2, you can find code samples in GitHub
(https://github.com/googleworkspace). Learn how to migrate to Drive API v3

(/workspace/drive/api/guides/migrate-to-v3).

Java (#java)Python (#python)Node.jsPHP (#php)


(#node.js)

drive/snippets/drive_v3/file_snippets/search_file.js

b.com/googleworkspace/node-samples/blob/main/drive/snippets/drive_v3/file_snippets/search_file.js)

/**
* Search file in drive location
* @return{obj} data file
* */
async function searchFile() {
const {GoogleAuth} = require('google-auth-library');
const {google} = require('googleapis');

// Get credentials and build service


// TODO (developer) - Use appropriate auth mechanism for your app
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/drive',

https://developers.google.com/workspace/drive/api/guides/search-files 4/6
6/27/25, 10:06 AM Search for files and folders | Google Drive | Google for Developers

});
const service = google.drive({version: 'v3', auth});
const files = [];
try {
const res = await service.files.list({
q: 'mimeType=\'image/jpeg\'',
fields: 'nextPageToken, files(id, name)',
spaces: 'drive',
});
Array.prototype.push.apply(files, res.files);
res.data.files.forEach(function(file) {
console.log('Found file:', file.name, file.id);
});
return res.data.files;
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}

Search for files with a custom file property


To search for files with a custom file property, use either the properties or the
appProperties search query term with a key and value. For example, to search for a
custom file property that's private to the requesting app called additionalID with a value
of 8e8aceg2af2ge72e78:

appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }

For more information, see Add custom file properties (/workspace/drive/api/guides/properties).

Search for files with a specific label or field value


To search for files with specific labels, use the labels search query term with a specific
label ID. For example: 'labels/LABEL_ID' in labels. If successful, the response body
contains all file instances where the label's applied.

To search for files without a specific label ID: Not 'labels/LABEL_ID' in labels.

https://developers.google.com/workspace/drive/api/guides/search-files 5/6
6/27/25, 10:06 AM Search for files and folders | Google Drive | Google for Developers

You can also search for files based on specific field values. For example, to search for files
with a text value: labels/LABEL_ID.text_field_id ='TEXT'.

For more information, see Search for files with a specific label or field value
(/workspace/drive/api/guides/search-labels).

Search the corpora


Searches that call files.list (/workspace/drive/api/reference/rest/v3/files/list) use the
corpora (/workspace/drive/api/guides/about-files#org) of user by default. To search other
corpora, such as files shared with a domain, set the corpora parameter.

Multiple corpora may be searched in a single query, though incomplete results might be
returned if the combined corpora is too large. If incompleteSearch is true in the response
body, then all documents weren't returned. If this occurs, you should narrow your query by
choosing a different corpora such as user or drive.

Related topics
Search for shared drives (/workspace/drive/api/guides/search-shareddrives)

Search query terms and operators (/workspace/drive/api/guides/ref-search-terms)

Google Workspace and Google Drive supported MIME types


(/workspace/drive/api/guides/mime-types)

Roles and permissions (/workspace/drive/api/guides/ref-roles)

Search for files with a specific label or field value


(/workspace/drive/api/guides/search-labels)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/search-files 6/6
6/27/25, 10:06 AM Trash or delete files and folders | Google Drive | Google for Developers

Trash or delete files and folders


You can remove Google Drive files and folders from both your My Drive and shared drives.
You have two options to do this: trash or delete.

You can move files and folders into the trash and then restore them (within 30 days of
trashing them). Deleting files and folders removes them permanently from Drive. If you
trash, restore, or permanently delete multiple files or folders at once, it might take time for
you to notice the changes.

Note: For this document, assume "files" means both files and folders. Folders are files that only contain
metadata and can be used to organize files in Drive. Specifically, a folder is a file with the MIME type
(/workspace/drive/api/guides/mime-types) application/vnd.google-apps.folder and with no
extension. For more information, see Create and populate folders (/workspace/drive/api/guides/folder).

This guide explains how you can dispose of files in Drive.

Trash
To remove Drive files, you can move them to the trash. Files in the trash are automatically
deleted after 30 days. You can restore files from your trash before the 30-day period.

Only the file owner can trash a file, and other users can't view files in the owner's trash. If
you attempt to trash a file you don't own, you receive an insufficientFilePermissions
(/workspace/drive/api/guides/handle-errors#insufficient-file-permissions) error. For more
information, see Permissions (#permissions).

To verify you're the file owner, call the files.get


(/workspace/drive/api/reference/rest/v3/files/get) method with the fileId and the fields
parameter set to the boolean ownedByMe field. The ownedByMe field isn't populated for files
in shared drives because they're owned by the shared drive, not individual users. For further
information about returning fields using the fields parameter, see Return specific fields for
a file (/workspace/drive/api/guides/fields-parameter).

If you're not the file owner but still want a copy of the trashed file, do one of the following:

Make a copy of the file.

Contact the owner to have them restore it from the trash.

https://developers.google.com/workspace/drive/api/guides/delete#node.js 1/7
6/27/25, 10:06 AM Trash or delete files and folders | Google Drive | Google for Developers

Move a file to the trash


To move a file to the trash, use the files.update
trashed field to True.
(/workspace/drive/api/reference/rest/v3/files/update) method and set the
To trash a shared drive file, you must also set the supportsAllDrives query parameter to
True. For more information, see Implement shared drive support
(/workspace/drive/api/guides/enable-shareddrives).

If successful, the response body


(/workspace/drive/api/reference/rest/v3/files/update#request-body) contains an instance of the
files (/workspace/drive/api/reference/rest/v3/files) resource.

Note: If you're using the previous Drive API v2 version, use the files.trash
(/workspace/drive/api/reference/rest/v2/files/trash) method. Learn how to migrate to Drive API v3
(/workspace/drive/api/guides/migrate-to-v3).

The following code sample shows how to use the fileId to mark the file as trashed:

Python (#python)Node.js
(#node.js)

const body_value = {
'trashed': True
};

const response = await drive_service.files.update({


fileId: 'FILE_ID edit',
requestBody: body_value,
});
return response;

Replace FILE_ID with the fileId of the file that you want to trash.

Determine a trashed file's properties


When a file is trashed, you can retrieve additional files
(/workspace/drive/api/reference/rest/v3/files) properties. You can use the files.get
(/workspace/drive/api/reference/rest/v3/files/get) method and include the following fields in the
fields parameter. For more information, see Return specific fields for a file
(/workspace/drive/api/guides/fields-parameter).

https://developers.google.com/workspace/drive/api/guides/delete#node.js 2/7
6/27/25, 10:06 AM Trash or delete files and folders | Google Drive | Google for Developers

The following fields are populated for all files:

trashed: Whether the file was trashed, either explicitly or from a trashed parent folder.
Note that while using trashed with the files.update method sets the file's status,
the files.get method retrieves the file's status.

explicitlyTrashed: Whether the file was explicitly trashed, as opposed to


recursively trashed, from a parent folder.

The following fields are only populated for files located within a shared drive:

trashedTime: The time that the item was trashed in RFC 3339
(http://tools.ietf.org/html/rfc3339) date-time format. If you're using the previous Drive API
v2 version, this field is called trashedDate.

trashingUser: If the file was explicitly trashed, the user who trashed it.

Recover a file from the trash


To recover a file from the trash, use the files.update
trashed field to
(/workspace/drive/api/reference/rest/v3/files/update) method and set the
False. To untrash a shared drive file, you also must set the supportsAllDrives query
parameter to True. For more information, see Implement shared drive support
(/workspace/drive/api/guides/enable-shareddrives).

If successful, the response body


(/workspace/drive/api/reference/rest/v3/files/update#request-body) contains an instance of the
files (/workspace/drive/api/reference/rest/v3/files) resource.

Note: If you're using the previous Drive API v2 version, use the files.untrash
(/workspace/drive/api/reference/rest/v2/files/untrash) method. Learn how to migrate to Drive API v3
(/workspace/drive/api/guides/migrate-to-v3).

The following code sample shows how to use the fileId to mark the file as untrashed:

Python (#python)Node.js
(#node.js)

const body_value = {
'trashed': False
};

const response = await drive_service.files.update({

https://developers.google.com/workspace/drive/api/guides/delete#node.js 3/7
6/27/25, 10:06 AM Trash or delete files and folders | Google Drive | Google for Developers

fileId: 'FILE_ID edit',


requestBody: body_value,
});
return response;

Replace FILE_ID with the fileId of the file that you want to untrash.

Empty trash
You can permanently delete all Drive files the user has moved to the trash (#file-trash) using
the files.emptyTrash (/workspace/drive/api/reference/rest/v3/files/emptyTrash) method. To
empty the trash of a shared drive, you must also set the driveId query parameter to the
shared drive ID.

If successful, the response body


(/workspace/drive/api/reference/rest/v3/files/delete#response-body) contains an empty instance.

Note: If you're using the previous Drive API v2 version, use the files.emptyTrash
(/workspace/drive/api/reference/rest/v2/files/emptyTrash) method. Learn how to migrate to Drive API
v3 (/workspace/drive/api/guides/migrate-to-v3).

The following code sample shows how to use the fileId to delete all files in the trash:

Python (#python)Node.js
(#node.js)

const response = await drive_service.files.emptyTrash({


});
return response;

Delete
You can permanently delete a Drive file without moving it to the trash. After you delete a file,
anyone you've shared the file with loses access to it. If you want others to retain access to
the file, you can transfer ownership
(/workspace/drive/api/guides/manage-sharing#transfer-organization-account) to someone else
before deletion.

https://developers.google.com/workspace/drive/api/guides/delete#node.js 4/7
6/27/25, 10:06 AM Trash or delete files and folders | Google Drive | Google for Developers

To delete a shared drive file, the user must have role=organizer on the parent folder. If
you're deleting a folder, all descendants owned by the user are also deleted. For more
information, see Permissions (#permissions).

To permanently delete a user-owned file without moving it to the trash, use the
files.delete (/workspace/drive/api/reference/rest/v3/files/delete) method. To delete a shared
drive file, you must also set the supportsAllDrives query parameter to True. For more
information, see Implement shared drive support
(/workspace/drive/api/guides/enable-shareddrives).

If successful, the response body


(/workspace/drive/api/reference/rest/v3/files/emptyTrash#response-body) contains an empty
instance.

Note: If you're using the previous Drive API v2 version, use the files.delete
(/workspace/drive/api/reference/rest/v2/files/delete) method. Learn how to migrate to Drive API v3
(/workspace/drive/api/guides/migrate-to-v3).

The following code sample shows how to use the fileId to delete the file:

Python (#python)Node.js
(#node.js)

const response = await drive_service.files.delete({


fileId: 'FILE_ID edit'
});
return response;

Replace FILE_ID with the fileId of the file that you want to delete.

Permissions
The following table shows the role permissions required to perform each operation. For a
complete list of roles and the operations permitted by each, refer to Roles and permissions
(/workspace/drive/api/guides/ref-roles).

Permitted operation ownerorganizerfileOrganizerwritercommenterreader

Move files and folders into the trash ✔ ✔ ✔

https://developers.google.com/workspace/drive/api/guides/delete#node.js 5/7
6/27/25, 10:06 AM Trash or delete files and folders | Google Drive | Google for Developers

Permitted operation ownerorganizerfileOrganizerwritercommenterreader

Recover files and folders from the trash ✔ ✔ ✔

Empty the trash ✔ ✔

Permanently delete a file or folder ✔ ✔

Delete files and folders in a shared ✔


[*]
drive

[*] Requires the organizer role on a direct or indirect parent, as opposed to the role being present on the
item.

Capabilities
A files (/workspace/drive/api/reference/rest/v3/files) resource contains a collection of boolean
capabilities fields used to indicate whether an action can be performed on a file.

To check the capabilities, call the files.get (/workspace/drive/api/reference/rest/v3/files/get)


method with the fileId and the fields parameter set to the capabilities field. For
further information about returning fields using the fields parameter, see Return specific
fields for a file (/workspace/drive/api/guides/fields-parameter).

The following fields are populated for all files:

capabilities.canTrash: Whether the current user can move this file to trash.

capabilities.canUntrash: Whether the current user can restore this file from trash.

capabilities.canDelete: Whether the current user can delete this file.

capabilities.canRemoveChildren: Whether the current user can remove children


from this folder. This is false when the item isn't a folder.

The following fields are only populated for files located within a shared drive:

capabilities.canTrashChildren: Whether the current user can trash children of


this folder. This is false when the item isn't a folder.

capabilities.canDeleteChildren: Whether the current user can delete children of


this folder. This is false when the item isn't a folder.

https://developers.google.com/workspace/drive/api/guides/delete#node.js 6/7
6/27/25, 10:06 AM Trash or delete files and folders | Google Drive | Google for Developers

File and folder limits


Drive files and folders, along with shared drive folders, have some storage limits.

Generally, after the item limit is reached, the only way to create more space is to
permanently delete (/workspace/drive/api/guides/delete#empty-trash) items or use a different
account. Moving files to the trash isn't enough to free up space.

For more information on file and folder limits, see the following:

File and folder limits in files (/workspace/drive/api/guides/folder#folder-limits)

File and folder limits in shared drives


(/workspace/drive/api/guides/manage-shareddrives#folder-limits)

Related topics
Delete files in Google Drive (https://support.google.com/drive/answer/2375102)

Shared drive versus My Drive API differences


(/workspace/drive/api/guides/shared-drives-diffs)

Roles and permissions (/workspace/drive/api/guides/ref-roles)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/delete#node.js 7/7
6/27/25, 10:05 AM Protect file content | Google Drive | Google for Developers

Protect file content


The Google Drive API supports several ways to 

prevent file modification, including file content


restriction and prohibiting the option to
download, print, or copy files.


Make files read-only with Drive  

content restrictions
You can add a content restriction to a Google Drive file to prevent users from doing 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 a Drive item to be
made read-only without changing the item's access permissions
(/workspace/drive/api/reference/rest/v3/permissions). This means it's not an access restriction.
While users cannot modify the file's content, other operations are still allowed based on
access level (for example, a user with edit access can still move an item or change its
sharing settings).

To add or remove a content restriction on a file in Drive, a user must have the associated
permissions (/workspace/drive/api/reference/rest/v3/permissions). For a file or folder in My Drive
or a shared drive with the capabilities.canModifyEditorContentRestriction, you
must have role=writer assigned. For a file or folder in My Drive or a shared drive with an
ownerRestricted content restriction, you must own the file or have role=organizer. To
view an item with a content restriction, users must have role=reader or higher. For a
complete list of roles, see Roles & permissions (/workspace/drive/api/guides/ref-roles). To
change permissions on a file, see Change permissions
(/workspace/drive/api/guides/manage-sharing#change-permissions).

You can use the contentRestrictions.readOnly boolean field on the files


(/workspace/drive/api/reference/rest/v3/files#contentrestriction) resource to set a content
restriction. Note that setting a content restriction on an item overwrites the existing one.

https://developers.google.com/workspace/drive/api/guides/content-restrictions#node.js 1/9
6/27/25, 10:05 AM Protect file content | Google Drive | Google for Developers

Scenarios for content restrictions


A content restriction on a Drive item signals to users that the contents 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 not meant to
prevent users with sufficient permissions from continuing to work on an item. Additionally,
it isn't a way to create an immutable record. Drive content restrictions are mutable, so a
content restriction on 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 the slides

Important: The preceding doesn't include the results of calculations in Sheets, so the displayed contents
of a sheet with a content restriction might change if there are formulas in a sheet that reference external
data sources.

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

Google Forms

https://developers.google.com/workspace/drive/api/guides/content-restrictions#node.js 2/9
6/27/25, 10:05 AM Protect file content | Google Drive | Google for Developers

Google Sites

Google Drawings

Shortcuts and third-party shortcuts. For more information, see Create a shortcut file
to content stored by your app (/workspace/drive/api/guides/third-party-shortcuts) and
Create a shortcut to a Drive file (/workspace/drive/api/guides/shortcuts).

Add a content restriction


To add a file content restriction, use the files.update
(/workspace/drive/api/reference/rest/v3/files/update) method with the
contentRestrictions.readOnly field set to true. Add an optional reason for why you're
adding the restriction, such as "Finalized contract." The following code sample shows how
to add a content restriction:

Java (#java)Python (#python)Node.js


(#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/


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 edit',
resource: updatedFile,
fields: 'contentRestrictions',
});
return response;

https://developers.google.com/workspace/drive/api/guides/content-restrictions#node.js 3/9
6/27/25, 10:05 AM Protect file content | Google Drive | Google for Developers

} catch (err) {
// TODO (developer) - Handle error
throw err;
}
}

Replace FILE_ID with the fileId of the file that you want to modify.

When you run the sample code, the file is content restricted and a lock symbol ( lock)
appears beside the file name within the Google Drive user interface (UI)
(https://drive.google.com/drive/my-drive). The file is now read-only.

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

Remove a content restriction


To remove a file content restriction, use the files.update method with the
contentRestrictions.readOnly field set to false. The following code sample shows
how to remove a content restriction:

Java (#java)Python (#python)Node.js


(#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');

https://developers.google.com/workspace/drive/api/guides/content-restrictions#node.js 4/9
6/27/25, 10:05 AM Protect file content | Google Drive | Google for Developers

const {google} = require('googleapis');

const auth = new GoogleAuth({scopes: 'https://www.googleapis.com/auth/


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 edit',
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 to modify.

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 and allow content editing
(provided you have the correct permissions). There are two options to do this:

1. In Drive, right-click the file with a content restriction and click Unlock lock_open.

Figure 2. Remove a file content restriction within a Drive file list.

2. Open the file with a content restriction and click (Locked mode) lock > Unlock file.

https://developers.google.com/workspace/drive/api/guides/content-restrictions#node.js 5/9
6/27/25, 10:05 AM Protect file content | Google Drive | Google for Developers

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

Check for a content restriction


To check for a content restriction, use the files.get
(/workspace/drive/api/reference/rest/v3/files/get) method with the contentRestrictions
returned field. The following code sample shows how to check the status of a content
restriction:

Java (#java)Python (#python)Node.js


(#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/


const service = google.drive({version: 'v3', auth});
try {
const response = await service.files.get({
fileId: 'FILE_ID edit',
fields: 'contentRestrictions',
});
return response;
} catch (err) {
// TODO (developer) - Handle error

https://developers.google.com/workspace/drive/api/guides/content-restrictions#node.js 6/9
6/27/25, 10:05 AM Protect file content | Google Drive | Google for Developers

throw err;
}
}

Replace FILE_ID with the fileId of the file that you want to check.

When you run the sample code, the method returns a ContentRestriction
(/workspace/drive/api/reference/rest/v3/files#contentrestriction) 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 the
files.update (/workspace/drive/api/reference/rest/v3/files/update) method with the
contentRestrictions.ownerRestricted boolean field set to true. The following code
sample shows how to add a content restriction for file owners only:

Java (#java)Python (#python)Node.js


(#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/


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 edit',
resource: updatedFile,

https://developers.google.com/workspace/drive/api/guides/content-restrictions#node.js 7/9
6/27/25, 10:05 AM Protect file content | Google Drive | Google for Developers

fields: 'contentRestrictions',
});
return response;
} catch (err) {
// TODO (developer) - Handle error
throw err;
}
}

Replace FILE_ID with the fileId of the file that you want to modify.

When you run the sample code, the file is content restricted and only file owners 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) (https://drive.google.com/drive/my-drive). If you're not the
owner, the lock symbol is dimmed.

To remove the ownerRestricted flag, use the files.update method with the
contentRestrictions.ownerRestricted field set to false.

Important: A My Drive file has a single owner so only they can modify the content restriction. A shared
drive owns the shared drive file, so any user with role=organizer permissions on the shared drive can
modify or remove the ownerRestricted flag.

Content restriction capabilities


A files (/workspace/drive/api/reference/rest/v3/files) resource contains a collection of boolean
capabilities fields used to indicate whether an action can be performed on a file.

Content restrictions contain the following capabilities:

capabilities.canModifyEditorContentRestriction: Whether the current user


can add or modify a content restriction (#add).

capabilities.canModifyOwnerContentRestriction: Whether the current user can


add or modify an owner content restriction (#owner-restriction).

capabilities.canRemoveContentRestriction: Whether the current user can


remove the applied content restriction (#remove) (if present).

For more information, see Capabilities


(/workspace/drive/api/guides/manage-sharing#capabilities).

https://developers.google.com/workspace/drive/api/guides/content-restrictions#node.js 8/9
6/27/25, 10:05 AM Protect file content | Google Drive | Google for Developers

For an example of retrieving file capabilities, see Verify user permissions


(/workspace/drive/api/guides/manage-sharing#verify-permissions).

Prevent users from downloading, printing, or copying your


file
You can limit how users with role=commenter or role=reader permissions can download,
print, and copy files within Drive, Docs, Sheets, and Slides.

To remove the options to download, print, and copy files, use the files.update
(/workspace/drive/api/reference/rest/v3/files/update) method with the
copyRequiresWriterPermission boolean field set to true.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/content-restrictions#node.js 9/9
6/27/25, 10:05 AM Transfer file ownership | Google Drive | Google for Developers

Transfer file ownership


You own the files that you create or upload on Google Drive. You can transfer ownership of
these files to another account.

Transfer file ownership to another Google Workspace


account in the same organization link
Ownership of files existing in "My Drive" can be transferred from one Google Workspace
account
(https://cloud.google.com/architecture/identity/overview-google-
authentication#cloud_identity_or_g_suite_account)
to another account in the same organization. An organization that owns a shared drive
owns the files within it. Therefore, ownership transfers are not supported for files and
folders in shared drives. Organizers of a shared drive can move items from that shared
drive and into their own "My Drive" which transfers the ownership to them.

To transfer ownership of a file in "My Drive", do one of the following:

Create (/workspace/drive/api/guides/manage-sharing#create-permission) a file permission


granting a specific user (type=user) owner access (role=owner).

Update an existing file permission with role=owner and transfer ownership to the
specified user (transferOwnership=true).

Note: When a file is transferred, the previous owner's role is downgraded to writer.

Transfer file ownership from one consumer account to


another
Ownership of files can be transferred between one consumer account
(https://cloud.google.com/architecture/identity/overview-google-authentication#consumer_account) to
another. However, Drive doesn't transfer ownership of a file between the two consumer
accounts until the prospective owner explicitly consents to the transfer. To transfer file
ownership from one consumer account to another:

https://developers.google.com/workspace/drive/api/guides/transfer-file 1/2
6/27/25, 10:05 AM Transfer file ownership | Google Drive | Google for Developers

1. The current owner initiates an ownership transfer by creating or updating the


prospective owner's file permission. The permission must include these settings:
role=writer, type=user, and pendingOwner=true. If the current owner is creating a
permission for the prospective owner, an email notification is sent to the prospective
owner indicating that they're being asked to assume ownership of the file.

2. The prospective owner accepts the ownership transfer request by creating or


updating their file permission. The permission must include these settings:
role=owner and transferOwnership=true. If the prospective owner is creating a
new permission, an email notification is sent to the previous owner indicating that
ownership has been transferred.

When a file is transferred, the previous owner's role is downgraded to writer.

Note: Service accounts don't have storage quota in Drive, so ownership transfers to service accounts will
fail.

Related topics
Share files, folders, and drives (/workspace/drive/api/guides/manage-sharing)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-18 UTC.

https://developers.google.com/workspace/drive/api/guides/transfer-file 2/2
6/27/25, 10:05 AM Manage folders with limited and expansive access | Google Drive | Google for Developers

Manage folders with limited and expansive


access
A user owns a My Drive folder. The folder might contain multiple users with access to
different files. This restrictive access model means different users could see different lists
of items within the same folder. A user with access to the parent My Drive folder but not to
an item within that folder has "restricted access". It creates a situation where it's difficult to
know who has access within the hierarchy.

Conversely, shared drive files are owned by the shared drive. Shared drives have an
expansive model so every user has the same list of items within the same folder.

The introduction of folders with limited access replicates the expansive access model from
shared drives to My Drive. With this change, folders with limited access are the one
exception that allows restricting access to a specific subfolder in both My Drive and shared
drives.

This guide explains how you can manage folders with limited access and expansive access
in Google Drive.

About folders with limited access


Folders with limited access allow you to restrict folders to specific users. Only users you
directly add to the folder's permissions can open it and access its content. Users with
inherited access to the shared My Drive folder or shared drive folder (through access from a
parent folder) can see the restricted folder in Drive but can't open it. This feature better
aligns the sharing behavior of items in both My Drive and shared drives, letting you organize
folders with sensitive content alongside more broadly shared content.

Folders with limited access are available in both My Drive and shared drives. The owner role
in My Drive and the organizer role in shared drives can always access folders with limited
access. To modify the list of folder users, no special permissions are required. Roles that
can share folders can update the member lists. To learn more about roles and permissions,
see Roles and permissions (/workspace/drive/api/guides/ref-roles) and Shared drives overview
(/workspace/drive/api/guides/about-shareddrives).

Note that although folders (/workspace/drive/api/guides/about-files#folder) are a type of file,


limited access isn't available for files.

https://developers.google.com/workspace/drive/api/guides/limited-expansive-access 1/6
6/27/25, 10:05 AM Manage folders with limited and expansive access | Google Drive | Google for Developers

Set limited access on a folder


While users with direct folder permissions
can access a folder with limited access, only
the owner role in My Drive and the organizer
role in shared drives can enable or disable
limited access.

Additionally, if a user with the writer role in


My Drive has the writersCanShare boolean
field on the files
(/workspace/drive/api/reference/rest/v3/files)
resource set to true, they can also turn the
feature on or off.

To limit access to a folder, set the boolean


inheritedPermissionsDisabled field on
the files resource to true. When true, only
the owner role, the organizer role, and users
with direct folder permissions can access it.

To turn inherited permissions back on, set inheritedPermissionsDisabled to false.

Verify permission to limit access on a folder


To check if you can limit access to a folder or not, inspect the boolean values of the
capabilities.canDisableInheritedPermissions and
capabilities.canEnableInheritedPermissions fields on the files
(/workspace/drive/api/reference/rest/v3/files) resource. These settings confirm if you have
permission to limit access to a folder through the inheritedPermissionsDisabled field.

For more information about capabilities, see Understand file capabilities


(/workspace/drive/api/guides/manage-sharing#capabilities).

List children of a folder with limited access


To check if you can list the children of a folder, use the capabilities.canListChildren
boolean field.

The returned value is always false when the item isn't a folder or if the requester's access
to the folder's contents was removed by setting inheritedPermissionsDisabled to
false.

https://developers.google.com/workspace/drive/api/guides/limited-expansive-access 2/6
6/27/25, 10:05 AM Manage folders with limited and expansive access | Google Drive | Google for Developers

If your access to the folder's contents was removed, you can still access the folder
metadata (/workspace/drive/api/guides/file) with the files.get()
(/workspace/drive/api/reference/rest/v3/files/get) and files.list()
(/workspace/drive/api/reference/rest/v3/files/list) methods. To confirm access is limited, check
the response body to see if the item is a folder with the MIME type
(/workspace/drive/api/guides/mime-types) application/vnd.google-apps.folder and the
capabilities.canListChildren field is set to false. If you try to list the children of such a
folder, the result is always empty.

Access folder with limited access metadata


Folders with limited access let you view folder metadata (/workspace/drive/api/guides/file) if
you have no access to the folder contents.

When using the permissions (/workspace/drive/api/reference/rest/v3/permissions) resource to


determine a user's access, both My Drive and shared drive folders that only grant access to
the metadata contain the following values in the response body:
inheritedPermissionsDisabled=true and view=metadata. The role is always set to
reader. The view field is only populated for permissions that belong to a view. For more
information, see Views (/workspace/drive/api/guides/ref-roles#views).

All the entries in the permissionDetails field have the inherited field set to true to
denote the permission is inherited and that direct access to the folder contents hasn't been
granted.

To grant access to both the folder contents and metadata, set the
inheritedPermissionsDisabled field to false or update the role to reader or higher.

Finally, if a permission was first limited by turning off inheritance on a folder


(inheritedPermissionsDisabled=true), and then the permission was added back directly
to the folder, the values in the response body become
inheritedPermissionsDisabled=true with the view field as unset. If the folder is in a
shared drive, the permissionDetails list has an entry with the inherited field set to
false to denote the permission isn't inherited. This permission grants access to both folder
contents and metadata like any other permission.

Delete folders with limited access


You can delete folders with limited access using the files.delete()
(/workspace/drive/api/reference/rest/v3/files/delete) method on the files resource.

https://developers.google.com/workspace/drive/api/guides/limited-expansive-access 3/6
6/27/25, 10:05 AM Manage folders with limited and expansive access | Google Drive | Google for Developers

In My Drive, only the item's owner can delete a folder hierarchy. If a user deletes a hierarchy
with folders that have limited access and are owned by others, these folders move to the
owner's My Drive.

If the user has the owner role, the entire hierarchy gets deleted.

In shared drives, the organizer role can delete hierarchies even if they contain folders with
limited access. If the fileOrganizer role deletes a hierarchy that contains folders with
limited access, the result depends on if they were added back as fileOrganizer on the
folders with limited access. If they were, the entire hierarchy gets deleted. If not, the folders
with limited access move to the shared drive's root folder.

About expansive access


The introduction of folders with limited access broadens the expansive access model from
shared drives to My Drive. Once the access model is rolled out, having access to a folder
means at least the same level of access to everything in that folder hierarchy. Folders with
limited access are the one exception that allows restricting access to a specific subfolder in
both My Drive and shared drives. This also means that unless your folder has limited
access, you can no longer remove access that's inherited from the parent folder. Doing so
means Drive API returns an error response. To define more granular access control within a
hierarchy, you can set limited access (#set-limited-access) on the folder.

Adapt to expansive access


To make it easier for developers to adapt to expansive access, several improvements were
made to the Google Drive API:

1. The permissionDetails[] field on the permissions


(/workspace/drive/api/reference/rest/v3/permissions) resource is now populated for items
in My Drive. Previously, the fields were either unset or replicated from the
teamDrivePermissionDetails field where appropriate. Only the permissionType
and inherited fields in My Drive are populated.

The permissionDetails[].inherited field indicates if a permission is inherited


from the item's parent. It lets you detect if certain roles (such as reader) are inherited
from the parent, and if a higher role (such as writer) is granted on the item directly.

When viewing the permissions for an item, the permissionDetails[] field might
contain multiple entries. If present, there's one entry for the permission directly on the

https://developers.google.com/workspace/drive/api/guides/limited-expansive-access 4/6
6/27/25, 10:05 AM Manage folders with limited and expansive access | Google Drive | Google for Developers

item for that scope, and then entries for the inherited or member permissions on the
item.

2. Developers can opt in to expansive access API behavior in My Drive ahead of any
future mandatory enforcement. You can set the enforceExpansiveAccess request
parameter to true so that future changes to expansive access don't affect your app.

Opting in now means the API operates the same for items in My Drive as it already
does for items in shared drives. For example, any attempt to restrict access below the
inherited role fails when calling permissions.update()
(/workspace/drive/api/reference/rest/v3/permissions/update). Similarly, a call to
permissions.delete() (/workspace/drive/api/reference/rest/v3/permissions/delete) fails if
the permission is inherited.

Detect and prevent restricted access


Your app might be creating restricted access (where a user has access to the parent My
Drive folder but not to a file within that folder) on your My Drive folders when using the
permissions.update() or permissions.delete() methods.

When using these methods, you can review the fields on the permissions resource to see
where a request might create restricted access and avoid sending such requests. To detect
this situation, use the enforceExpansiveAccess field on your request.

Additionally, if your app has already created restricted access on your folders, you can take
the following steps:

1. Traverse the folder hierarchy to remove the restricted access. In its place, you should
set limited folder access (#set-limited-access).

2. If the item you're trying to unshare is a file, you can create an intermediate folder, set
limited access on it, and move the file inside the new folder.

3. If you don't want to use limited access folders but must remove some access, you can
move the file to a private folder (such as the My Drive root folder). You can then create
a shortcut (/workspace/drive/api/guides/shortcuts) to the item's original location so users
can still use it.

Related topics
Share files, folders, and drives (/workspace/drive/api/guides/manage-sharing)

https://developers.google.com/workspace/drive/api/guides/limited-expansive-access 5/6
6/27/25, 10:05 AM Manage folders with limited and expansive access | Google Drive | Google for Developers

How file access works in shared drives


(https://support.google.com/a/users/answer/12380484)

Learn about folders with limited access


(https://support.google.com/drive/answer/14254362)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/limited-expansive-access 6/6
6/27/25, 10:04 AM Manage pending access proposals | Google Drive | Google for Developers

Manage pending access proposals


An access proposal is a proposal from a requester to an approver to grant a recipient
access to a Google Drive item.

An approver can review and act on all unresolved access proposals across Drive files. This
means you can speed up the approval process by programmatically querying for access
proposals and then resolving them. It also allows proposals to be viewed in aggregate by an
approver.

The Google Drive API provides the accessproposals


(/workspace/drive/api/reference/rest/v3/accessproposals) resource so you can view and resolve
pending access proposals. The methods of the accessproposals resource work on files,
folders, the files within a shared drive but not on the shared drive.

The following terms are specific to access proposals:

Requester: The user initiating the access proposal to a Drive item.

Recipient: The user receiving the additional permissions on a file if the access
proposal is granted. Many times the recipient is the same as the requester but not
always.

Approver: The user responsible for approving (or denying) the access proposal. This
is typically because they're an owner on the document or they have the ability to share
the document.

Important: Access proposals can't be created using the Drive API. Users must request access using the
Drive UI. For more information, see Get permission to open a file or folder
(https://support.google.com/docs/answer/6211862).

List pending access proposals


To list all pending access proposals on a Drive item, call the list()
(/workspace/drive/api/reference/rest/v3/accessproposals/list) method on theaccessproposals
(/workspace/drive/api/reference/rest/v3/accessproposals) resource and include the fileId path
parameter.

Only approvers on a file can list the pending proposals on a file. An approver is a user with
the can_approve_access_proposals capability on the file. If the requester isn't an

https://developers.google.com/workspace/drive/api/guides/pending-access 1/3
6/27/25, 10:04 AM Manage pending access proposals | Google Drive | Google for Developers

approver, an empty list is returned. For more information about capabilities, see
Understand file capabilities (/workspace/drive/api/guides/manage-sharing#capabilities).

The response body (/workspace/drive/api/reference/rest/v3/accessproposals/list#response-body)


consists of an AccessProposal
(/workspace/drive/api/reference/rest/v3/accessproposals/list#accessproposal) object representing
a list of unresolved access proposals on the file.

The AccessProposal object includes info about each proposal such as the requester, the
recipient, and the message that the requester added. It also includes an
AccessProposalRoleAndView
(/workspace/drive/api/reference/rest/v3/accessproposals/list#accessproposalroleandview) object
that groups the requester's proposed role with a view. Since role is a repeated field,
multiples could exist for each proposal. For example, a proposal might have an
AccessProposalRoleAndView object of role=reader and view=published, plus an
additional AccessProposalRoleAndView object with only the role=writer value. For more
information, see Views (/workspace/drive/api/guides/ref-roles#views).

Pass the following query parameters to customize pagination of, or filter, access proposals:

pageToken: A page token, received from a previous list call. Provide this token to
retrieve the subsequent page.

pageSize: The maximum number of access proposals to return per page.

Resolve pending access proposals link


To resolve all pending access proposals on a Drive item, call the resolve()
(/workspace/drive/api/reference/rest/v3/accessproposals/resolve) method on the
accessproposals (/workspace/drive/api/reference/rest/v3/accessproposals) resource and
include the fileId and proposalId path parameters.

The resolve() method includes an action query parameter that denotes the action to take
on the proposal. The Action
(/workspace/drive/api/reference/rest/v3/accessproposals/resolve#action) object tracks the state
change of the proposal so we know if it's being accepted or denied.

The resolve() method also includes the optional query parameters of role and view. The
only supported roles are writer, commenter, and reader. If the role isn't specified, it
defaults to reader. An additional optional query parameter of send_notification lets you
send an email notification to the requester when the proposal is accepted or denied.

https://developers.google.com/workspace/drive/api/guides/pending-access 2/3
6/27/25, 10:04 AM Manage pending access proposals | Google Drive | Google for Developers

Just as with the list() method, users resolving the proposal must have the
can_approve_access_proposals capability on the file. For more information about
capabilities, see Understand file capabilities
(/workspace/drive/api/guides/manage-sharing#capabilities).

Proposals are resolved using the same patterns listed under Scenarios for sharing Drive
resources (/workspace/drive/api/guides/manage-sharing#sharing-drive-resources). If there are
multiple proposals for the same user, but with different roles, the following applies:

If one proposal is accepted and one is denied, the accepted role applies to the Drive
item.

If both proposals are accepted at the same time, the proposal with the higher
permission (for example, role=writer versus role=reader) is applied. The other
access proposal is removed from the item.

After sending a proposal to the resolve() method, the sharing action is complete. The
AccessProposal is no longer returned through the list() method. Once the proposal is
accepted, the user must use the permissions
(/workspace/drive/api/reference/rest/v3/permissions) collection to update permissions on a file
or folder. For more information, see Update permissions
(/workspace/drive/api/guides/manage-sharing#update-permissions).

Related topics
Share files, folders, and drives (/workspace/drive/api/guides/manage-sharing)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/pending-access 3/3
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

Manage long-running operations


A long-running operation (LRO) is an API method that takes a longer time to complete than
is appropriate for an API response. Typically, you don't want to hold the calling thread open
while the task runs as it offers a poor user experience. Instead, it's better to return some
type of promise to the user and allow them to check back later.

The Google Drive API returns a LRO every time you call the download()
(/workspace/drive/api/reference/rest/v3/files/download) method on the files
(/workspace/drive/api/reference/rest/v3/files) resource to download the content of a file either
through the Drive API or its client libraries (/workspace/drive/api/guides/downloads).

The method returns an operations (/workspace/drive/api/reference/rest/v3/operations)


resource to the client. You can use the operations resource to asynchronously retrieve the
status of the API method by polling the operation through the get()
(/workspace/drive/api/reference/rest/v3/operations/get) method. LROs in Drive API adhere to the
Google Cloud LRO design pattern
(https://cloud.google.com/apis/design/design_patterns#long_running_operations).

For more information, see Long-running operations (https://google.aip.dev/151).

Note: Both the files.download() method and the operations.get() method consume normal Drive
API quota. For more information, see Usage limits (/workspace/drive/api/guides/limits).

Process overview
The following diagram shows the high-level steps of how the file.download method
works.

1. Call files.download: When your app calls the download() method, it launches the
Drive API download request for the file. For more information, see Download files
(#download-files).

2. Request permissions: The request sends authentication credentials to the Drive API.
If your app requires calling Drive API using a user's authentication that hasn't yet been
granted, it prompts the user to sign in. Your app also asks for access with scopes
(/workspace/drive/api/guides/api-specific-auth#drive-scopes) that you specify when setting
up authentication.

https://developers.google.com/workspace/drive/api/guides/long-running-operations 1/10
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

3. Start download: A Drive API request is


made to start the file download. The
request could be made to Google Vids or
some other Google Workspace content.

4. Start LRO: A long-running operation begins


and it manages the download process.

5. Return pending operation: The Drive API


returns a pending operation containing
information about the user making the
request and several file metadata fields.

6. Initial pending state: Your app receives the


pending operation along with an initial
pending state of done=null. This denotes
the file isn't ready for download yet and
that the operation status is pending.

7. Call operations.get and verify result:


Your app calls get() at the recommended Figure 1. High-level steps for the
intervals to poll the operation result and file.download method.
get the latest state of a long-running
operation. If the pending state of done=false is returned, your app must keep polling
until the operation returns the completed state (done=true). For large files, expect to
poll multiple times. For more information, see Get the details about a long-running
operation (#operation-details).

8. Check pending state: If the pending state of done=true is returned from the LRO, this
denotes the file is ready for download and that the operation status is complete.

9. Return completed operation with download URI: Once the LRO is done, the Drive API
returns the download URI and the file is now available to the user.

Download files
To download content under a long-running operation, use the download()
(/workspace/drive/api/reference/rest/v3/files/download) method on the files
(/workspace/drive/api/reference/rest/v3/files) resource. The method takes the query
parameters of file_id, mime_type, and revision_id:

Required. The file_id query parameter is the ID of the file to download.

https://developers.google.com/workspace/drive/api/guides/long-running-operations 2/10
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

Optional. The mime_type query parameter denotes the MIME type the method should
use. It's only available when downloading non-blob media content (such as Google
Workspace documents). For a complete list of supported MIME types, see Export
MIME types for Google Workspace documents
(/workspace/drive/api/guides/ref-export-formats).

If the MIME type isn't set, the Google Workspace document is downloaded with a
default MIME type. For more information, see Default MIME types (#default-mime-types).

Optional. The revision_id query parameter is the revision ID of the file to download.
It's only available when downloading blob files, Google Docs, and Google Sheets.
Returns error code INVALID_ARGUMENT when downloading a specific revision on
unsupported files.

The download() method is the only way to download Vids files in MP4 format and is
typically best suited to downloading most video files.

Download links generated for Google Docs or Sheets initially return a redirect. Click the new
link to download the file.

A request to the download() method that begins the LRO, and the request to fetch the final
download URI, should both use resource keys. For more information, see Access link-
shared Drive files using resource keys (/workspace/drive/api/guides/resource-keys).

The request protocol is shown here.

POST https://www.googleapis.com/drive/v3/files/{FILE_ID}/download

Replace FILE_ID with the fileId of the file that you want to download.

Note: The download() method is only available in Drive API v3.

Default MIME types


If a MIME type isn't set when downloading non-blob content, the following default MIME
types are assigned:

https://developers.google.com/workspace/drive/api/guides/long-running-operations 3/10
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

Document File
Format MIME type
Type Extension

Google Apps JSON application/vnd.google-apps.script+json .json


Script

Google Docs Microsoft Word application/vnd.openxmlformats- .docx


officedocument.wordprocessingml.document

Google PNG image/png .png


Drawings

Google Forms ZIP application/zip .zip

Google SheetsMicrosoft Excel application/vnd.openxmlformats- .xlsx


officedocument.spreadsheetml.sheet

Google Sites Raw Text text/raw .txt

Google Slides Microsoft application/vnd.openxmlformats- .pptx


PowerPoint officedocument.presentationml.presentation

Google Vids MP4 application/mp4 .mp4

Jamboard PDF application/pdf .pdf

Download response
When calling the download() (/workspace/drive/api/v3/reference/files/download) method, the
response body (/workspace/drive/api/reference/rest/v3/files/download#response-body) consists of
a resource representing a long-running operation. The method typically returns a link to
download the file contents.

Tip: Save the name field value as you'll need that to poll the LRO.

{
"done": true,
"metadata": {
"@type": "type.googleapis.com/google.apps.drive.v3.DownloadFileMetadata",
"resourceKey": "RESOURCE_KEY"
},
"name": "NAME",
"response": {
"@type": "type.googleapis.com/google.apps.drive.v3.DownloadFileResponse",
"downloadUri": "DOWNLOAD_URI",

https://developers.google.com/workspace/drive/api/guides/long-running-operations 4/10
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

"partialDownloadAllowed": false
}
}

This output includes the following values:

RESOURCE_KEY: A resource key helps protect your file from unintended access. For
more information, see Access link-shared Drive files using resource keys
(/workspace/drive/api/guides/resource-keys).

NAME: The server-assigned name.

DOWNLOAD_URI: The final download URI for the file.

Note that the partialDownloadAllowed field denotes if a partial download


(/workspace/drive/api/guides/manage-downloads#partial_download) is permitted. True when
downloading blob file content.

Get the details about a long-running operation


Long-running operations are method calls that might take a substantial amount of time to
complete. Typically, newly created download operations are initially returned in a pending
state (done=null), especially for Vids files.

You can use the operations (/workspace/drive/api/reference/rest/v3/operations) resource that


Drive API provides to check the status of the processing LRO by including the unique server-
assigned name.

The get() (/workspace/drive/api/reference/rest/v3/operations/get) method gets the latest state


of a long-running operation asynchronously. Clients can use this method to poll the
operation result at intervals as recommended by the API service.

Note: The user making the get() method request must match the user who initiated the adjoining
download() method request or else the request fails.

Poll a long-running operation


To poll an available LRO, repeatedly call the get()
(/workspace/drive/api/reference/rest/v3/operations/get) method until the operation finishes. Use

https://developers.google.com/workspace/drive/api/guides/long-running-operations 5/10
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

an exponential backoff (/workspace/drive/api/guides/limits#exponential) between each poll


request, such as 10 seconds.

An LRO remains available for a minimum of 12 hours but in some cases can persist longer.
This duration is subject to change and can be different between file types. Once the
resource expires a new download() method request is necessary.

Any requests to get() should use resource keys. For more information, see Access link-
shared Drive files using resource keys (/workspace/drive/api/guides/resource-keys).

The request protocols are shown here.

Method callcurl (#curl)


(#method-call)

operations.get(name='NAME');

Replace NAME with the operation's server-assigned name as shown in the response
to the download() method request.

Note that the name is only returned in the response to a download() request. There's no
other way to retrieve it as Drive API doesn't support the List() method. If the name value is
lost, you must generate a new response by calling the download() method request again.

The response from a get() request consists of a resource representing a long-running


operation. For more information, see Download response (#download-response).

When the response contains a completed state (done=true), the long-running operation
has finished.

Download a revision
You can use the value of the headRevisionId field from the files
(/workspace/drive/api/reference/rest/v3/files) resource to download the latest revision. This
fetches the revision that corresponds to the metadata of the file you previously retrieved. To
download the data for all previous revisions of the file that are still stored in the cloud, you
can call the list() (/workspace/drive/api/reference/rest/v3/revisions/list) method on the
revisions (/workspace/drive/api/reference/rest/v3/revisions) resource with the fileId
parameter. This returns all the revisionIds in the file.

https://developers.google.com/workspace/drive/api/guides/long-running-operations 6/10
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

Note: Access to historical revisions is restricted based on role. Check the


capabilities.canReadRevisions field on the files (/workspace/drive/api/reference/rest/v3/files)
resource before attempting access.

To download the revision content of blob files, you must call the get()
(/workspace%20/drive/api/reference/rest/v3/revisions/get) method on the revisions
(/workspace/drive/api/reference/rest/v3/revisions) resource with the ID of the file to download,
the ID of the revision, and the alt=media URL parameter. The alt=media URL parameter
tells the server that a content download is being requested as an alternative response
format.

Revisions for Google Docs, Sheets, Slides, and Vids can't be downloaded using the get()
method with the alt=media URL . Otherwise, it generates a fileNotDownloadable
(/workspace/drive/api/guides/handle-errors#file-not-downloadable) error.

The alt=media URL parameter is a system parameter


(https://cloud.google.com/apis/docs/system-parameters) available across all Google REST APIs.
If you use a client library for the Drive API, you don't need to explicitly set this parameter.

The request protocol is shown here.

GET https://www.googleapis.com/drive/v3/files/{FILE_ID}/revisions/{REVISION_ID

Replace the following:

FILE_ID: The fileId of the file that you want to download.

REVISION_ID: The revisionId of the revision that you want to download.

Note: If you're using the older Drive API v2, you must send an authorized GET request to its downloadUrl
property. Google Drive generates this short-lived URL when you request the revision but don't rely on it for
later use. You can also export the revision in one of the supported formats by checking the exportLinks
property.

Google Docs, Drawings, and Slides revisions auto-increment the revision numbers. However,
the series of numbers might have gaps if revisions are deleted, so you shouldn't rely on
sequential numbers to retrieve revisions.

https://developers.google.com/workspace/drive/api/guides/long-running-operations 7/10
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

Troubleshoot LROs
When a LRO fails, its response includes a canonical Google Cloud error code
(https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto).

The following table provides an explanation of the cause for each code and a
recommendation for how to handle the code. For many errors, the recommended action is
to try the request again using exponential backoff
(/workspace/drive/api/guides/limits#exponential).

You can read more about this error model and how to work with it in the API Design Guide
(https://cloud.google.com/apis/design/errors#handling_errors).

CodeEnum Description Recommended action

1 CANCELLED The operation was canceled, typically by the Re-run the operation.
caller.

2 UNKNOWN This error might be returned when a Status Retry with exponential
value received from another address space backoff.
belongs to an error space that isn't known in
this address space. If the API error doesn't
return enough information, the error might be
converted to this error.

3 INVALID_ARGUMENT The client specified an invalid argument. This Don't retry without fixing
error differs from FAILED_PRECONDITION. the problem.
INVALID_ARGUMENT indicates arguments that
are problematic regardless of the state of the
system, such as a malformed file name.

4 DEADLINE_EXCEEDED The deadline expired before the operation could Retry with exponential
complete. For operations that change the state backoff.
of the system, this error might be returned even
if the operation has completed successfully. For
example, a successful response from a server
could have been delayed long enough for the
deadline to expire.

5 NOT_FOUND Some requested entity, such as a FHIR resource, Don't retry without fixing
wasn't found. the problem.

6 ALREADY_EXISTS The entity that a client attempted to create, Don't retry without fixing
such as a DICOM instance, already exists. the problem.

7 PERMISSION_DENIED The caller doesn't have permission to execute Don't retry without fixing
the specified operation. This error code doesn't the problem.

https://developers.google.com/workspace/drive/api/guides/long-running-operations 8/10
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

CodeEnum Description Recommended action

imply the request is valid, the requested entity


exists, or it satisfies other preconditions.

8 RESOURCE_EXHAUSTED Some resource has been exhausted, such as a Retry with exponential
per-project quota. backoff. Quota might
become available over
time.

9 FAILED_PRECONDITIONThe operation was rejected because the system Don't retry without fixing
isn't in a state required for the operation's the problem.
execution. For example, the directory to be
deleted is non-empty, or an rmdir operation is
applied to a non-directory.

10 ABORTED The operation was aborted, typically due to a Retry with exponential
concurrency issue such as a sequencer check backoff.
failure or transaction abort.

11 OUT_OF_RANGE The operation was attempted past the valid Don't retry without fixing
range, such as seeking or reading past end-of- the problem.
file. Unlike INVALID_ARGUMENT, this error
indicates a problem that may be fixed if the
system state changes.

12 UNIMPLEMENTED The operation isn't implemented or isn't Don't retry.


supported/enabled in the Drive API.

13 INTERNAL Internal errors. This indicates that an Retry with exponential


unexpected error was encountered in backoff.
processing on the underlying system.

14 UNAVAILABLE The Drive API is unavailable. This is most likely Retry with exponential
a transient condition, which can be corrected by backoff.
retrying with exponential backoff. Note that it's
not always safe to retry non-idempotent
operations.

15 DATA_LOSS Unrecoverable data loss or corruption. Contact your system


administrator. The
system administrator
might want to contact a
support representative if
data loss or corruption
occurred.

16 UNAUTHENTICATED The request doesn't have valid authentication Don't retry without fixing
credentials for the operation. the problem.

https://developers.google.com/workspace/drive/api/guides/long-running-operations 9/10
6/27/25, 10:02 AM Manage long-running operations | Google Drive | Google for Developers

Related topics
Download and export files (/workspace/drive/api/guides/manage-downloads)

Manage file revisions (/workspace/drive/api/guides/manage-revisions)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/long-running-operations 10/10
6/27/25, 10:02 AM Manage file revisions | Google Drive | Google for Developers

Manage file revisions


Google Drive API provides the revisions (/workspace/drive/api/reference/rest/v3/revisions)
resource so that you can download and publish file revisions. For more details about
revision terminology, see Changes and revisions overview
(/workspace/drive/api/guides/change-overview).

Specify revisions to save from auto delete


Google Drive automatically deletes older revisions that are no longer of interest to the user.
To prevent this from happening, you can set the boolean flag keepRevisionForever to
true to mark revisions that you don't want Drive to purge.

Download a revision
To download the latest revision, use the files.download
(/workspace/drive/api/v3/reference/files/download) method. For more information, see Manage
long-running operations (/workspace/drive/api/guides/long-running-operations#download-revision).

Publish a revision
To publish a Google Docs, Google Sheets, and Google Slides revision, set the published
property for that file in the revisions (/workspace/drive/api/reference/rest/v3/revisions)
resource. This property can't be set for Google Sites revisions using Drive API.

Google Slides and Google Drawings don't support publishing specific revisions. Only
automatic re-publishing of the most recent revision is supported. To publish Slides and
Drawings, also set publishAuto to true.

If the file is created in a Google Workspace domain, the publishedOutsideDomain property


indicates whether the revision is accessible by anyone or if it's restricted to users of the
domain. For Sites files, this property indicates whether a type=anyone permission exists.

Published revisions don't reflect changes made to a file unless the publishAuto property is
set. If that property is set to true, newer revisions of a file are automatically published,
overwriting the previous ones. This behavior is also controlled by the "Automatically re-

https://developers.google.com/workspace/drive/api/guides/manage-revisions 1/2
6/27/25, 10:02 AM Manage file revisions | Google Drive | Google for Developers

publish when changes are made" checkbox in the Drive UI. Slides and Drawings only
support automatic re-publishing and require the publishAuto property to be set to true.
For Sites files, publishAuto is always false.

Related topics
Download and export files (/workspace/drive/api/guides/manage-downloads)

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0
License (https://creativecommons.org/licenses/by/4.0/), and code samples are licensed under the Apache
2.0 License (https://www.apache.org/licenses/LICENSE-2.0). For details, see the Google Developers Site
Policies (https://developers.google.com/site-policies). Java is a registered trademark of Oracle and/or its
affiliates.

Last updated 2025-06-04 UTC.

https://developers.google.com/workspace/drive/api/guides/manage-revisions 2/2

You might also like