Skip to content Skip to sidebar Skip to footer

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 dri

Solution 1:

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>'definitialize_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.

Solution 2:

You can use Credentials oauth2 object using the following,

import json
from google.oauth2.service_account import Credentials

SCOPES = ['https://www.googleapis.com/auth/drive']

service_account_info = json.load(open('service_account.json'))
creds=Credentials.from_service_account_info(
    service_account_info, scopes=SCOPES)

drive_service = build('drive', 'v3', credentials=creds)

Post a Comment for "Google Drive Api Python Service Account Example"