google-apigoogle-api-python-client

Listing Google Drive files returning empty list (Python)


I am testing my python connection to Google Drive using Python Google API Client. I am able to establish a connection, but I am not getting back a list of objects from Google Drive. I wonder if a lack of permission in my API key is giving a silent error.

from googleapiclient.discovery import build, Resource

def test_gdrive(gdrive):
    #connect to google drive.
    #gdrive is a custom class that returns a Resource object from googleapiclient
    service Resource = gdrive.connect_to_service('drive', gdrive.credentials, 'v3')
    assert service is not None # this passes
    # I simply want it to list the first page of all the results in my drive.
    results = service.files().list(q="'root' in parents and mimeType = 'application/vnd.google-apps.folder'"
                                   spaces='drive', 
                                   fields='nextPageToken, files(id, name)', 
                                   ).execute()
    items = results.get('files', [])
    if not items:
        raise AssertionError(f'No files found in test_gdrive. Results is {results}')
    else:
        assert items[0]['id'] is not None

I am getting the custom error. AssertionError: No files found in test_gdrive. Results is {'files': []}

I have also tried the query f"name='{self.folder_name}' and mimeType='application/vnd.google-apps.folder' and 'root' in parents" to search for a specific folder in the root that I know exists. It is also coming up empty.

I was expecting at least one result from the API call.

The file is not shared, but I am authenticating as myself. The scope is " 'https://www.googleapis.com/auth/drive.file',"


Solution

  • To list files you need more than the scope

    https://www.googleapis.com/auth/drive.file
    

    You also need to add the scope

    'https://www.googleapis.com/auth/drive.metadata.readonly'