importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.StartPageToken;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;/* Class to demonstrate use-case of Drive's fetch start page token */publicclassFetchStartPageToken{/** * Retrieve the start page token for the first time. * * @return Start page token as String. * @throws IOException if file is not found */publicstaticStringfetchStartPageToken()throwsIOException{/*Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();try{StartPageTokenresponse=service.changes().getStartPageToken().execute();System.out.println("Start token: "+response.getStartPageToken());returnresponse.getStartPageToken();}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to fetch start page token: "+e.getDetails());throwe;}}}
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordeffetch_start_page_token():"""Retrieve page token for the current state of the account. Returns & prints : start page token Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """creds,_=google.auth.default()try:# create drive api clientservice=build("drive","v3",credentials=creds)# pylint: disable=maybe-no-memberresponse=service.changes().getStartPageToken().execute()print(f'Start token: {response.get("startPageToken")}')exceptHttpErroraserror:print(f"An error occurred: {error}")response=Nonereturnresponse.get("startPageToken")if__name__=="__main__":fetch_start_page_token()
usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class to demonstrate use-case of Drive's fetch start page tokenpublicclassFetchStartPageToken{/// <summary>/// Retrieve the starting page token./// </summary>/// <returns>start page token as String, null otherwise.</returns>publicstaticstringDriveFetchStartPageToken(){try{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.Drive);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});varresponse=service.Changes.GetStartPageToken().Execute();// Prints the token value.Console.WriteLine("Start token: "+response.StartPageTokenValue);returnresponse.StartPageTokenValue;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}else{throw;}}returnnull;}}}
/** * Retrieve page token for the current state of the account. **/asyncfunctionfetchStartPageToken(){// Get credentials and build service// TODO (developer) - Use appropriate auth mechanism for your appconst{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive.appdata',});constservice=google.drive({version:'v3',auth});try{constres=awaitservice.changes.getStartPageToken({});consttoken=res.data.startPageToken;console.log('start token: ',token);returntoken;}catch(err){// TODO(developer) - Handle errorthrowerr;}}
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;importcom.google.api.client.http.HttpRequestInitializer;importcom.google.api.client.http.javanet.NetHttpTransport;importcom.google.api.client.json.gson.GsonFactory;importcom.google.api.services.drive.Drive;importcom.google.api.services.drive.DriveScopes;importcom.google.api.services.drive.model.ChangeList;importcom.google.auth.http.HttpCredentialsAdapter;importcom.google.auth.oauth2.GoogleCredentials;importjava.io.IOException;importjava.util.Arrays;/* Class to demonstrate use-case of Drive's fetch changes in file. */publicclassFetchChanges{/** * Retrieve the list of changes for the currently authenticated user. * * @param savedStartPageToken Last saved start token for this user. * @return Saved token after last page. * @throws IOException if file is not found */publicstaticStringfetchChanges(StringsavedStartPageToken)throwsIOException{/*Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application.*/GoogleCredentialscredentials=GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE_FILE));HttpRequestInitializerrequestInitializer=newHttpCredentialsAdapter(credentials);// Build a new authorized API client service.Driveservice=newDrive.Builder(newNetHttpTransport(),GsonFactory.getDefaultInstance(),requestInitializer).setApplicationName("Drive samples").build();try{// Begin with our last saved start token for this user or the// current token from getStartPageToken()StringpageToken=savedStartPageToken;while(pageToken!=null){ChangeListchanges=service.changes().list(pageToken).execute();for(com.google.api.services.drive.model.Changechange:changes.getChanges()){// Process changeSystem.out.println("Change found for file: "+change.getFileId());}if(changes.getNewStartPageToken()!=null){// Last page, save this token for the next polling intervalsavedStartPageToken=changes.getNewStartPageToken();}pageToken=changes.getNextPageToken();}returnsavedStartPageToken;}catch(GoogleJsonResponseExceptione){// TODO(developer) - handle error appropriatelySystem.err.println("Unable to fetch changes: "+e.getDetails());throwe;}}}
importgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpErrordeffetch_changes(saved_start_page_token):"""Retrieve the list of changes for the currently authenticated user. prints changed file's ID Args: saved_start_page_token : StartPageToken for the current state of the account. Returns: saved start page token. Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """creds,_=google.auth.default()try:# create drive api clientservice=build("drive","v3",credentials=creds)# Begin with our last saved start token for this user or the# current token from getStartPageToken()page_token=saved_start_page_token# pylint: disable=maybe-no-memberwhilepage_tokenisnotNone:response=(service.changes().list(pageToken=page_token,spaces="drive").execute())forchangeinresponse.get("changes"):# Process changeprint(f'Change found for file: {change.get("fileId")}')if"newStartPageToken"inresponse:# Last page, save this token for the next polling intervalsaved_start_page_token=response.get("newStartPageToken")page_token=response.get("nextPageToken")exceptHttpErroraserror:print(f"An error occurred: {error}")saved_start_page_token=Nonereturnsaved_start_page_tokenif__name__=="__main__":# saved_start_page_token is the token numberfetch_changes(saved_start_page_token=209)
use Google\Client;use Google\Service\Drive;# TODO - PHP client currently chokes on fetching start page tokenfunction fetchChanges(){ try { $client = new Client(); $client->useApplicationDefaultCredentials(); $client->addScope(Drive::DRIVE); $driveService = new Drive($client); # Begin with our last saved start token for this user or the # current token from getStartPageToken() $savedStartPageToken = readLine("Enter Start Page Token: "); $pageToken = $savedStartPageToken; while ($pageToken != null) { $response = $driveService->changes->listChanges($pageToken, array( 'spaces' => 'drive' )); foreach ($response->changes as $change) { // Process change printf("Change found for file: %s", $change->fileId); } if ($response->newStartPageToken != null) { // Last page, save this token for the next polling interval $savedStartPageToken = $response->newStartPageToken; } $pageToken = $response->nextPageToken; } echo $savedStartPageToken; } catch(Exception $e) { echo "Error Message: ".$e; }}require_once 'vendor/autoload.php';
usingGoogle.Apis.Auth.OAuth2;usingGoogle.Apis.Drive.v3;usingGoogle.Apis.Services;namespaceDriveV3Snippets{// Class to demonstrate use-case of Drive's fetch changes in file.publicclassFetchChanges{/// <summary>/// Retrieve the list of changes for the currently authenticated user./// prints changed file's ID/// </summary>/// <param name="savedStartPageToken">last saved start token for this user.</param>/// <returns>saved token for the current state of the account, null otherwise.</returns>publicstaticstringDriveFetchChanges(stringsavedStartPageToken){try{/* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */GoogleCredentialcredential=GoogleCredential.GetApplicationDefault().CreateScoped(DriveService.Scope.Drive);// Create Drive API service.varservice=newDriveService(newBaseClientService.Initializer{HttpClientInitializer=credential,ApplicationName="Drive API Snippets"});// Begin with our last saved start token for this user or the// current token from GetStartPageToken()stringpageToken=savedStartPageToken;while(pageToken!=null){varrequest=service.Changes.List(pageToken);request.Spaces="drive";varchanges=request.Execute();foreach(varchangeinchanges.Changes){// Process changeConsole.WriteLine("Change found for file: "+change.FileId);}if(changes.NewStartPageToken!=null){// Last page, save this token for the next polling intervalsavedStartPageToken=changes.NewStartPageToken;}pageToken=changes.NextPageToken;}returnsavedStartPageToken;}catch(Exceptione){// TODO(developer) - handle error appropriatelyif(eisAggregateException){Console.WriteLine("Credential Not found");}else{throw;}}returnnull;}}}
/** * Retrieve the list of changes for the currently authenticated user. * @param {string} savedStartPageToken page token got after executing fetch_start_page_token.js file **/asyncfunctionfetchChanges(savedStartPageToken){// Get credentials and build service// TODO (developer) - Use appropriate auth mechanism for your appconst{GoogleAuth}=require('google-auth-library');const{google}=require('googleapis');constauth=newGoogleAuth({scopes:'https://www.googleapis.com/auth/drive.readonly',});constservice=google.drive({version:'v3',auth});try{letpageToken=savedStartPageToken;do{constres=awaitservice.changes.list({pageToken:savedStartPageToken,fields:'*',});res.data.changes.forEach((change)=>{console.log('change found for file: ',change.fileId);});pageToken=res.data.newStartPageToken;returnpageToken;}while(pageToken);}catch(err){// TODO(developer) - Handle errorthrowerr;}}
[null,null,["อัปเดตล่าสุด 2025-02-24 UTC"],[[["The `changes` collection enables efficient tracking of all Google Drive file changes, including those shared with a user."],["To begin tracking changes, retrieve a start page token using `changes.getStartPageToken` and then use it with `changes.list` to get the initial list of changes."],["The `changes.list` method retrieves a chronological list of file changes, and you can use the `nextPageToken` or `newStartPageToken` to fetch subsequent changes."],["Subscribe to change notifications using `changes.watch` to receive updates when new changes are available, and then poll the change feed using `changes.list` to retrieve the actual changes."]]],["Google Drive's `changes` collection efficiently tracks file modifications. To begin, use `changes.getStartPageToken` to get a token representing the current account state, storing it for initial use with `changes.list`. Subsequently, `changes.list` retrieves changes chronologically; `includeRemoved` and `restrictToMyDrive` refine the response. Iterate through pages using `nextPageToken` and store `newStartPageToken` for future use. Lastly, `changes.watch` subscribes to change log updates, prompting a poll of the change feed for details.\n"]]