pythongoogle-sheetsgoogle-drive-api

How to use Google Cloud ADC to access Google Drive API from Python with personal account (not service account)


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?


Solution

  • Below I will show three examples of how to authenticate with ADC but first some prerequisities:

    1. Have a google cloud project and enable google drive API
    2. To be able to do google ADC login you need the GCP role: Service Usage Consumer for the project in question
    3. Install gcloud cli
    4. 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)