How to use OAuth and API with Google API Client for python. This time, we will authenticate with Service Account, and API will target Calendar.
Explanation page about Google official authentication. Using OAuth 2.0 for Server to Server Applications
I will use this. google/google-api-python-client
Install with pip.
$ pip install --upgrade google-api-python-client
Google Developers Console
First, create a Service Account in the Google Developers Console.
Set the API permissions in the Administration Console.
oauth2client.client.AccessTokenRefreshError: access_denied: Requested client not authorized.
google_auth.py
import json
from httplib2 import Http
from oauth2client.client import SignedJwtAssertionCredentials
from googleapiclient.discovery import build
#Service account email address
client_email = '[email protected]'
#p12 version certification
fileName = "./project.p12"
with open(fileName, 'rb') as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key,
'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly'
,sub='[email protected]')
#json version certification
#fileName = "./project.json"
#json_key = json.load(open(fileName))
#credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'],
# 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly'
# ,sub='[email protected]')
http = Http()
credentials.authorize(http)
# Calendar API
from apiclient.discovery import build
calendar_service = build('calendar', 'v3', http=http)
calendar_list = calendar_service.calendarList().get(calendarId='[email protected]').execute()
print calendar_list['summary']
Execution result)
[email protected]
Notes)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/calendar/v3/users/me/calendarList/info%40example.com?alt=json returned "Not Found">
https://developers.google.com/api-client-library/python/auth/service-accounts?hl=ja
http://stackoverflow.com/questions/21407985/google-calendar-api-404-on-calendar-service-account
http://kb.cloudiway.com/errorunauthorized_client-descriptionunauthorized-client-or-scope-in-request-uri/
that's all.
Recommended Posts