Search code examples
phpgoogle-drive-api

The "pageSize" parameter does not work in google drive api v3


I use google drive api v3 with php. I stuck with the one problem. I set pageSize to 1000, but I receive only a bit more than 300 files and nextPageToken. Why I have to use nextPageToken if I have only 400 files and set pageSize to 1000?

$drive = new Google_Service_Drive($client);

$optParams = array(
    'pageSize' => 1000,
    'fields' => "nextPageToken, files(id,name,mimeType,webContentLink,webViewLink)",
    'q' => "'" . $folderId . "' in parents and trashed = false",
    'orderBy' => 'name'
    );

$results = $drive->files->listFiles($optParams);

Solution

  • There are various conditions that will cause the output set to be restricted to less than the proposed page size. For instance, including permissions in the files fields will limit the set to 100 each, while including parents will limit it to 360 items each. There are possibly other conditions as well.

    Bottom line, you can not reliably depend on having the maximum output set at the size requested using pageSize. To insure that you get the complete set of files requested, you will need to check and process the nextPageToken.

    Here is an example:

    function GetFiles($service)
    {
    
        $fileFields =
            'id, mimeType, name, ownedByMe, owners, parents, webContentLink';
    
        $options =
        [
            'pageSize' => 1000,
            'supportsAllDrives' => true,
            'fields' => "files($fileFields), nextPageToken"
        ];
    
        $files = [];
        $pageToken = null;
        do
        {
            try
            {
                if ($pageToken !== null)
                {
                    $options['pageToken'] = $pageToken;
                }
    
                $response = $service->files->listFiles($options);
    
                $files = array_merge($files, $response->files);
                $pageToken = $response->getNextPageToken();
            }
            catch (Exception $exception)
            {
                $message = $exception->getMessage();
                echo "exception: $message\r\n";
                $pageToken = null;
            }
        } while ($pageToken !== null);
    
        return $files;
    }