Google Drive API is a powerful tool for integrating cloud storage with your applications. It allows developers to access and manipulate files and folders stored on Google Drive using APIs. In this blog, we will explore how to use the Google Drive API with Python.
Prerequisites
Before we begin, you will need the following:
- A Google account
- Python 3 installed on your machine
- A Google Cloud Platform (GCP) project with the Google Drive API enabled
- A JSON key file for your GCP project
Authentication
To use the Google Drive API, we need to authenticate our application. We can authenticate using either OAuth2 or a service account.
OAuth2
OAuth2 allows users to grant your application access to their Google Drive account. To authenticate using OAuth2, follow these steps:
- Install the
google-auth
andgoogle-auth-oauthlib
libraries:pip install google-auth google-auth-oauthlib
- In the GCP console, go to the Credentials page and create a new OAuth2 client ID.
- Download the client ID JSON file and save it in your project directory.
- Use the following code to authenticate:
from google.oauth2.credentials import Credentials creds = Credentials.from_authorized_user_file('client_secret.json', ['https://www.googleapis.com/auth/drive'])
This code reads the client ID JSON file and authorizes your application to access the Google Drive API.
Service Account
Service accounts are special accounts that can be used to authenticate an application without user interaction. To authenticate using a service account, follow these steps:
- Create a service account in the GCP console and download the JSON key file.
- Install the
google-auth
andgoogle-auth-oauthlib
libraries:pip install google-auth google-auth-oauthlib
- Use the following code to authenticate:
from google.oauth2.service_account import Credentials creds = Credentials.from_service_account_file('service_account.json')
This code reads the service account JSON file and authorizes your application to access the Google Drive API.
Uploading Files
To upload a file to Google Drive using Python and the Google Drive API, follow these steps:
- Create a
DriveService
object:from googleapiclient.discovery import build from googleapiclient.errors import HttpError service = build('drive', 'v3', credentials=creds)
- Create a file metadata object:
file_metadata = { 'name': 'My File' }
This metadata object specifies the name of the file we want to upload.
- Create a media object:
from googleapiclient.http import MediaFileUpload file_path = 'path/to/file' media = MediaFileUpload(file_path)
This media object specifies the file we want to upload.
- Use the
Files().create()
method to upload the file:
This code uploads the file and prints the file ID.file = service.files().create( body=file_metadata, media_body=media, fields='id' ).execute() print(f'File ID: {file.get("id")}')
Downloading Files
To download a file from Google Drive using Python and the Google Drive API, follow these steps:
- Get the file ID:
file_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
- Use the
Files().get()
method to download the file:import io file = service.files().get(fileId=file_id).execute() file_content = io.BytesIO() download_url = file.get('downloadUrl') if download_url: resp, content = service._http.request(download_url) if resp.status == 200: file_content.write(content) print('File downloaded successfully.') else: print('An error occurred while downloading the file.') else: print('The file does not have a download URL.')
This code downloads the file content and saves it to a
BytesIO
object.
Searching Files
To search for files on Google Drive using Python and the Google Drive API, follow these steps:
- Use the
Files().list()
method to search for files:
query = "name contains 'My File'" results = service.files().list(q=query, fields='files(id, name)').execute() items = results.get('files', []) if not items: print('No files found.') else: print('Files:') for item in items: print(f'{item["name"]} ({item["id"]})')
This code searches for files containing the phrase 'My File' in their name and prints the name and ID of each file found.
Deleting Files
To delete a file from Google Drive using Python and the Google Drive API, follow these steps:
- Get the file ID:
file_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
- Use the
Files().delete()
method to delete the file:
Use the Files().delete() method to delete the file:
This code deletes the file from Google Drive.
Conclusion
In this blog, we explored how to use the Google Drive API with Python to authenticate, upload, download, search for, and delete files. The Google Drive API offers powerful features for integrating cloud storage with your applications, and Python provides a convenient and easy-to-use interface for accessing these features. With the knowledge gained from this blog, you can begin building your own applications that leverage the power of the Google Drive API.