Last modified: Feb 01, 2026 By Alexander Williams
Python Google Drive API Guide for Beginners
Managing files in Google Drive can be tedious. The Python Google Drive API changes that. It lets you automate tasks with code.
You can upload files, search for documents, and manage permissions. This guide will show you how. We will start from scratch.
You will learn to set up the API and write useful scripts. This is a powerful skill for any developer. It saves time and reduces errors.
What is the Google Drive API?
The Google Drive API is a programming interface. It allows applications to interact with Google Drive. You can read, write, and update files.
It uses RESTful calls and OAuth 2.0 for security. With Python, you use a client library. This library handles the complex HTTP requests.
Automation is the main benefit. Think of backing up files or syncing data. The API makes these tasks simple and repeatable.
Prerequisites and Setup
You need a few things before starting. First, ensure you have Python installed. Version 3.7 or higher is recommended.
You also need a Google Cloud Platform (GCP) project. This is where you enable the API and get credentials. Let's walk through the steps.
Step 1: Create a GCP Project and Enable the API
Go to the Google Cloud Console. Create a new project or select an existing one.
Navigate to "APIs & Services" > "Library". Search for "Google Drive API". Click on it and press the "Enable" button.
Step 2: Create Credentials
Go to "APIs & Services" > "Credentials". Click "Create Credentials" and choose "OAuth client ID".
Select "Desktop app" as the application type. Give it a name like "Python Drive Client". Click "Create".
Download the JSON credentials file. Rename it to credentials.json. Save it in your project folder. Keep this file secret.
Step 3: Install the Required Python Library
Open your terminal or command prompt. Install the Google Client Library and OAuth toolkit. Use the pip package manager.
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
This installs everything you need. The main library is google-api-python-client. The others handle authentication.
Authenticating Your Application
Authentication is the first step in any script. You must prove your app has permission to access Drive. We use OAuth 2.0.
The process generates a token. This token is stored for future use. Here is a basic authentication script.
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os.path
# Define the permissions your app needs
SCOPES = ['https://www.googleapis.com/auth/drive.file']
def authenticate_drive():
creds = None
# The file token.json stores the user's access and refresh tokens
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
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)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
# Get authenticated credentials
credentials = authenticate_drive()
print("Authentication successful!")
Run this script. A browser window will open. Log in with your Google account. Grant the requested permissions.
A token.json file will be created. Your script uses this file next time. It won't ask for login again.
The SCOPES variable is crucial. It defines what your app can do. drive.file scope lets you access files you create or open.
Building the Drive Service
After authentication, you build a service object. This object is your gateway to the API. You use it to make all requests.
from googleapiclient.discovery import build
# Use the credentials to build the Drive service
service = build('drive', 'v3', credentials=credentials)
print("Drive service created.")
The build function creates the service. The arguments are the API name, version, and your credentials. Now you can call API methods.
Core API Operations with Python
Let's explore common tasks. We will upload a file, list files, and search for a file. These are the building blocks for automation.
Uploading a File to Google Drive
Use the create method to upload. You need to specify file metadata and the actual file data.
def upload_file(file_path, file_name, mime_type='text/plain'):
file_metadata = {'name': file_name}
media = MediaFileUpload(file_path, mimetype=mime_type)
file = service.files().create(
body=file_metadata,
media_body=media,
fields='id'
).execute()
print(f"File uploaded. ID: {file.get('id')}")
return file.get('id')
# Example: Upload a text file
from googleapiclient.http import MediaFileUpload
file_id = upload_file('sample.txt', 'MySampleFile.txt')
File uploaded. ID: 1AbCdEfGhIjKlMnOpQrStUvWxYz123456789
The function returns the file's unique ID. Store this ID if you need to update or delete the file later.
Listing Files in Your Drive
To see what's in your Drive, use the list method. It returns a paginated result.
def list_files(page_size=10):
results = service.files().list(
pageSize=page_size,
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']})")
list_files(5)
Files:
MySampleFile.txt (1AbCdEfGhIjKlMnOpQrStUvWxYz123456789)
Budget.xlsx (2ZyXwVuTsRqPoNmLkJiHgFeDcBa987654321)
This is a great way to get an overview. For more complex queries, you can use the q parameter to search.
Searching for a File by Name
Searching is a powerful feature. You