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?
Below I will show three examples of how to authenticate with ADC but first some prerequisities:
Service Usage Consumer
for the project in questiongcloud 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)