Top 10 Google Drive API Python Solutions: A Comprehensive Guide

Jennie Lee
6 min readMar 27, 2024

--

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

Introduction to Google Drive API Python Integration

Google Drive API is a powerful tool provided by Google that allows developers to interact with Google Drive and perform various tasks programmatically. With the Google Drive API, you can create, retrieve, update, and delete files/folders, as well as perform other operations such as sharing and searching. In this tutorial, we will explore how to use Python to interact with Google Drive, specifically focusing on listing files, creating files, and creating folders.

Setting up the Project and Obtaining Credentials

Before we can start using the Google Drive API, we need to set up a project on the Google Cloud Dashboard and obtain the necessary credentials. Here are the steps to follow:

  1. Create a new project on the Google Cloud Dashboard.
  2. Give your project a name and click on the “Create” button. Your new project will be created.
  3. Enable the Google Drive API for your project. To do this:
  • Go to the “APIs & Services” section in the left navigation menu, and click on “Library”.
  • In the search bar, type “Google Drive API” and click on the result.
  • Click on the “Enable” button to enable the API for your project.
  1. Create credentials for your project. To do this:
  • Go back to the “APIs & Services” section and click on “Credentials”.
  • Click on the “Create credentials” button, and select “Service account” from the drop-down menu.
  • Fill in the required information, such as the service account name and role.
  • Click on the “Create” button to create the service account.
  • Once the service account is created, click on the “Done” button.
  1. Download the credentials file. To do this:
  • Locate your newly created service account in the “Service accounts” table, and click on the pencil icon to edit it.
  • Click on the “Keys” tab, and then click on the “Add key” button.
  • Select “JSON” as the key type and click on the “Create” button.
  • The JSON credentials file will be downloaded to your computer.
  1. Rename the downloaded JSON file to “credentials.json” and place it in your project directory.

Now that we have set up the project and obtained the necessary credentials, we can move on to creating and interacting with Google Drive files and folders using Python.

Creating and Sharing a Folder in Google Drive

Before we can start interacting with files in Google Drive, we need to create a folder to store them. Fortunately, creating a folder is a simple process. Here’s a step-by-step guide:

  1. Go to your Google Drive account on your web browser.
  2. Click on the “New” button on the left side of the screen.
  3. From the drop-down menu, select “Folder”. A new folder will be created with a default name.
  4. Rename the folder to a meaningful name that you can reference in your Python code.
  5. Once you have created the folder, go to the folder’s page and click on the “Share” button.
  6. In the “Share with people and groups” section, enter the email address of your service account.
  7. Set the access level to “Editor” and click on the “Send” button.
  8. The folder is now shared with the service account and ready to be accessed using the Google Drive API.

Importing Required Libraries and Setting Up Credentials

To interact with the Google Drive API using Python, we need to import the required libraries and set up the credentials. Here’s how:

  1. Open your Python IDE or editor and create a new Python script.
  2. Import the necessary libraries:
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google.oauth2 import service_account
  1. Set up the Google Drive credentials using the credentials.json file:
credentials = service_account.Credentials.from_service_account_file('credentials.json')
drive_service = build('drive', 'v3', credentials=credentials)

Make sure that the credentials.json file is in the same directory as your Python script.

Now that we have imported the required libraries and set up the credentials, we can move on to interacting with Google Drive using Python.

Interacting with Google Drive Using Python

In this section, we will cover the steps to create a new folder in Google Drive, upload a file to the folder, and list the files inside the folder. This will give you a good understanding of how to perform common operations using the Google Drive API.

  1. Specify the folder name and parent folder ID:
folder_name = 'My Python Folder'
parent_folder_id = 'Your_Folder_ID'

Replace 'Your_Folder_ID' with the ID of the folder you created in the previous section.

  1. Create a new folder using the create() method:
def create_folder(folder_name, parent_folder_id):
file_metadata = {
'name': folder_name,
'mimeType': 'application/vnd.google-apps.folder',
'parents': [parent_folder_id]
}
folder = drive_service.files().create(body=file_metadata, fields='id').execute()
print('Folder ID: %s' % folder.get('id'))

This function takes the folder name and parent folder ID as parameters. It creates a dictionary containing the metadata for the new folder, including the name, MIME type, and parent folder ID. It then calls the create() method of the files resource in the Drive service, passing in the file metadata. Finally, it prints the ID of the newly created folder.

  1. Upload a file to the folder using the create() method with metadata and media body:
def upload_file(file_name, file_path, folder_id):
file_metadata = {
'name': file_name,
'parents': [folder_id]
}
media = MediaFileUpload(file_path, resumable=True)
file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print('File ID: %s' % file.get('id'))

This function takes the file name, file path, and folder ID as parameters. It creates a dictionary containing the metadata for the file, including the name and parent folder ID. It then creates a MediaFileUpload object from the file path, which allows us to upload the file in chunks if necessary. Finally, it calls the create() method of the files resource in the Drive service, passing in the file metadata and media body. It prints the ID of the newly uploaded file.

  1. List the files inside the folder using the list() method with parent folder ID filtering:
def list_files(folder_id):
results = drive_service.files().list(q="'%s' in parents" % folder_id).execute()
files = results.get('files', [])

if not files:
print('No files found.')
else:
print('Files:')
for file in files:
print('- %s (%s)' % (file.get('name'), file.get('id')))

This function takes the folder ID as a parameter. It calls the list() method of the files resource in the Drive service, passing in a query string that filters the results to only include files with the specified folder ID as the parent. It then retrieves the list of files from the API response and prints the name and ID of each file. If there are no files in the folder, it prints a message indicating that no files were found.

To use the functions, simply call them with the appropriate parameters. For example:

create_folder('My Python Folder', 'Your_Folder_ID')
upload_file('Sample File.txt', 'path/to/file.txt', 'Your_Folder_ID')
list_files('Your_Folder_ID')

Make sure to replace 'Your_Folder_ID' with the ID of the folder you created in the previous section, and 'path/to/file.txt' with the actual path to the file you want to upload.

Conclusion and Additional Resources

In this tutorial, we have learned how to use Python to interact with Google Drive using the Google Drive API. We started by setting up the project and obtaining the necessary credentials. Then, we created a folder in Google Drive and shared it with the service account. Finally, we imported the required libraries, set up the credentials, and used Python to create a new folder, upload a file to the folder, and list the files inside the folder.

You can find the complete code for this tutorial on GitHub. The requirements.txt file contains the dependencies required to run the code. Feel free to explore the Google Drive API further and try out other operations such as updating and deleting files/folders.

Happy coding!

Looking for a Postman alternative?

Try APIDog, the Most Customizable Postman Alternative, where you can connect to thousands of APIs right now!

--

--

Jennie Lee
Jennie Lee

Written by Jennie Lee

Software Testing Blogger, #API Testing

No responses yet