LoginSignup
33
39

More than 5 years have passed since last update.

RubyでOAuth認証なしにGoogleSpreadSheetのデータを取得

Last updated at Posted at 2016-04-20

はじめに

Google DriveのスプレッドシートにRubyでアクセスする方法のようにRubyでスプレッドシートを取得する方法はあるのですが、
OAuthを利用したものであるため、手動でcurlやwebで認証しcodeを取得する必要があります。
そのため、cronなどで定期的に処理するといった自動化ができません。

そこでOAuthを使わずにスプレッドシートにアクセスする方法として、サービスアカウントを使ったアクセス方法を紹介します。

追記

なお、 google_drive の作者である @gimite さんのコメントからいただいたとおり、google_drive 2.1.0 以降では、GoogleDrive::Session.from_service_account_key を使うことで json ファイルを使っての認証が行いやすくなっております。

新しい導入手順も https://github.com/gimite/google-drive-ruby/blob/master/doc/authorization.md にて公開されていますので、そちらを参考にしてください。

動作環境

名前 バージョン
Ruby 2.1.0
google_drive 1.0.6

前準備

サービスアカウントの作成

まずは、Google API Consoleから認証情報を選択。

1.png

そして、認証情報作成からサービスアカウントキーを選択します。

2.png

サービスアカウント名などを入力し、アカウントを作成します。
このとき保存形式には、JSONを指定しましょう。

3.png

作成完了すると、以下のダイアログと同時にJSONファイルがダウンロードされます。

4.png

なお、作成したJSONは以下の様な内容になっています。

{
  "type": "service_account",
  "project_id": "project_id",
  "private_key_id": "***",
  "private_key": "***",
  "client_email": "***@***.iam.gserviceaccount.com",
  "client_id": "***",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/***.iam.gserviceaccount.com"
}

スプレッドシートに編集/閲覧権限を付与

アカウントを作成したので、対象となるスプレッドシートに権限を付与します。
対象のスプレッドシートを右クリックし、共有を選択します。

6.png

JSONに記載されたclient_emailに編集あるいは閲覧権限を付与します。
通知の必要はないので、チェックボックスは外しておきましょう。

7.png

実際の取得処理

ここまで準備できたら、あとはコードを書くのみです。

取得の方法としては、以下のようになります。
SHEET_IDには、参照するSpreadSheetのidを、AUTH_JSONには、ダウンロードしたjsonのファイルパスを指定してください。

require 'bundler/setup'
require 'google_drive'

require 'json'

sheet_id = ENV['SHEET_ID']
json_file = ENV['AUTH_JSON']

options = JSON.parse(File.read(json_file))
key = OpenSSL::PKey::RSA.new(options['private_key'])

auth = Signet::OAuth2::Client.new(
  token_credential_uri: options['token_uri'],
  audience: options['token_uri'],
  scope: %w(
    https://www.googleapis.com/auth/drive
    https://docs.google.com/feeds/
    https://docs.googleusercontent.com/
    https://spreadsheets.google.com/feeds/
  ),
  issuer: options['client_email'],
  signing_key: key
)
auth.fetch_access_token!

# スプレッドシートの取得
session = GoogleDrive.login_with_oauth(auth.access_token)
ws = session.spreadsheet_by_key(sheet_id).worksheets[0]

# 整形処理 & 表示
table = (1..ws.num_rows).map do |row|
  (1..ws.num_cols).map do |col|
    ws[row, col]
  end
end

table.each do |row|
  puts row.join("\t")
end

実行すると以下のように、無事スプレッドシートの内容が表示されます。

id  name
1   apple
2   orange
3   banana

参考

33
39
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
33
39