Work with events from Google Drive Stay organized with collections Save and categorize content based on your preferences.
This page explains how to receive Google Drive events fromGoogle CloudPub/Sub.
ADrive event represents an activity or change to aDrive resource, such as a new file in a folder. You can useevents to understand what happened and then take action, or to respond in ameaningful way for your users.
Here are some examples of how you can use events:
Observe and respond to changes in a file, folder, or shared drive, such aswhen a file is edited or a new revision is uploaded.
Monitor changes to files to improve the performance of your app.
Audit activities like file sharing, file moves, and deletions to help detectpotential data leaks and unauthorized access.
Offer insights into how users are managing their files, helping to identifyareas where content management could be improved.
Track file changes to verify compliance with regulatory requirements orsecurity policies.
Analyze Drive activity using other Google Cloudproducts such asEventarc,Workflows,andBigQuery.
How events work
Whenever something happens in Drive, a Google Drive API resource iscreated, updated, or deleted. Drive uses events to deliverinformation to your app about the type of activity that occurred, and theDrive API resource that was affected.
Drive categorizes events by type. Event types help you filter andreceive only the type of information you need, and let you handle similaractivities in the same way.
The following table shows how an example activity in Driveaffects a related Drive API resource, and the type of event that yourDrive app receives:
| Activity | Drive API resource | Event type |
|---|---|---|
| A user creates an access proposal on a file. | AnAccessProposal resource is created. | New access proposal |
A user creates an approval on a file. | AnApproval resource is created. | New approval |
| A user posts a comment in a Google Docs, Sheets, or Slides file. | AComment resource is created. | New comment |
| A user adds a file to a folder or shared drive. | AFile resource is created. | New file |
| A user replies to a comment. | AReply resource is created. | New reply |
Receive events from Google Drive
Traditionally, your Drive app could locate events through eitherthe Drive API or the Google Drive Activity API. With the addition ofDrive events in Google Workspace Events API, there's now a thirdmethod receive events:
Developer Preview: Subscribe to events using theGoogle Workspace Events API to receive events as theyoccur. For more information, seeSubscribe to Google Driveevents.
Subscribe to events using the Drive API. Get user change eventswith the
changes.watchmethod or file change events using thefiles.watchmethod.Query for recent events by calling theGoogle Drive Activity API.
The following table explains the difference and reasons for subscribing toevents versus querying for them:
| Subscribe to Google Workspace events | Subscribe to Drive API watch events | Query for Drive Activity API events | |
|---|---|---|---|
| Use cases |
|
|
|
| API | Google Workspace Events API | Google Drive API | Google Drive Activity API |
| Source of events | Files, folders, and shared drives | changes.watch andfiles.watch | DriveActivity |
| Supported events |
| ChannelFor a list of supported event types, see the Understand Google Drive API notification events in the Drive API documentation. | ActionFor a list of supported fields, see the Action resource in the Drive Activity API reference documentation. |
| Event format | A Pub/Sub message, formatted according to the CloudEvent specification. For details, seeStructure of Google Workspace events. | A Drive API resource (Channel) | An Drive Activity API resource (Action) |
| Event data | Base64-encoded string with or without resource data. For example payloads, seeEvent data. | JSON payload that contains resource data. For an example payload, see theChannel resource in the reference documentation. | JSON payload that contains resource data. For an example payload, see theactivity.query response body in the reference documentation. |
Get started with Drive events
This guide explains how to create and manage a Google Workspace eventssubscription on a Drive resource. This lets your app receiveevents over Google Cloud Pub/Sub.
Create a Google Cloud project
To generate a Google Cloud project, seeCreate a Google Cloudproject.
Enable the Google Workspace Events API, Google Cloud Pub/Sub API, and Google Drive API
Before using Google APIs, you need to turn them on in a Google Cloud project.You can turn on one or more APIs in a single Google Cloud project.Google Cloud console
In the Google Cloud console, open the Google Cloud project for your app andenable the Google Workspace Events API, Pub/Sub API, andDrive API:
Confirm that you're enabling the APIs in the correctCloud project, then clickNext.
Confirm that you're enabling the correct APIs, then clickEnable.
gcloud
In your working directory, sign in to your Google Account:
gcloudauthloginSet your project to the Cloud project for your app:
gcloudconfigsetprojectPROJECT_IDReplace
PROJECT_IDwith theprojectIDfor the Cloud project for your app.Enable the Google Workspace Events API, Pub/Sub API, andDrive API:
gcloudservicesenableworkspaceevents.googleapis.com\pubsub.googleapis.com\drive.googleapis.com
Set up a client ID
To generate an OAuth 2.0 client ID, seeCreate OAuth client IDcredentials.
Create a Pub/Sub topic
Before creating a subscription, you must create a Google Cloud Pub/Subtopic that receives relevant events your application is interested in. To createthe Pub/Sub topic, seeCreate and subscribe to a Pub/Subtopic.
Make sure to reference the Drive service account(drive-api-event-push@system.gserviceaccount.com) for your requests.
Create a Drive subscription
Beta: Drive events are in Developer Preview. You must use thev1beta version of the API. Attemptsto use the standardv1 version of the API will fail.Cloud events are dispatched when the subscription subject (or any other fileunderneath the subject's hierarchy) changes. For example, if you create asubscription on a shared drive and a file changes that's nested within severalsubfolders in that shared drive, it generates an event. For supported resourcesand Drive event types, seeEvent types for creatingsubscriptions.
The following Node.js application creates a Drive eventssubscription on a file or folder to listen for content change events. For moreinformation, seeCreate a Google Workspacesubscription.
To run this example, make sure you have bothNode.js & npminstalled.You also need to make sure you have the required dependencies installed to runthis example.
# Install needed dependencies$npminstallgoogleapis@google-cloud/local-authaxiosTo create a Drive subscription you use theGoogle Workspace Events API'ssubscriptions.create() method to create aSubscription resource:
// app.jsconstfs=require('fs').promises;const{authenticate}=require('@google-cloud/local-auth');const{google}=require('googleapis');constaxios=require('axios');// Scopes for Google Drive API access.constSCOPES=['SCOPES'];/** * Authenticates the user running the script. * @return {Promise<OAuth2Client>} The authorized client. */asyncfunctionauthorize(){constclient=awaitauthenticate({scopes:SCOPES,keyfilePath:'credentials.json',});if(client.credentials){constcontent=awaitfs.readFile('credentials.json');constkeys=JSON.parse(content);const{client_id,client_secret}=keys.installed||keys.web;constpayload=JSON.stringify({type:'authorized_user',client_id,client_secret,refresh_token:client.credentials.refresh_token,});awaitfs.writeFile('token.json',payload);returnclient;}else{thrownewException('credentials.json did not have the Oauth client secret or it was not properly formatted');}}/** * Creates a subscription to Google Drive events. * @param {OAuth2Client} authClient An authorized OAuth2 client. */asyncfunctioncreateSubscription(authClient){consturl='https://workspaceevents.googleapis.com/v1beta/subscriptions';constdata={targetResource:'TARGET_RESOURCE',eventTypes:['EVENT_TYPES'],payload_options:{include_resource:{{'<var>RESOURCE_DATA</var>'}}},drive_options:{include_descendants:{{'<var>INCLUDE_DESCENDANTS</var>'}}},notification_endpoint:{pubsub_topic:'TOPIC_NAME'}};try{const{token}=awaitauthClient.getAccessToken();constresponse=awaitaxios.post(url,data,{headers:{'Authorization':`Bearer${token}`}});console.log('Subscription created:',response.data);}catch(error){constmessage=error.response?error.response.data:error.message;console.error('Error creating subscription:',message);}}authorize().then(createSubscription).catch(console.error);Replace the following:
SCOPES: One or moreOAuthscopes that support each event type for thesubscription. Formatted as an array of strings. To list multiple scopes,separate by commas. As a best practice, you should use the most restrictivescope that still allows your app to function. For example,'https://www.googleapis.com/auth/drive.file'.TARGET_RESOURCE: TheGoogle Workspace resourcethat you're subscribing to, formatted as its full resource name. Forexample, to subscribe to a Drive file or folder, use//drive.googleapis.com/files/FileID.EVENT_TYPES: One or moreevent typesthat you want to subscribe to in the target resource. Format as an array ofstrings, such as'google.workspace.drive.file.v3.contentChanged'.RESOURCE_DATA: A boolean that specifies whether thesubscription includes resource data in the event payload. This propertyaffects the duration time of your subscription. To learn more, seeEventdata.True: Includes all resource data. To limit which fields are included,add thefieldMaskand specify at least one field for the changed resource. Only subscriptionsto Chat and Drive resource support includingresource data.False: Excludes resource data.
INCLUDE_DESCENDANTS: A boolean field that's part ofDriveOptions.Only available when thetargetResourceis either a Drivefile or a shared drive that has the MIME type set toapplication/vnd.google-apps.folder. Cannot be set on the root folder of MyDrive or shared drives.True: The subscription includes all descendant Drivefiles in the list of events.False: The subscription is created for the single file or shared drivethat's specified as thetargetResource.
TOPIC_NAME: The full name of the Pub/Sub topic that youcreated in your Cloud project. This Pub/Sub topic receives eventsfor the subscription. Formatted asprojects/PROJECT_ID/topics/TOPIC_ID. ThenotificationEndpointfield is used to specify the Pub/Sub topic and it's where the subscriptiondelivers events.
Test your Drive subscription
To test that you're receiving Drive events, you can trigger anevent and pull messages to the Pub/Sub subscription. For more information, seeTest your Google Workspacesubscription.
Process Drive events using Cloud Functions
Drive events are sent to the Pub/Sub topic in the subscriptionyou create. Make sure when creating the trigger that the Pub/Sub topic for thetrigger matches the Pub/Sub topic in your event subscription. You can thendeploy your Cloud Runfunction and make edits tothe file to see event changes in the logs.
Before you create the function, update thepackage.json for the dependencies:
{"dependencies":{"@google-cloud/functions-framework":"^3.0.0","cloudevents":"^8.0.0"}}Next, create the source code for the function:
constfunctions=require('@google-cloud/functions-framework');const{HTTP}=require("cloudevents");/** * A Cloud Function triggered by Pub/Sub messages containing Google Drive activity events. * This function processes different types of Drive events. * * @param {object} cloudEvent The CloudEvent object. * @param {object} cloudEvent.data The data payload from the event source. */functions.cloudEvent('helloFromDrive',async(cloudEvent)=>{try{// Verify the Pub/Sub message existsif(!cloudEvent.data||!cloudEvent.data.message){console.warn("Event is missing the Pub/Sub message payload.");return;}// Extract the Pub/Sub message detailsconst{message}=cloudEvent.data;const{attributes,data}=message;// The original Drive CloudEvent is reconstructed from the Pub/Sub message attributesconstdriveEvent=HTTP.toEvent({headers:attributes});const{type}=driveEvent;// The Drive event's payload is a base64 encoded JSON stringconstpayload=JSON.parse(Buffer.from(data,"base64").toString());console.log(`Processing Drive event type:${type}`);// Use a switch statement to handle different event typesswitch(type){case'google.workspace.drive.file.v3.contentChanged':console.log('File Content Changed:',payload);break;case'google.workspace.drive.accessproposal.v3.created':console.log('Access Proposal Created:',payload);break;default:console.log(`Received unhandled event type:${type}`);break;}}catch(error){console.error("An error occurred while processing the Drive event:",error);}});Limitations
- When the
includeDescendantsboolean field inDriveOptionsistrue, Drive subscriptions on shared drives and folders always dispatch an event, even if the file that triggered the event is nested many layers below the folder used for the Drive subscription. - Even though you may have created a subscription on a folder, you may not receive all events within the file hierarchy as the user or application may not be granted access to them. In this case, the subscription remains active but you won't receive any events for resources you don't have access to.
- Subscriptions are supported for events on all files and folders but not on the root folder of shared drives. Subscriptions are only supported for files and foldersinside shared drives. Changes made directly to the root folder of a shared drive won't trigger events.
- The user that authorizes the subscription must have permission on the file corresponding to the events that they subscribe to.
- The subscription only receives events for resources where the user has access through their Google Workspace account or Google Account.
Related topics
- Google Workspace Events API overview
- Create a Google Workspace subscription
- Subscribe to Google Drive events
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-17 UTC.