CRUD operations with Google Drive in Python using google-api-python-client

Codeptive Solutions
CodeptiveSolutions
Published in
5 min readApr 28, 2020

Hey Everyone! In this story, we will learn to integrate the google-api-python-client library in python for file operation with google drive like upload file, download file, get file details and delete the file.

🔧 Setup

  1. google-api-python-client library

We need to install the google-api-python-client library of the python for these CRUD operations.

pip install google-api-python-client

2. Google Service Account

We need a google service account for this and this is a reference to create a service account in the google developer console. After creating a service account we will get a JSON file like below and we will use this JSON file for the operations with google drive.

Sample JSON file of the google service account.

Service Account JSON File

For accessing any folder using this service account, we need to grant write access to service account email test-456@vernal-isotope-253109.iam.gserviceaccount.com from the service-account.json file.

So, I created a demo folder called “Google Drive Demo” and grant write access to it. Also for any operations, we need a google folder id of Google Drive Demo folder and that I copied from URL as highlighted in the below screenshot.

3. Enable Google Drive API

We need to enable drive API for a project of this service account. This is a reference link to enable google drive API.

So, Let’s start with an upload file operation.

🔼 UPLOAD FILE

In this section, we will create a function that will upload any files from local machine to Google Drive Demo folder of the drive.

This code will upload 4 different files in the Google Drive Demo folder. Make sure you replaced parent_folder_id with your Google Drive Folder Id. Below is the output of the above code.

Console output:

{'kind': 'drive#file', 'id': '1CLrXti7-sFYQ7jeAkbJIiFwi3RmLNRXH', 'name': 'google-logo.jpg', 'mimeType': 'image/jpeg'}
{'kind': 'drive#file', 'id': '1HVom1UX6RZU0wqZM-pYfDshvhEWz2Ifm', 'name': 'download.png', 'mimeType': 'image/png'}
{'kind': 'drive#file', 'id': '1ePZiPxNN0z3qNOXPFT4GHDW-4CPQEEa2', 'name': 'sample.pdf', 'mimeType': 'application/pdf'}
{'kind': 'drive#file', 'id': '18TU2hENa4bKi3HSXUllcSca3swC3OXMw', 'name': 'file-sample_100kB.doc', 'mimeType': 'application/msword'}
Uploaded files to Google Drive Demo folder

⬇️ DOWNLOAD FILE

In this section, We will download files that were uploaded from the above code. We need google file id to download the file and we can get it from a shareable link of google document.

Get shareable link

The link will look like this https://drive.google.com/open?id=1HVom1UX6RZU0wqZM-pYfDshvhEWz2Ifm.

The download_file() of the code will take the below parameters.

  1. Id of the google file and we can get that from the above shareable link.
  2. Local folder path to save the downloaded files.

The above code will download all uploaded files. Make sure you replaced parent_folder_id with your Google Drive Folder Id.

Console output:

Download 100%.
Download 100%.
Download 100%.
Download 100%.
Downloaded files

📔 GET FILE DETAILS

In this section, we will fetch details of the uploaded files.

This code will print details of the file. The fields parameter is passed to get specific fields in the response. Make sure you replaced parent_folder_id with your Google Drive Folder Id.

Console output with different fields value:

fields = None

{'kind': 'drive#file', 'id': '1CLrXti7-sFYQ7jeAkbJIiFwi3RmLNRXH', 'name': 'google-logo.jpg', 'mimeType': 'image/jpeg'}

fields = “id,name,mimeType,webViewLink,createdTime,modifiedTime, size”

{'id': '1CLrXti7-sFYQ7jeAkbJIiFwi3RmLNRXH', 'name': 'google-logo.jpg', 'mimeType': 'image/jpeg', 'webViewLink': 'https://drive.google.com/file/d/1CLrXti7-sFYQ7jeAkbJIiFwi3RmLNRXH/view?usp=drivesdk', 'createdTime': '2019-12-03T07:55:14.663Z', 'modifiedTime': '2019-12-03T08:25:22.628Z', 'size': '28031'}

fields = “*”

{'kind': 'drive#file', 'id': '', 'name': 'google-logo.jpg', 'mimeType': 'image/jpeg', 'starred': False, 'trashed': False, 'explicitlyTrashed': False, 'parents': [''], 'spaces': ['drive'], 'version': '3', 'webContentLink': '', 'webViewLink': '', 'iconLink': '', 'hasThumbnail': True, 'thumbnailLink': '', 'thumbnailVersion': '1', 'viewedByMe': False, 'createdTime': '2019-12-03T07:55:14.663Z', 'modifiedTime': '2019-12-03T08:25:22.628Z', 'modifiedByMeTime': '2019-12-03T07:55:14.663Z', 'modifiedByMe': True, 'owners': [{'kind': 'drive#user', 'displayName': 'test-456@vernal-isotope-253109.iam.gserviceaccount.com', 'me': True, 'permissionId': '', 'emailAddress': 'test-456@vernal-isotope-253109.iam.gserviceaccount.com'}], 'lastModifyingUser': {'kind': 'drive#user', 'displayName': '', 'photoLink': '', 'me': False, 'permissionId': '', 'emailAddress': '<email>'}, 'shared': True, 'ownedByMe': True, 'capabilities': {'canAddChildren': False, 'canChangeCopyRequiresWriterPermission': True, 'canChangeViewersCanCopyContent': True, 'canComment': True, 'canCopy': True, 'canDelete': True, 'canDownload': True, 'canEdit': True, 'canListChildren': False, 'canModifyContent': True, 'canMoveItemIntoTeamDrive': True, 'canMoveItemOutOfDrive': True, 'canReadRevisions': True, 'canRemoveChildren': False, 'canRename': True, 'canShare': True, 'canTrash': True, 'canUntrash': True}, 'viewersCanCopyContent': True, 'copyRequiresWriterPermission': False, 'writersCanShare': True, 'permissions': [{'kind': 'drive#permission', 'id': '', 'type': 'user', 'emailAddress': '<email>', 'role': 'writer', 'displayName': '', 'photoLink': '', 'deleted': False}, {'kind': 'drive#permission', 'id': 'anyoneWithLink', 'type': 'anyone', 'role': 'reader', 'allowFileDiscovery': False}, {'kind': 'drive#permission', 'id': '', 'type': 'user', 'emailAddress': 'test-456@vernal-isotope-253109.iam.gserviceaccount.com', 'role': 'owner', 'displayName': 'test-456@vernal-isotope-253109.iam.gserviceaccount.com', 'deleted': False}], 'permissionIds': ['', 'anyoneWithLink', ''], 'originalFilename': 'google-logo.jpg', 'fullFileExtension': 'jpg', 'fileExtension': 'jpg', 'md5Checksum': '664c8a61ad7d772f0a7198f9274f5cf9', 'size': '28031', 'quotaBytesUsed': '28031', 'headRevisionId': '', 'imageMediaMetadata': {'width': 820, 'height': 475, 'rotation': 0}, 'isAppAuthorized': True}

❎ DELETE FILE

In this section, we will delete file from Google Drive Demo folder.

This code will delete the download.png file. Make sure you replaced parent_folder_id with your Google Drive Folder Id.

Console output:

File deleted successfully.
download.png deleted from the Google Drive Demo folder

That’s it for this one. Thank you for reading this ❤️

If you find this post useful, press👏 button as many times as you can and share this post with others. You can leave your feedback/suggestions in the comments 💬 below. For future posts of this series, you can follow me on medium to receive post updates. 🔔

Would you like to check out other useful articles?

--

--