Search code examples
python-3.xgoogle-apigoogle-drive-apigoogle-api-python-clientservice-accounts

Google Drive API Python Service Account Example


Is it possible to authenticate against the Google Drive API using a Google Service Account, rather than an OAuth flow ?

The Python examples for Google Drive use OAuth - Google drive Python Quick start

However I can't find any Service Account examples.

The majority of the other Google APIs I use (Translate, Cloud Vision) do use Service Account however, so I'd like to deprecate my Google Drive OAuth code for consistency.


Solution

  • The best service account python example that i know of is the one for Google analytics

    It should be something like this.

    from apiclient.discovery import build
    from oauth2client.service_account import ServiceAccountCredentials
    
    
    SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
    KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
    VIEW_ID = '<REPLACE_WITH_VIEW_ID>'
    
    
    def initialize_drive():
      """Initializes an service object.
    
      Returns:
        An authorized service object.
      """
      creds = ServiceAccountCredentials.from_json_keyfile_name(
          KEY_FILE_LOCATION, SCOPES)
    
      # Build the service object.
      service = build('drive', 'v3', credentials=creds)
    
      return service
    

    Once you have the drive service you should be able to use the rest of the code you have from the other tutorial. Its just the auth method that is diffrent.

    Just remember to create service account credentials and not Oauth credentials.