Intro
I was looking for Google Drive API access with Service Account authentication (ie. server to server communication without frequent user interaction). I always, ended up here https://developers.google.com/drive/api/v3/quickstart/python via search engines. So, I couldn't find suitable doc for Service Account access for Google Drive API.
How to access
I found a way to mix it with other tutorials.
Sharing with email
Service account json (credential.json) has an client_email. We should share the resources with this account, then only the Service Account access is possible.
The mix
I searched for "Google Service Account Getting started python".
# https://developers.google.com/drive/api/v3/quickstart/python
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-py
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
credentials = ServiceAccountCredentials.from_json_keyfile_name(
key_file_location, scopes=scopes)
# https://developers.google.com/drive/api/v3/quickstart/python
service = build('drive', 'v3', credentials=credentials)
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
Conclusion
I was able to figure out Google Drive API. I would like to thank Google for consistent terminology.
Remarks
This article is not bullet proof. Basically, get credential by following this tutorial https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/service-py. Now use that credential to https://developers.google.com/drive/api/v3/quickstart/python.
Top comments (2)
Hi Ajeeb,
I tried executing your script but its returning no value. Could you please elaborate "We should share the resources with this account, then only the Service Account access is possible."
Does that mean, we need to have a linked email account with the service account?
oauth2client is deprecated
Now you need something like:
from google.oauth2.service_account import Credentials
Credentials.from_service_account_file(key_file_location)