Skip to content

Use Service Account

Takahiro Ooishi edited this page Aug 12, 2024 · 2 revisions

https://github.com/taka0125/google_spreadsheet_fetcher/tree/main/samples/service_account

GCPプロジェクトを作成し、設定をする

1. Google Sheets API を有効にする

2. 認証情報 > 認証情報を作成 > サービスアカウント

3. サービスアカウント > 2で作ったアカウント > キー > 鍵を追加 > 新しい鍵を作成

4. JSONタイプを選び、作成

::GoogleSpreadsheetFetcher::Authorizer::ServiceAccount にこのファイルの内容を渡す

APIを実行する

sheet_key = 'example_sheet_id'

GoogleSpreadsheetFetcher.configure do |config|
  credential = Pathname.new('path_to_service_account_credential_file.json').read
  config.authorizer = ::GoogleSpreadsheetFetcher::Authorizer::ServiceAccount.new(credential)
  config.user_id = 'sample'
end

sheet_key = 'example_sheet_id'

fetcher = GoogleSpreadsheetFetcher::Fetcher.new(sheet_key, GoogleSpreadsheetFetcher.config.user_id)

pp fetcher.fetch_all_rows_by!(index: 0)