3
votes

I have the following service account json credentials file for a Google Cloud Platform project:

enter image description here

How would I authenticate to Google Drive API using this service account? For example, when I try doing the following:

from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'

flow = client.flow_from_clientsecrets('mykey.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))

results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])

I get an error when running the flow command that complains about the format of the keyfile not starting with web or installed:

Invalid file format. See https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
Expected a JSON object with a single property for a "web" or "installed" application 

Is there a way to use the above key to list my Drive files for my Google Service Account? If so, how would this be done?

2

2 Answers

2
votes

For using service account credentials, the ServiceAccountCredentials library should be imported from oauth2client.service_account and used as below:

# The needed import for service account credentials:
from oauth2client.service_account import ServiceAccountCredentials

from apiclient.discovery import build

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

# Parsing JSON credentials for a service account:
credentials = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)

service = build('drive', 'v3', credentials=credentials)

Then, use service as regular, e.g. service.files() etc.

-2
votes

You can go to the following Python Quickstart for Drive page and click "Enable the Drive API" button. This will allow you to download credentials that are of the format the following line excepts:

flow = client.flow_from_clientsecrets('mykey.json', SCOPES)