🦔

【Ruby】スクリプトでGoogleドライブにファイルをアップロードしてみる

2023/04/19に公開

はじめに

API を叩いて入手した画像をそのまま Google ドライブに保存したかったので、Google API を使って Ruby でスクリプトを作ってみました。
今回の記事では、Google ドライブに保存する際の事前準備とスクリプトのサンプルコードをまとめておきます。

環境

Ruby 3.1.3

事前準備

Gem のインストール

Google が公式で出している下記の gem を使用しました。
それぞれgem installしておきます。

サービスアカウントの準備

サービスアカウントの作成はこちらを参照ください。
アカウント作成後、キーを発行して JSON ファイルをダウンロードしておきます。
また、ファイルを保存したい Google ドライブのフォルダにアカウントを共有しておきます。

キー作成時の画面

キー作成時に表示される注意メッセージです。
今回はサービスアカウントを使用しましたが状況に応じて、Workload Identityを使う方が良さそうです。
引用元でも紹介されているこちらのページが参考になります。

スクリプト

require 'google/apis/drive_v3'
require 'googleauth'

scope = 'https://www.googleapis.com/auth/drive.file'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('./client_secret.json'),
  scope: scope)
authorizer.fetch_access_token!

drive = Google::Apis::DriveV3::DriveService.new
drive.authorization = authorizer

metadata = Google::Apis::DriveV3::File.new(name: 'sample.png', parents: ['GoogleドライブのフォルダID'])
drive.create_file(metadata, upload_source: './sample.png', content_type: 'image/png')

個別に説明していきます。

scope = 'https://www.googleapis.com/auth/drive.file'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
  json_key_io: File.open('./client_secret.json'),
  scope: scope)
authorizer.fetch_access_token!

Google Auth Library for RubyReadmeを参考にしました。

scopeではアプリでできることの範囲(スコープ)を設定することができます。
今回は Google ドライブにファイルを作成させたかったので、https://www.googleapis.com/auth/drive.file のスコープコードを設定しました。
その他のスコープコードはこちらを参照ください。

json_key_ioには事前準備で用意しておいたサービスアカウントキーの JSON ファイルを指定します。

drive = Google::Apis::DriveV3::DriveService.new
drive.authorization = authorizer

metadata = Google::Apis::DriveV3::File.new(name: 'sample.png', parents: ['GoogleドライブのフォルダID'])
drive.create_file(metadata, upload_source: './sample.png', content_type: 'image/png')

REST client for Google APIsReadmeを参考にしました。

Google::Apis::DriveV3::File.new()の引数で、保存するファイルの名前(name)と保存先のフォルダ(parents)を指定します。

create_file()の引数ではアップロードするファイル(upload_source)とファイルのタイプ(content_type)を指定します。
共有ドライブに保存する場合は、下記のようにsupports_team_drives: trueを追加する必要があります。

GitHubで編集を提案

Discussion