Google Drive SDK

Files: list

Requires authorization

Lists the user's files. Try it now or see an example.

Requests with files.list accept the q parameter, which is a search query combining one or more search terms. For more information, see Search for files.

Request

HTTP request

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

Parameters

Parameter name Value Description
Optional query parameters
maxResults integer Maximum number of files to return. Acceptable values are 0 to 1000, inclusive. (Default: 100)
pageToken string Page token for files.
projection string This parameter is deprecated and has no function.

Acceptable values are:
  • "BASIC": Deprecated
  • "FULL": Deprecated
q string Query string for searching files. See Searching for files for more information about supported fields and operations.

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#fileList",
  "etag": etag,
  "selfLink": string,
  "nextPageToken": string,
  "nextLink": string,
  "items": [
    files Resource
  ]
}
Property name Value Description Notes
kind string This is always drive#fileList.
etag etag The ETag of the list.
nextPageToken string The page token for the next page of files.
items[] list The actual list of files.

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.Files;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

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

// ...

public class MyClass {

  // ...

  /**
   * Retrieve a list of File resources.
   *
   * @param service Drive API service instance.
   * @return List of File resources.
   */
  private static List<File> retrieveAllFiles(Drive service) throws IOException {
    List<File> result = new ArrayList<File>();
    Files.List request = service.files().list();

    do {
      try {
        FileList files = request.execute();

        result.addAll(files.getItems());
        request.setPageToken(files.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.Drive.v2;
using Google.Apis.Drive.v2.Data;

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

public class MyClass {

  // ...

  /// <summary>
  /// Retrieve a list of File resources.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <returns>List of File resources.</returns>
  public static List<File> retrieveAllFiles(DriveService service) {
    List<File> result = new List<File>();
    FilesResource.ListRequest request = service.Files.List();

    do {
      try {
        FileList files = request.Fetch();

        result.AddRange(files.Items);
        request.PageToken = files.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 File resources.
 *
 * @param Google_DriveService $service Drive API service instance.
 * @return Array List of Google_DriveFile resources.
 */
function retrieveAllFiles($service) {
  $result = array();
  $pageToken = NULL;

  do {
    try {
      $parameters = array();
      if ($pageToken) {
        $parameters['pageToken'] = $pageToken;
      }
      $files = $service->files->listFiles($parameters);

      $result = array_merge($result, $files->getItems());
      $pageToken = $files->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_files(service):
  """Retrieve a list of File resources.

  Args:
    service: Drive API service instance.
  Returns:
    List of File resources.
  """
  result = []
  page_token = None
  while True:
    try:
      param = {}
      if page_token:
        param['pageToken'] = page_token
      files = service.files().list(**param).execute()

      result.extend(files['items'])
      page_token = files.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 File resources.
#
# @param [Google::APIClient] client
#   Authorized client instance
# @return [Array]
#   List of File resources.
#
def retrieve_all_files(client)
  drive = client.discovered_api('drive', 'v2')
  result = Array.new
  page_token = nil
  begin
    parameters = {}
    if page_token.to_s != ''
      parameters['pageToken'] = page_token
    end
    api_result = client.execute(
      :api_method => drive.files.list,
      :parameters => parameters)
    if api_result.status == 200
      files = api_result.data
      result.concat(files.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 File resources.
 *
 * @param {Function} callback Function to call when the request is complete.
 */
function retrieveAllFiles(callback) {
  var retrievePageOfFiles = function(request, result) {
    request.execute(function(resp) {
      result = result.concat(resp.items);
      var nextPageToken = resp.nextPageToken;
      if (nextPageToken) {
        request = gapi.client.drive.files.list({
          'pageToken': nextPageToken
        });
        retrievePageOfFiles(request, result);
      } else {
        callback(result);
      }
    });
  }
  var initialRequest = gapi.client.drive.files.list();
  retrievePageOfFiles(initialRequest, []);
}

Go

Uses the Go client library

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

// AllFiles fetches and displays all files
func AllFiles(d *drive.Service) ([]*drive.File, error) {
  var fs []*drive.File
  pageToken := ""
  for {
    q := d.Files.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 fs, err
    }
    fs = append(fs, r.Items...)
    pageToken = r.NextPageToken
    if pageToken == "" {
      break
    }
  }
  return fs, nil
}

Objective-C

Uses the Objective-C client library

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

+ (void)retrieveAllFilesWithService:(GTLServiceDrive *)service
                    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 queryForFilesList];
  // queryTicket can be used to track the status of the request.
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket, GTLDriveFileList *files,
                            NSError *error) {
          if (error == nil) {
            completionBlock(files.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.