Google Drive SDK

Changes: list

Requires authorization

Lists the changes for a user. Try it now or see an example.

Request

HTTP request

GET https://www.googleapis.com/drive/v2/changes

Parameters

Parameter name Value Description
Optional query parameters
includeDeleted boolean Whether to include deleted items. (Default: true)
includeSubscribed boolean Whether to include shared files and public files the user has opened. When set to false, the list will include owned files plus any shared or public files the user has explictly added to a folder in Drive. (Default: true)
maxResults integer Maximum number of changes to return. Acceptable values are 0 to 1000, inclusive. (Default: 100)
pageToken string Page token for changes.
startChangeId long Change ID to start listing changes from.

Authorization

This request requires authorization with at least one of the following scopes (read more about authentication and authorization).

Scope
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/drive.readonly
https://www.googleapis.com/auth/drive.metadata.readonly
https://www.googleapis.com/auth/drive.appdata
https://www.googleapis.com/auth/drive.apps.readonly

Request body

Do not supply a request body with this method.

Response

If successful, this method returns a response body with the following structure:

{
  "kind": "drive#changeList",
  "etag": etag,
  "selfLink": string,
  "nextPageToken": string,
  "nextLink": string,
  "largestChangeId": long,
  "items": [
    changes Resource
  ]
}
Property name Value Description Notes
kind string This is always drive#changeList.
etag etag The ETag of the list.
nextPageToken string The page token for the next page of changes.
largestChangeId long The current largest change ID.
items[] list The actual list of changes.

Examples

Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).

Java

Uses the Java client library

import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Changes;
import com.google.api.services.drive.model.Change;
import com.google.api.services.drive.model.ChangeList;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

// ...

public class MyClass {

  // ...

  /**
   * Retrieve a list of Change resources.
   *
   * @param service Drive API service instance.
   * @param startChangeId ID of the change to start retrieving subsequent
                          changes from or {@code null}.
   * @return List of Change resources.
   */
  private static List<Change> retrieveAllChanges(Drive service,
      Long startChangeId) throws IOException {
    List<Change> result = new ArrayList<Change>();
    Changes.List request = service.changes().list();

    if (startChangeId != null) {
      request.setStartChangeId(startChangeId);
    }
    do {
      try {
        ChangeList changes = request.execute();

        result.addAll(changes.getItems());
        request.setPageToken(changes.getNextPageToken());
      } catch (IOException e) {
        System.out.println("An error occurred: " + e);
        request.setPageToken(null);
      }
    } while (request.getPageToken() != null &&
             request.getPageToken().length() > 0);

    return result;
  }

  // ...

}

.NET

Uses the .NET client library

using Google.Apis.Authentication;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;

using System.Collections.Generic;
// ...

public class MyClass {

  // ...

  /// <summary>
  /// Retrieve a list of Change resources.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="startChangeId">
  /// ID of the change to start retrieving subsequent changes from or null.
  /// </param>
  /// <returns>List of Change resources.</returns>
  public static List<Change> retrieveAllChanges(DriveService service,
      String startChangeId) {
    List<Change> result = new List<Change>();
    ChangesResource.ListRequest request = service.Changes.List();

    if (!String.IsNullOrEmpty(startChangeId)) {
      request.StartChangeId = startChangeId;
    }
    do {
      try {
        ChangeList changes = request.Fetch();

        result.AddRange(changes.Items);
        request.PageToken = changes.NextPageToken;
      } catch (Exception e) {
        Console.WriteLine("An error occurred: " + e.Message);
        request.PageToken = null;
      }
    } while (!String.IsNullOrEmpty(request.PageToken));
    return result;
  }

  // ...
}

PHP

Uses the PHP client library

/**
 * Retrieve a list of Change resources.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @param String $startChangeId ID of the change to start retrieving subsequent
                                changes from or NULL.
 * @return Array List of Google_Change resources.
 */
function retrieveAllChanges($service, $startChangeId = NULL) {
  $result = array();
  $pageToken = NULL;

  do {
    try {
      $parameters = array();
      if ($startChangeId) {
        $parameters['startChangeId'] = $startChangeId;
      }
      if ($pageToken) {
        $parameters['pageToken'] = $pageToken;
      }
      $changes = $service->changes->listChanges($parameters);

      $result = array_merge($result, $changes->getItems());
      $pageToken = $changes->getNextPageToken();
    } catch (Exception $e) {
      print "An error occurred: " . $e->getMessage();
      $pageToken = NULL;
    }
  } while ($pageToken);
  return $result;
}

