Skip to content

Instantly share code, notes, and snippets.

@daemianmack
Created February 10, 2014 16:58
Show Gist options
  • Save daemianmack/8919830 to your computer and use it in GitHub Desktop.
Save daemianmack/8919830 to your computer and use it in GitHub Desktop.
Authenticate via OAuth to the Google Drive API and list all files in the account
# Given a client_secrets.json file, authenticate via OAuth to the
# Google Drive API and list all files in the account.
# Setup:
## gem install google-api-client
## Under Google Developers Console, enable the Drive API and Drive SDK.
### Under Credentials > OAuth, create a new client ID.
#### This provides the client_secrets.json.
#### The Redirect URI must exactly match what the app actually sends.
# Docs:
## Example Ruby gdrive app
https://developers.google.com/drive/web/examples/ruby#setting_up_the_client_id_client_secret_and_other_oauth_20_parameters
## cloud console API tool
https://cloud.google.com/console/project/apps~neon-fort-486/apiui/api/drive/method/drive.files.list
## gdrive SDK parents API; good luck getting the item's folder's name
https://developers.google.com/drive/v2/reference/parents/get
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
def retrieve_all_files(client)
# Retrieve a list of File resources.
#
# @param [Google::APIClient] client
# Authorized client instance
# @return [Array]
# List of File resources.
drive = client.discovered_api('drive', 'v2')
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)
puts "Page status: #{api_result.status}"
if api_result.status == 200
files = api_result.data
result.concat(files.items)
page_token = files.next_page_token
else
puts "An error occurred: #{result.data['error']['message']}"
page_token = nil
end
end while page_token.to_s != ''
result
end
# Initialize the client.
client = Google::APIClient.new(
:application_name => 'filelister',
:application_version => '0.0.1')
# Load client secrets from ./client_secrets.json.
client_secrets = Google::APIClient::ClientSecrets.load
# Run installed application flow. Check the samples for a more
# complete example that saves the credentials between runs.
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => ['https://www.googleapis.com/auth/drive'])
client.authorization = flow.authorize
files = retrieve_all_files(client)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment