Children: list

Stay organized with collections Save and categorize content based on your preferences.

Lists a folder's children. To list all children of the root folder, use the alias root for the folderId value. Try it now or see an example.

This method accepts the q parameter, which is a search query combining one or more search terms. For more information, see the Search for files guide.

Request

HTTP request

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

Parameters

Parameter name Value Description
Path parameters
folderId string The ID of the folder. To list all files in the root folder, use the alias root as the value for folderId.
Optional query parameters
maxResults integer Maximum number of children to return. Acceptable values are 0 to 1000, inclusive. (Default: 100)
orderBy string A comma-separated list of sort keys. Valid keys are 'createdDate', 'folder', 'lastViewedByMeDate', 'modifiedByMeDate', 'modifiedDate', 'quotaBytesUsed', 'recency', 'sharedWithMeDate', 'starred', and 'title'. Each key sorts ascending by default, but may be reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedDate desc,title. Please note that there is a current limitation for users with approximately one million files in which the requested sort order is ignored.
pageToken string Page token for children.
q string Query string for searching children. 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:

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.metadata
https://www.googleapis.com/auth/drive.photos.readonly

Some scopes are restricted and require a security assessment for your app to use them. For more information, see the authentication and authorization page.

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#childList",
  "etag": etag,
  "selfLink": string,
  "nextPageToken": string,
  "nextLink": string,
  "items": [
    children Resource
  ]
}
Property name Value Description Notes
kind string This is always drive#childList.
etag etag The ETag of the list.
nextPageToken string The page token for the next page of children. This will be absent if the end of the children list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results.
items[] list The list of children. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched.

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.Children;
import com.google.api.services.drive.model.ChildList;
import com.google.api.services.drive.model.ChildReference;

import java.io.IOException;

// ...

public class MyClass {

  // ...

  /**
   * Print files belonging to a folder.
   *
   * @param service Drive API service instance.
   * @param folderId ID of the folder to print files from.
   */
  private static void printFilesInFolder(Drive service, String folderId)
      throws IOException {
    Children.List request = service.children().list(folderId);

    do {
      try {
        ChildList children = request.execute();

        for (ChildReference child : children.getItems()) {
          System.out.println("File Id: " + child.getId());
        }
        request.setPageToken(children.getNextPageToken());
      } catch (IOException e) {
        System.out.println("An error occurred: " + e);
        request.setPageToken(null);
      }
    } while (request.getPageToken() != null &&
             request.getPageToken().length() > 0);
  }

  // ...

}

.NET

Uses the .NET client library.

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

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Print files belonging to a folder.
  /// </summary>
  /// <param name="service">Drive API service instance.</param>
  /// <param name="folderId">ID of the folder to print files from</param>
  public static void PrintFilesInFolder(DriveService service,
      String folderId) {
    ChildrenResource.ListRequest request = service.Children.List(folderId);

    do {
      try {
        ChildList children = request.Execute();

        foreach (ChildReference child in children.Items) {
          Console.WriteLine("File Id: " + child.Id);
        }
        request.PageToken = children.NextPageToken;
      } catch (Exception e) {
        Console.WriteLine("An error occurred: " + e.Message);
        request.PageToken = null;
      }
    } while (!String.IsNullOrEmpty(request.PageToken));
  }

  // ...

}

PHP

Uses the PHP client library.

/**
 * Print files belonging to a folder.
 *
 * @param Google_Service_Drive $service Drive API service instance.
 * @param String $folderId ID of the folder to print files from.
 */
function printFilesInFolder($service, $folderId) {
  $pageToken = NULL;

  do {
    try {
      $parameters = array();
      if ($pageToken) {
        $parameters['pageToken'] = $pageToken;
      }
      $children = $service->children->listChildren($folderId, $parameters);

      foreach ($children->getItems() as $child) {
        print 'File Id: ' . $child->getId();
      }
      $pageToken = $children->getNextPageToken();
    } catch (Exception $e) {
      print "An error occurred: " . $e->getMessage();
      $pageToken = NULL;
    }
  } while ($pageToken);
}

Python

Uses the Python client library.

from apiclient import errors
# ...

def print_files_in_folder(service, folder_id):
  """Print files belonging to a folder.

  Args:
    service: Drive API service instance.
    folder_id: ID of the folder to print files from.
  """
  page_token = None
  while True:
    try:
      param = {}
      if page_token:
        param['pageToken'] = page_token
      children = service.children().list(
          folderId=folder_id, **param).execute()

      for child in children.get('items', []):
        print 'File Id: %s' % child['id']
      page_token = children.get('nextPageToken')
      if not page_token:
        break
    except errors.HttpError, error:
      print 'An error occurred: %s' % error
      break

JavaScript

Uses the JavaScript client library.

/**
 * Retrieve a list of files belonging to a folder.
 *
 * @param {String} folderId ID of the folder to retrieve files from.
 * @param {Function} callback Function to call when the request is complete.
 *
 */
function retrieveAllFilesInFolder(folderId, callback) {
  var retrievePageOfChildren = function(request, result) {
    request.execute(function(resp) {
      result = result.concat(resp.items);
      var nextPageToken = resp.nextPageToken;
      if (nextPageToken) {
        request = gapi.client.drive.children.list({
          'folderId' : folderId,
          'pageToken': nextPageToken
        });
        retrievePageOfChildren(request, result);
      } else {
        callback(result);
      }
    });
  }
  var initialRequest = gapi.client.drive.children.list({
      'folderId' : folderId
    });
  retrievePageOfChildren(initialRequest, []);
}

Go

Uses the Go client library.

import (
  "google.golang.org/drive/v2"
  "fmt"
)

// AllChildren fetches all the children of a given folder
func AllChildren(d *drive.Service, folderId string) ([]*drive.ChildReference,
    error) {
  var cs []*drive.ChildReference
  pageToken := ""
  for {
    q := d.Children.List(folderId)
    // 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 = r.NextPageToken
    if pageToken == "" {
      break
    }
  }
  return cs, nil
}

Objective-C

Uses the Objective-C client library.

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

+ (void)printFilesInFolderWithService:(GTLServiceDrive *)service
                             folderId:(NSString *)folderId {
  // The service can be set to automatically fetch all pages of the result. More
  // information can be found on <a href="https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Result_Pages">https://code.google.com/p/google-api-objectivec-client/wiki/Introduction#Result_Pages</a>.
  service.shouldFetchNextPages = YES;

  GTLQueryDrive *query =
    [GTLQueryDrive queryForChildrenListWithFolderId:folderId];
  // queryTicket can be used to track the status of the request.
  GTLServiceTicket *queryTicket =
    [service executeQuery:query
        completionHandler:^(GTLServiceTicket *ticket,
                            GTLDriveChildList *children, NSError *error) {
          if (error == nil) {
            for (GTLDriveChildReference *child in children) {
              NSLog(@"File Id: %@", child.identifier);
            }
          } else {
            NSLog(@"An error occurred: %@", error);
          }
        }];
}

// ...

Try it!

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