Python

Uses the Python client library

from apiclient import errors
# ...

def retrieve_all_changes(service, start_change_id=None):
  """Retrieve a list of Change resources.

  Args:
    service: Drive API service instance.
    start_change_id: ID of the change to start retrieving subsequent changes
                     from or None.
  Returns:
    List of Change resources.
  """
  result = []
  page_token = None
  while True:
    try:
      param = {}
      if start_change_id:
        param['startChangeId'] = start_change_id
      if page_token:
        param['pageToken'] = page_token
      changes = service.changes().list(**param).execute()

      result.extend(changes['items'])
      page_token = changes.get('nextPageToken')
      if not page_token:
        break
    except errors.HttpError, error:
      print 'An error occurred: %s' % error
      break
  return result

Ruby

Uses the Ruby client library

##
# Retrieve a list of Change resources.
#
# @param [Google::APIClient] client
#   Authorized client instance
# @param [String] start_change_id
#   ID of the change to start retrieving subsequent changes from or nil.
# @return [Array]
#   List of Change resources.
#
def retrieve_all_changes(client, start_change_id=nil)
  drive = client.discovered_api('drive', 'v2')
  result = Array.new
  page_token = nil
  begin
    parameters = {}
    if start_change_id.to_s != ''
      parameters['startChangeId'] = start_change_id
    end
    if page_token.to_s != ''
      parameters['pageToken'] = page_token
    end
    api_result = client.execute(
      :api_method => drive.changes.list,
      :parameters => parameters)
    if api_result.status == 200
      changes = api_result.data
      result.concat(changes.items)
      page_token = files.next_page_token
    else
      puts "An error occurred: #{result.data['error']['message']}"
      page_token = nil
    end
  end while page_token.to_s != ''
  result
end

JavaScript

Uses the JavaScript client library

/**
 * Retrieve a list of Change resources.
 *
 * @param {Function} callback Function to call when the request is complete.
 * @param {String} startChangeId ID of the change to start retrieving subsequent
 *                               changes from or {@code null}.
 *
 */
function retrieveAllChanges(callback, startChangeId) {
  var retrievePageOfChanges = function(request, result) {
    request.execute(function(resp) {
      result = result.concat(resp.items);
      var nextPageToken = resp.nextPageToken;
      if (nextPageToken) {
        request = gapi.client.drive.changes.list({
          'pageToken': nextPageToken
        });
        retrievePageOfChanges(request, result);
      } else {
        callback(result);
      }
    });
  }
  var initialRequest;
  if (startChangeId) {
    initialRequest = gapi.client.drive.changes.list({
      'startChangeId' : startChangeId
    });
  } else {
    initialRequest = gapi.client.drive.changes.list();
  }
  retrievePageOfChanges(initialRequest, []);
}

Go

Uses the Go client library

import (
  "code.google.com/p/google-api-go-client/drive/v2"
  "fmt"
)

// AllChanges fetches all changes after a starting change
func AllChanges(d *drive.Service,
    startChangeId string) ([]*drive.Change, error) {
  var cs []*drive.Change
  pageToken := ""
  for {
    q := d.Changes.List()
    // If we have a pageToken set, apply it to the query
    if pageToken != "" {
      q = q.PageToken(pageToken)
    }
    r, err := q.Do()
    if err != nil {
      fmt.Printf("An error occurred: %v\n", err)
      return cs, err
    }
    cs = append(cs, r.Items...)
    pageToken = string(r.NextPageToken)
    if pageToken == "" {
      break
    }
  }
  return cs, nil
}

Objective-C

Uses the Objective-C client library

#import "GTLDrive.h"
// ...

+ (void)retrieveAllChangesWithService:(GTLServiceDrive *)service
                        startChangeId:(long long)startChangeId
                      completionBlock:(void (^)(NSArray *, NSError *))completionBlock {
  // The service can be set to automatically fetch all pages of the result. More information
  // can be found on https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Result_Pages.
  service.shouldFetchNextPages = YES;

  GTLQueryDrive *query = [GTLQueryDrive queryForChangesList];
  if (startChangeId != -1) {
    query.startChangeId =  startChangeId;
  }
  // queryTicket can be used to track the status of the request.
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket, GTLDriveChangeList *changes,
                            NSError *error) {
          if (error == nil) {
            completionBlock(changes.items, nil);
          } else {
            NSLog(@"An error occurred: %@", error);
            completionBlock(nil, error);
          }
        }];
}

// ...

Try it!

Use the APIs Explorer below to call this method on live data and see the response.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.