If you need to upload a file to Google Drive using the API for free, it’s possible. There are multiple ways to achieve this, and in this blog, I will explain one approach: using a Google Service Account. This method can also be employed for backend server-based applications.

Introduction:
In today’s digital age, managing and sharing files efficiently is crucial. Google Drive offers a powerful solution, and with the Google Drive API in Python, you can automate file uploads for various applications. In this guide, we’ll walk you through the steps to get started with the Google Drive API, from setting up a service account to uploading files seamlessly.
Table of Contents:
- Understanding the Google Drive API
- Briefly explain what the Google Drive API is and its advantages.
- Setting Up Your Environment
- How to install the required packages (google-auth and google-api-python-client) using pip.
- Creating a Google Service Account
- Step-by-step instructions on how to create a Google Service Account, including project selection and service account details.
- Granting Permissions
- Explaining how to grant necessary permissions to the service account, with an emphasis on selecting the appropriate role (e.g., admin).
- Generating API Key
- Detailed steps on generating an API key in JSON format, which will be used for authentication.
- Enabling Google Drive API
- How to navigate to the Google Cloud Console and enable the Google Drive API for your project.
- Writing Python Code
- Providing sample Python code snippets to demonstrate how to use the Google Drive API for file uploads.
- Uploading Your First File
- A step-by-step guide to uploading a file to Google Drive using the API.
- Handling Errors
- Tips on handling common errors and troubleshooting issues.
- Conclusion
- Recap the key takeaways and the benefits of using the Google Drive API for file uploads.
- Recap the key takeaways and the benefits of using the Google Drive API for file uploads.
First, we need to install the required packages: google-auth==2.22.0
and google-api-python-client==2.97.0
. You can use the following pip command:
pip install google-auth==2.22.0 google-api-python-client==2.97.0
Next you need to create the service account
you can refer https://developers.google.com/identity/protocols/oauth2/service-account#creatinganaccount or follow bellow steps
Step 1: Go to https://console.developers.google.com/iam-admin/serviceaccounts.

Step 2: If you already have a project, select it; otherwise, create a new project.
Step 3: Click on “Create Service Account.”

Step 4: Fill in the details in the “Service Account Details” tab and click “Create and Continue.”

Step 5: In the “Grant This Service Account Access to Project” tab, select the role as “Admin” and click “Continue.”

Step 6: Click “Done” and leave the other settings as default.

Step 7: You have now created an account. Click on the account and go to the “Key” tab.

Step 8: Click “Add Key,” create a new key, select it as a JSON file, and download the JSON file. Save the file.

Step 9: Go to the API section at https://console.cloud.google.com/apis/library and select and enable the Google Drive API for your project.

Next we move on to coding
import os
from google.oauth2 import service_account
from googleapiclient.discovery import build
# Define the Google Drive API scopes and service account file path
SCOPES = ['https://www.googleapis.com/auth/drive']
SERVICE_ACCOUNT_FILE = "/file/path/of/json/file.json"
# Create credentials using the service account file
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# Build the Google Drive service
drive_service = build('drive', 'v3', credentials=credentials)
def create_folder(folder_name, parent_folder_id=None):
"""Create a folder in Google Drive and return its ID."""
folder_metadata = {
'name': folder_name,
"mimeType": "application/vnd.google-apps.folder",
'parents': [parent_folder_id] if parent_folder_id else []
}
created_folder = drive_service.files().create(
body=folder_metadata,
fields='id'
).execute()
print(f'Created Folder ID: {created_folder["id"]}')
return created_folder["id"]
def list_folder(parent_folder_id=None, delete=False):
"""List folders and files in Google Drive."""
results = drive_service.files().list(
q=f"'{parent_folder_id}' in parents and trashed=false" if parent_folder_id else None,
pageSize=1000,
fields="nextPageToken, files(id, name, mimeType)"
).execute()
items = results.get('files', [])
if not items:
print("No folders or files found in Google Drive.")
else:
print("Folders and files in Google Drive:")
for item in items:
print(f"Name: {item['name']}, ID: {item['id']}, Type: {item['mimeType']}")
if delete:
delete_files(item['id'])
def delete_files(file_or_folder_id):
"""Delete a file or folder in Google Drive by ID."""
try:
drive_service.files().delete(fileId=file_or_folder_id).execute()
print(f"Successfully deleted file/folder with ID: {file_or_folder_id}")
except Exception as e:
print(f"Error deleting file/folder with ID: {file_or_folder_id}")
print(f"Error details: {str(e)}")
def download_file(file_id, destination_path):
"""Download a file from Google Drive by its ID."""
request = drive_service.files().get_media(fileId=file_id)
fh = io.FileIO(destination_path, mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while not done:
status, done = downloader.next_chunk()
print(f"Download {int(status.progress() * 100)}%.")
if __name__ == '__main__':
# Example usage:
# Create a new folder
# create_folder("MyNewFolder")
# List folders and files
# list_folder()
# Delete a file or folder by ID
# delete_files("your_file_or_folder_id")
# Download a file by its ID
# download_file("your_file_id", "destination_path/file_name.extension")
Code for uploading
Special thanks to Md Mahmudul Huq Topu How share this code in chat
Check out my GitHub at ragug for more resources and examples that might help you in your projects.
Happy coding !