Google Drive offers a RESTful API that enables developers to interact with files stored in the cloud. In this guide, you'll learn how to upload files to Google Drive using Python and the Google Drive API.
1. Setup
First, install the required Google client libraries:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
2. Enable the Google Drive API
Follow these steps to enable the API and obtain credentials:
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Enable the Google Drive API under "APIs & Services".
- Go to "Credentials" and create an OAuth 2.0 client ID.
- Download the
credentials.json
file and place it in your project directory.
3. Authenticate and Build the Drive Service
Use the following Python code to authenticate the user and build the Drive service object:
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
import os.path
SCOPES = ['https://www.googleapis.com/auth/drive.file']
def authenticate():
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.json', 'w') as token:
token.write(creds.to_json())
return build('drive', 'v3', credentials=creds)
4. Upload a File
Once authenticated, you can upload a file like this:
from googleapiclient.http import MediaFileUpload
def upload_file(service, file_path, mime_type='application/octet-stream'):
file_metadata = {'name': os.path.basename(file_path)}
media = MediaFileUpload(file_path, mimetype=mime_type)
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print(f'File uploaded with ID: {file.get("id")}')
# Example usage
if __name__ == '__main__':
service = authenticate()
upload_file(service, 'example.txt')
Conclusion
Uploading files to Google Drive with Python is straightforward using the Google Drive API and official client libraries. Always remember to handle user credentials securely and limit OAuth scopes to the minimum required.