I'm using the Google Drive API to try to answer a seemingly simple question: does a folder by a certain name exist in a drive?
Specifics:
googleapiclient
Example:
Given the enclosing drive ID abcdef
, does the folder with name June 2019
(and mimeType application/vnd.google-apps.folder
) exist?
Current route:
>>> from googleapiclient.discovery import build
>>> # ... build credentials
>>> driveservice = build("drive", "v3", credentials=cred).files()
>>> [i for i in driveservice.list().execute()['files'] if
... i['name'] == 'June 2019' and i['mimeType'] == 'application/vnd.google-apps.folder']
[{'kind': 'drive#file',
'id': '1P1k5c2...........',
'name': 'June 2019',
'mimeType': 'application/vnd.google-apps.folder'}]
So the answer is yes, the folder exists. But there should be a more efficient way to do this via .list()
by passing the driveId
. How can that be done? I've tried various combinations all of which seem to throw a non-200 response.
>>> FOLDER_ID = "abcdef........"
>>> driveservice.list(corpora="drive", driveId=FOLDER_ID).execute()
# 403 response, even when adding the additional requested params
How can I use the q
param to query by folder name?
When using driveId
and corpora="drive"
, you need to provide two more parameters: includeItemsFromAllDrives
and supportsAllDrives
Code:
response = driveservice.list(
q="name='June 2019' and mimeType='application/vnd.google-apps.folder'",
driveId='abcdef',
corpora='drive',
includeItemsFromAllDrives=True,
supportsAllDrives=True
).execute()
for item in response.get('files', []):
# process found item
Update:
If it's a drive id you're sure exists and you keep getting "Shared drive not found" error, it might be a scope problem with credentials you've aquired for the api. Also according to these Google API documents there seems to a lot of changes and deprecations happening, all related to the shared drives api support. https://developers.google.com/drive/api/v3/enable-shareddrives https://developers.google.com/drive/api/v3/reference/files/list
If you keep having these problems, here's alternative solution for you using the spaces
parameter:
response = driveservice.list(
q="name='June 2019' and mimeType='application/vnd.google-apps.folder'",
spaces='drive'
).execute()
for item in response.get('files', []):
# process matched item
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With