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.
In your showing script, it seems that the following search queries are used.
In order to retrieve all folders just under a folder, the following search query is used.
query = f"name='{folder_name}' and '{parent_folder_id}' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false"
parent_folder_id
are retrieved. I thought that in this case, name='{folder_name}'
might not be required to be used. Because all folders and files are managed by unique IDs in Google Drive. When you know the ID, it can be directly used.In order to retrieve all files just under a folder, the following search query is used.
query = f"'{parent_folder_id}' in parents and mimeType='application/vnd.google-apps.file' and trashed=false"
In this case, the files of the mimeType of application/vnd.google-apps.file
just under a folder parent_folder_id
. are retrieved. I guessed that this might be the reason for your current issue.
If you want to retrieve only the files except for the folders just under the folder parent_folder_id
, how about the following modification?
query = f"'{parent_folder_id}' in parents and mimeType='application/vnd.google-apps.file' and trashed=false"
query = f"'{parent_folder_id}' in parents and mimeType!='application/vnd.google-apps.folder' and trashed=false"
parent_folder_id
are retrieved.