Set Up Google Drive API Client in Python
- Begin by ensuring that you have the `google-api-python-client` installed. You can do this using the command `pip install google-api-python-client`, alongside `google-auth-httplib2` and `google-auth-oauthlib` for authentication purposes.
- Once the libraries are installed, load the necessary modules and set up authentication. Use OAuth 2.0 to authenticate and authorize the app with Google Drive by creating a `credentials.json` file which you download from the Google API Console.
- Set up the API service to interact with Google Drive by using the `build` function from `googleapiclient.discovery`, specifying the service name ('drive') and version ('v3').
from google.oauth2 import service_account
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = 'path_to_service_account.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)
List Files in Google Drive
- To list files, use the `files().list()` method available via the Drive API. You can filter by file type or other attributes by setting query parameters.
- Iterate through the response to retrieve files and file information such as name, id, and other metadata.
results = service.files().list(
pageSize=10, fields="nextPageToken, 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']})")
Upload Files to Google Drive
- To upload files, use the `files().create()` method. Specify the media to upload with `MediaFileUpload`, which takes the file path and MIME type as parameters.
- Set the `body` parameter to define file metadata like `name` and `parents` (to specify directory, if needed).
from googleapiclient.http import MediaFileUpload
file_metadata = {'name': 'my_document.txt'}
media = MediaFileUpload('files/my_document.txt', mimetype='text/plain')
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print(f"File ID: {file.get('id')}")
Download Files from Google Drive
- Downloading involves using `files().get_media()` after specifying the `fileId`. This retrieves the media contents from Drive.
- To save the file, you can use Python standard library's `io` and `open` functions to write the contents received.
from googleapiclient.http import MediaIoBaseDownload
import io
file_id = 'your_file_id_here'
request = service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print(f"Download {int(status.progress() * 100)}.")
with open('downloaded_file.txt', 'wb') as f:
fh.seek(0)
f.write(fh.read())
Delete Files from Google Drive
- To delete files, use the `files().delete()` method with the specified file ID. It's important to ensure that this action is intended because it is irreversible.
service.files().delete(fileId='your_file_id_here').execute()
print('File Deleted Successfully')
Handling Errors and Exceptions
- Use try-except blocks to catch exceptions such as `HttpError` while interacting with Google Drive API. This can help in logging and handling errors more gracefully.
- Implement logging to track the application’s behavior and catch potential points of failure.
from googleapiclient.errors import HttpError
try:
# Your API call here
pass
except HttpError as error:
print(f"An error occurred: {error}")