LoginSignup
22
32

More than 5 years have passed since last update.

Google API Client for python でのService Account OAuthとAPIの使い方

Posted at

0. はじめに

Google API Client for pythonでのOAuthとAPIの使い方について。
今回はService Accountでの認証で、APIはCalendarを対象とします。

Google公式の認証についての解説ページ。
Using OAuth 2.0 for Server to Server Applications

1. 下準備

Google API Clientの取得

こちらを使います。
google/google-api-python-client

pipでインストールします。

$ pip install --upgrade google-api-python-client

Google Developers Console

まず、Google Developers ConsoleでService Accountを作成します。

  1. プロジェクトを作成
  2. [APIと認証]→[API]でCalendarを有効化 ※OAuth同意画面の設定を行っておく
  3. [APIと認証]→[認証情報]→[認証情報を追加]→[サービスアカウント]→[p12]で作成し「~.p12]ファイルを保管しておく ※JSONでも可

管理コンソール

管理コンソールでAPIの権限設定を行います。

※サービスアカウント毎に設定を行わないとAPIを使った際に以下のようなエラーが発生しますので必ず設定してください。

oauth2client.client.AccessTokenRefreshError: access_denied: Requested client not authorized.
  1. [セキュリティ]→[もっと見る]→[詳細設定]→[APIクライアントアクセスを管理する]
  2. [クライアント名]にDevelopers Consoleで作成した「クライアントID」(.apps.googleusercontent.com)を入力 ※メールアドレスではないので注意
  3. [1 つ以上の API の範囲]に「https://www.googleapis.com/auth/calendar,https://www.googleapis.com/auth/calendar.readonly」を入力
  4. [承認]を押下

2. モジュールの作成

google_auth.py

import json

from httplib2 import Http

from oauth2client.client import SignedJwtAssertionCredentials
from googleapiclient.discovery import build

# サービスアカウントのメールアドレス
client_email = '999-xxx@developer.gserviceaccount.com'

# p12版の認証
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='info@example.com')

# json版の認証
#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='info@example.com')


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='info@example.com').execute()

print calendar_list['summary']

実行結果)

info@example.com

注意事項)

  1. SignedJwtAssertionCredentialsの引数にsub='メールアドレス'を設定しないと、以下のエラーが出てAPIにアクセスできません。
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/calendar/v3/users/me/calendarList/info%40example.com?alt=json returned "Not Found">

参考URL

  1. https://developers.google.com/api-client-library/python/auth/service-accounts?hl=ja

  2. http://stackoverflow.com/questions/21407985/google-calendar-api-404-on-calendar-service-account

  3. http://kb.cloudiway.com/errorunauthorized_client-descriptionunauthorized-client-or-scope-in-request-uri/

以上。

22
32
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
32