dokichan
dokichan

Reputation: 591

How to get all user's files on Google Drive using Google API Python SDK?

I have this Python code, that shows all files from Google Drive:

files = []
page_token = None
while True:
    response = service.files().list(spaces='drive',
                                    fields='nextPageToken, '
                                           'files(id, name)',
                                    pageToken=page_token).execute()
    for file in response.get('files', []):
        print(F'Found file: {file.get("name")}, {file.get("id")}')
    files.extend(response.get('files', []))
    page_token = response.get('nextPageToken', None)
    if page_token is None:
        break

The problem is, it shows only files of mine. What I want to do, is, being administrator of my organization, list all files of other user. Is it possible to do? And if it is, how can I modify the code above in order to obtain that?

Upvotes: 1

Views: 865

Answers (1)

Impersonating users in your organization

You would need to create a service account for your project in the API Console. If you want to access user data for users in your Google Workspace account, then delegate domain-wide access to the service account you can review the steps here: Using Service Accounts.

Once you create a service account in a GCP project (console.developers.google.com), enable DWD (domain-wide delegation), then authorize that service account in your G Suite admin console, that key can then be used to "impersonate" any account in the G Suite instance:

Create the credentials object from the JSON file

from oauth2client.service_account import ServiceAccountCredentials

scopes = ['https://www.googleapis.com/auth/drive.metadata.readonly']

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    '/path/to/keyfile.json', scopes=scopes)

Starting the impersonation process for [email protected]

delegated_credentials = credentials.create_delegated('[email protected]')

Make sure to also follow the steps from the official documentation on how to add the domain wide delegation in the Admin console.

Once you have this set up, you should be able to call the Google API from Drive and run the same code to gather the Drive files under the impersonation of any user from the organization.

References:

Upvotes: 1

Related Questions