LoginSignup
0
0

More than 1 year has passed since last update.

GoogleAPIの使用について

Posted at

GoogleAPIの使用についてちょっと嵌ったところがあったのでメモ書きと簡単なコードを紹介します。

目的

  • 同じような問題で詰まっている方がいれば解決方法をシェアしてハッピーになってもらえればと
  • GoogleAPIってどんなことが出来るの?が少しでもシェアできればと

それでは

GoogleAPIの説明やサービスアカウント等の話は省きます。
ドキュメント読めば書いてあるのでドキュメント読んでください。

本記事では、GoogleWorkSpaceの特定ユーザーがメンバーとなっているGroupを一覧化する方法を紹介します。

嵌ったこと

ドキュメント通りにGCPでProjectを立ち上げ、サービスアカウントを作成、鍵(JSON)をダウンロードしてコードを実行したのですがうまくいかず、認可されていないとのエラーに悩んでました。

message': 'Not Authorized to access this resource/api

結論
GoogleWorkSpace管理上でロールを割り当ててなかったことが原因でした。

ロールを作成して、今回はグループ操作をしたので、グループのみに権限を与え(チェックを入れ)、サービスアカウントに割り当てて解決

image.png

サンプルコード

qiita.py
#Googleクライアントライブラリ
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials

SECRETS = '[秘密鍵].json'

SCOPES = ['https://www.googleapis.com/auth/admin.directory.group']

def Get_GoogleGroup():
    #クレデンシャルインスタンスの作成
    credentials = Credentials.from_service_account_file(SECRETS)

    #スコープの追加
    scoped_credentials = credentials.with_scopes(SCOPES)

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

    results = service.groups().list(domain='hoge.com', userKey='test@hoge.com').execute()

    results = results['groups']

    groups = []

    for i in range(len(results)):
          groups.append(results[i]['email'])

    print(groups)

0
0
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
0
0