This is a record of my trial to use Google Drive API on Ruby (and on Rails).
- For installed applications
Differences from web applications
-> Include some parameters in authorization code request at a first authorization (access_type=offline& approval_prompt=force)
-> Require refresh_token ( and access_token ,too).
My sample code is following.
qiita.rb
require 'google/api_client'
##
# Retrieve a list of File resources.
#
CLIENT_ID = ' your client ID '
CLIENT_SECRET = ' your client secret '
REDIRECT_URI = ' your redirect url '
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
# Initialize the client & Google+ API
client = Google::APIClient.new
# Initialize OAuth 2.0 client
# client.authorizaton returns Signet::OAuth2::Client objext
client.authorization.client_id = CLIENT_ID
client.authorization.client_secret = CLIENT_SECRET
client.authorization.redirect_uri = REDIRECT_URI
client.authorization.scope = OAUTH_SCOPE
# Request authorization
redirect_uri = client.authorization.authorization_uri
# You will get a redirect URL, and input it to an address var of a browser.
puts redirect_uri
# When prompted ,copy an authorization code and paste it to your terminal.
client.authorization.code = gets.strip
# Get tokens
# ex. {"access_token"=>"ya296ZSGyxLfflpv1ADxHjCKvZLoKyVylgjiLhW1sX_fKw",
# "token_type"=>"Bearer", "expires_in"=>3600,
# "refresh_token"=>"1/4jaoSQ_edOCVegeaORYEdlwMiwyLJB3E1uNz3hfKQto"}
tokens = client.authorization.fetch_access_token
#Update tokens and retrieve a list of File Resources.
begin
client.authorization.update_token!(
:refresh_token => tokens["refresh_token"],
:access_token => tokens["access_token"],
:expires_in => tokens["expires_in"]
)
drive = client.discovered_api('drive', 'v2')
rescue
puts "Here is in resucue"
ensure
result = Array.new
page_token = nil
begin
parameters = {}
if page_token.to_s != ''
parameters['pageToken'] = page_token
end
api_result = client.execute(
:api_method => drive.files.list,
:parameters => parameters)
if api_result.status == 200
files = api_result.data
result.concat(files.items)
else
puts "An error occurred: #{result.data['error']['message']}"
page_token = nil
end
end while page_token.to_s != ''
# Printing file names
result.each { |item|
puts item.title
}
end
参考にしたURL
http://www.eisbahn.jp/yoichiro/2012/10/google-drive-api-ruby-on-rails.html
http://www.eisbahn.jp/yoichiro/2012/05/google_oauth2_web_server_profile_refreshtoken.html
http://code.google.com/p/oauth-signet/wiki/SignetOAuth2Client
http://rubydoc.info/github/google/google-api-ruby-client/
https://developers.google.com/drive/v2/reference/files#resource
いじょ