google-drive-api

Google Drive API not listing files in folder despite files existing


I’m trying to list all the file IDs in a specific folder in Google Drive using the Drive API.

First, I find the folder ID like this:

import requests

headers = {
    "Authorization": GCP_ACCESS_TOKEN,
    "Content-Type": "application/json"
}

# Find a folder's ID
parent_folder_id = "12345"
folder_name = "photos"
query = f"name='{folder_name}' and '{parent_folder_id}' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false"
params = {
    "q": query,
    "fields": 'files(id)'
}

response = requests.get("https://www.googleapis.com/drive/v3/files", headers=headers, params=params)
print(response.json())

This returns:

{'files': [{'id': "6789"}]}

Now, I’m trying to get all file IDs in that folder:

folder_id = "6789"
query = f"'{parent_folder_id}' in parents and mimeType='application/vnd.google-apps.file' and trashed=false"
params = {
    "q": query,
    "fields": 'files(id)'
}

response = requests.get("https://www.googleapis.com/drive/v3/files", headers=headers, params=params)
print(response.json())

But this returns:

{"files": []}

It’s weird because this folder has two files. I’m not sure what’s happening.

What am I doing wrong? How can I correctly list all the file IDs in a folder?

Additional Information:

•   I’m using Python and the requests library.
•   The folder definitely contains two files.
•   The authorization token is valid and working, as I can retrieve other data.

Solution

  • Modification points:

    If you want to retrieve only the files except for the folders just under the folder parent_folder_id, how about the following modification?

    From:

    query = f"'{parent_folder_id}' in parents and mimeType='application/vnd.google-apps.file' and trashed=false"
    

    To:

    query = f"'{parent_folder_id}' in parents and mimeType!='application/vnd.google-apps.folder' and trashed=false"
    

    Reference: