Reputation: 11
I'm trying to use service accounts to authenticate and create a Google Drive API client in Python. I have the JSON file containing the service account credentials. I need to get the folder names. However, when I run my code, I get an empty list although I have folders in the drive.
Note that my Google Drive is a "Shared With Me" drive. I am not the owner. And I added the service account email to the drive as a content manager. I can create folders using the API but I cannot get the folder names.
Here's my code:
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# Replace the values below with your own service account credentials and folder name
SERVICE_ACCOUNT_FILE = 'secret.json'
PARENT_FOLDER_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXXXX'
# Authenticate and create the Google Drive API client
creds = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)
service = build('drive', 'v3', credentials=creds)
# Call the Drive API to get all the folders under the specified parent folder that are not owned by the authenticated user and have been shared with the authenticated user
results = service.files().list(q="not 'me' in owners and '" + PARENT_FOLDER_ID + "' in parents and sharedWithMe = true", fields="nextPageToken, files(id, name)").execute()
folders = results.get('files', [])
# Print the names of all the folders
if not folders:
print('No folders found.')
else:
print('Folders:')
for folder in folders:
print(f'{folder["name"]} ({folder["id"]})')
I also tried with many different queries that I found from different StackOverFlow posts but none of them worked.
What could be causing this issue and how can I resolve it?
Any help would be appreciated. Thank you!
Edit
I tried asking ChatGPT to generate some random queries for the q parameter in the list() function. Then, I started trying them one-by-one. This one worked:
q = f"'{PARENT_FOLDER_ID}' in parents and mimeType='application/vnd.google-apps.folder'"
Upvotes: 1
Views: 1200
Reputation: 479
I'm under the impression that you are missing to add the parameters "supportAllDrives" and "includeItemsFromAllDrives", can you try to use this call instead? .--- Edit: It turned out I did the query wrong as well, adding the corrected version:
results = drive_service.files().list(supportsAllDrives=True, includeItemsFromAllDrives=True, q=f"parents in '{folder_id}' and trashed = false", fields = "nextPageToken, files(id, name)").execute()
Upvotes: 1