LoginSignup
5
3

More than 5 years have passed since last update.

G Suite Admin SDK / Google API Client Library for Pythonの使い方

Posted at

Google APIはドキュメントは多いけどよくわからんかったので使ったときのメモ。

前提

  • Pythonが使える
  • G Suiteのアカウントがユーザー管理の役割とかの強い権限を持っている

クイックスタート

Python Quickstart  |  Directory API  |  Google Developers
最初のサンプルコードもこれのステップを踏むだけでいい。とくに準備はいらない。ちゃんとやるのならDevelopers Consoleでプロジェクト作ってクレデンシャル作成とかしてもいい。

サービスというのはAPI Explorerで一覧になってるやつ。
Google APIs Explorer

URLの/admin/directory_v1/ に該当する部分を指定すればいい。

service = build('admin', 'directory_v1', credentials=creds)

  # Call the Admin SDK Directory API
  print('Getting the first 10 users in the domain')
  results = service.users().list(customer='my_customer', maxResults=10,
                orderBy='email').execute()
  users = results.get('users', [])

使い方の雰囲気はみればわかると思うけど、

  1. googleapiclient.discovery.buildからサービスを作成
  2. サービスから実行するリソースを取得
  3. リソースに対して実行するメソッドを指定してリクエストを作成
  4. リクエストに対してexecute()を実行してレスポンスを取得
  5. レスポンスはただのディクショナリになっているのであとは自由に

という感じ。

SCOPEの探し方

指定するスコープの一覧はここにある。
Directory API: Authorize Requests  |  Directory API  |  Google Developers

やりたい内容に合わせて複数指定していけばいい。

Web APIのリファレンス

リクエストとレスポンスの詳細をみたいときはこれをみるといい。
API Reference  |  Directory API  |  Google Developers

その場で試すのもできる。

Python APIのリファレンス

ここから辿れる。わりとしっかり書いてるので読めばだいたい解決する。
https://google-api-client-libraries.appspot.com/documentation/admin/directory_v1/python/latest/index.html

こまごまTips

ページング

ページング用にlist_nextが用意されている。使うとラク。自前でwhileとか再帰とか書かないでいい。
Pagination  |  API Client Library for Python  |  Google Developers

activities = service.activities()
request = activities.list(userId=someUserId, collection=public)

while request is not None:
 activities_doc = request.execute(http=http)

 # Do something with the activities

 request = activities.list_next(request, activities_doc)

バッチ処理

HTTPリクエストがいっかいで済む。エコ。
https://developers.google.com/api-client-library/python/guide/batch

更新系だけじゃなくて参照でも使える。

def insert_animal(request_id, response, exception):
 if exception is not None:
  # Do something with the exception
  pass
 else:
  # Do something with the response
  pass

service = build('farm', 'v2')

batch = service.new_batch_http_request(callback=insert_animal)

batch.add(service.animals().insert(name="sheep"))
batch.add(service.animals().insert(name="pig"))
batch.add(service.animals().insert(name="llama"))
batch.execute(http=http)
5
3
0

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
5
3