Skip to content

Instantly share code, notes, and snippets.

@prasathmani
Last active July 9, 2025 01:10
Show Gist options
  • Save prasathmani/5d78a6126c3e1920ffb6fd591a759edb to your computer and use it in GitHub Desktop.
Save prasathmani/5d78a6126c3e1920ffb6fd591a759edb to your computer and use it in GitHub Desktop.
upload files to google drive using python
import requests
import json
from typing import Dict
# ==== CONFIGURATION ====
CLIENT_ID = '####'
CLIENT_SECRET = '####'
REFRESH_TOKEN = '####'
FOLDER_ID = '####'
UPLOAD_FILE = 'my-upload-test.zip' # Change this to your file
# ==== CONSTANTS ====
TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token'
UPLOAD_URL = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart'
def get_access_token(client_id: str, client_secret: str, refresh_token: str) -> str:
"""Retrieve a new access token using the refresh token."""
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {
'grant_type': 'refresh_token',
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token,
}
response = requests.post(TOKEN_URL, headers=headers, data=data)
if response.status_code != 200:
raise Exception(f"Failed to get access token: {response.text}")
token_info = response.json()
return token_info.get('access_token')
def create_multipart_payload(file_path: str, folder_id: str) -> Dict:
"""Prepare metadata and file content for the upload."""
file_name = file_path.split('/')[-1]
metadata = {
'name': file_name,
'parents': [folder_id]
}
mime_type = 'application/zip' # Adjust this if uploading another file type
with open(file_path, 'rb') as f:
files = {
'data': ('metadata', json.dumps(metadata), 'application/json; charset=UTF-8'),
'file': (file_name, f, mime_type)
}
return files.copy() # copy for safe use outside 'with' block
def upload_to_drive(access_token: str, files: Dict) -> None:
"""Upload a file to Google Drive."""
headers = {
'Authorization': f'Bearer {access_token}'
}
response = requests.post(UPLOAD_URL, headers=headers, files=files)
if response.status_code not in [200, 201]:
raise Exception(f"Failed to upload file: {response.text}")
print("Upload successful!")
print("Response:", response.json())
def main():
try:
access_token = get_access_token(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN)
files = create_multipart_payload(UPLOAD_FILE, FOLDER_ID)
upload_to_drive(access_token, files)
except Exception as e:
print(f"Error: {e}")
if __name__ == '__main__':
main()
@ab9801
Copy link

ab9801 commented Mar 23, 2023

Awesome, was very useful for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment