Lets say you need to run a script locally that needs to connect to google workspace resources like drive and sheets. How do you do this from Python leveraging Google Application Default Credentials?
2 Answers
Below I will show three examples of how to authenticate with ADC but first some prerequisities:
- Have a google cloud project and enable google drive API
- To be able to do google ADC login you need the GCP role:
Service Usage Consumerfor the project in question - Install gcloud cli
- To access google drive APIs, you need to perform the login explicitly passing scope for the drive API:
gcloud auth application-default login --scopes=https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/drive- for some reason official docs doesn't mention this.
At this point your local machine is set up to act as you using ADC. But how do we use ADC from popular Python libraries. Well, here are three code examples:
Using modern python google auth library and googleapiclient:
from googleapiclient.discovery import build
from google.auth import default
# Define the scopes required for accessing Google Drive
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
# Get the default credentials for the environment
creds, _ = default(scopes=SCOPES)
# Build the Google Drive API client
service = build('drive', 'v3', credentials=creds)
Second example is google sheets api service pygsheets:
import pygsheets
from google.auth import default
# Define the scopes required for accessing Google Drive
SCOPES = ['https://www.googleapis.com/auth/drive']
# Get the default credentials for the environment
creds, _ = default(scopes=SCOPES)
gc = pygsheets.authorize(custom_credentials=creds)
Third example which you probably shouldn't use because it's very old and unmaintained but adding it here since I also needed to figure this out, here is how to do it with PyDrive:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth() # Seems to automagically load gcp ADC
drive = GoogleDrive(gauth)
Comments
The above answer is correct. However, to allow the service account to access your Google Drive files, you must explicitly share the folder or files with the service account's email address.
Your service account email follows this format
To grant access:
Go to Google Drive and locate the folder or file you want to share.
Right-click → Share and enter the service account’s email address.
Assign the required permissions (Viewer, Editor, etc.) based on your needs.
This step is necessary because service accounts do not have default access to personal Google Drive files. They must be treated as external users and explicitly granted permissions. Once shared, the API requests from your service account will work as expected.