Here is the Python code to list all files from Google Drive using the Google Drive API:
# First, install the necessary packages using pip: # pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client from google.oauth2.credentials import Credentials from googleapiclient.discovery import build # Replace with your own credentials.json file creds = Credentials.from_authorized_user_file('credentials.json', ['https://www.googleapis.com/auth/drive']) # Create a Drive API client service = build('drive', 'v3', credentials=creds) # Call the Drive API to list all files results = service.files().list( pageSize=10, # number of files to retrieve per page fields="nextPageToken, files(id, name, mimeType)").execute() items = results.get('files', []) # Print the results if not items: print('No files found.') else: print('Files:') for item in items: print(f'{item["name"]} ({item["id"]}) - {item["mimeType"]}')
This code uses the google-auth
, google-auth-oauthlib
, google-auth-httplib2
, and google-api-python-client
packages to authenticate and interact with the Google Drive API. Replace the credentials.json
file with your own API credentials, which you can obtain from the Google Cloud Console. The code then calls the files().list()
method to retrieve a list of files and prints their names, IDs, and MIME types.