How to list the contents of a Google Drive folder by ID with the

ghz 昨天 ⋅ 1 views

How to list the contents of a Google Drive folder by ID with the V3 API Python client?

The official documentation here is not helping much on this topic. First of all it is an example on searching by mimeType, not by parent ID. And then I replaced the search term by the example in here and it still does not find anything. My code is below. Note that the function is named copy_folder just because I was actually trying to copy all files and sub-folders in a folder to a new folder and the first step is to get the contents of the source folder. And the source folder is in a team drive. The 'files' key in the response is just empty while in the folder I tested there are actually files and sub-folders.

def copy_folder(service, src, dst):
    """
    Copies a folder. It will create a new folder in dst with the same name as src,
    and copies the contents of src into the new folder
    src: Source folder's id
    dst: Destination folder's id that the source folder is going to be copied to
    """
    page_token = None
    while True:
        response = service.files().list(q="'%s' in parents" % src,
                                        supportsAllDrives=True,
                                        spaces='drive',
                                        fields='nextPageToken, files(id, name)',
                                        pageToken=page_token,
                                        ).execute()
        for file in response.get('files', []):
            # Process change
            print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break

Answer

The issue you're encountering with the empty response for files can be due to several reasons, especially related to how Google Drive API handles Team Drives. Here are a few things you can check:

1. Ensure API Access to Team Drives

For Team Drives, you need to explicitly enable access to files within those drives. You must set supportsAllDrives=True in the request, which you're already doing, but you also need to ensure the proper permissions and authentication scope are set up.

  • The OAuth 2.0 scope you need is https://www.googleapis.com/auth/drive (for full access) or https://www.googleapis.com/auth/drive.file (for file access).
  • Also, make sure your API client has access to the Team Drive.

2. Use corpora Parameter

For Team Drives, you should also specify the corpora parameter to make sure you're querying the correct location (the Team Drive). You need to set it to teamDrive.

Here's how you can modify the query:

def copy_folder(service, src, dst):
    """
    Copies a folder. It will create a new folder in dst with the same name as src,
    and copies the contents of src into the new folder
    src: Source folder's id
    dst: Destination folder's id that the source folder is going to be copied to
    """
    page_token = None
    while True:
        response = service.files().list(
            q="'%s' in parents" % src,
            supportsAllDrives=True,
            spaces='drive',
            corpora='teamDrive',  # Add this line to query within Team Drive
            driveId=src,  # You should also specify the driveId if you're using a Team Drive
            fields='nextPageToken, files(id, name)',
            pageToken=page_token
        ).execute()

        for file in response.get('files', []):
            # Process file
            print(f'Found file: {file.get("name")} ({file.get("id")})')

        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break

3. Use driveId (Team Drive-specific)

For Team Drives, you also need to specify the driveId of the Team Drive. This helps the API locate the files in the correct context.

You can pass the driveId when listing the files:

response = service.files().list(
    q="'%s' in parents" % src,
    supportsAllDrives=True,
    spaces='drive',
    corpora='teamDrive',  # specifies Team Drive
    driveId=src,  # This is the ID of the Team Drive
    fields='nextPageToken, files(id, name)',
    pageToken=page_token
).execute()

4. Handle Different Types of Files

Make sure that the folder you're trying to list actually contains files or sub-folders that the API can return. Sometimes the folder might have shared files that may not show up unless the proper access scope is granted.

5. Check the Folder ID

Verify that the src and dst are correct and correspond to the actual folders in the Team Drive. If there are any issues with the folder IDs, the API may not return the correct data.

6. Debugging

To debug further, you can log the response object to see if there are any additional fields or error messages that might help:

print(response)  # To inspect the entire response object

Example Flow for Creating a Folder

Here’s a basic approach to copy a folder structure from one Team Drive to another:

  1. List files and folders in the source folder (with driveId and corpora='teamDrive' settings).
  2. Create a corresponding folder in the destination drive.
  3. For each file/subfolder, copy it to the destination folder.

Let me know if you need more specific help with the copy process!