Code Monkey home page Code Monkey logo

ruby-samples's Introduction

Google Workspace Ruby Samples Build Status

A collection of samples that demonstrate how to call Google Workspace APIs in Ruby.

APIs

Admin SDK

Apps Script

Calendar

Classroom

Docs

Drive V3

Gmail

Sheets

Slides

Tasks

Tools

Lint

gem install rubocop
rubocop

It should not produce any errors, i.e.:

Inspecting 24 files
........................

24 files inspected, no offenses detected

You can fix basic errors with:

rubocop --fix

ruby-samples's People

Contributors

afeld avatar asrivas avatar emon avatar fotijr avatar googleworkspace-bot avatar grant avatar hashedhyphen avatar jpoehnelt avatar jsmeredith avatar marckk avatar mos-adebayo avatar renovate[bot] avatar sqrrrl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ruby-samples's Issues

Expected top level property 'installed' or 'web' to be present.

Expected Behavior

Successful Ruby Quickstart

Actual Behavior

Traceback (most recent call last):
        5: from init.rb:42:in `<main>'
        4: from init.rb:22:in `authorize'
        3: from /home/perro/.rvm/gems/ruby-2.5.1/gems/googleauth-0.14.0/lib/googleauth/client_id.rb:82:in `from_file'
        2: from /home/perro/.rvm/gems/ruby-2.5.1/gems/googleauth-0.14.0/lib/googleauth/client_id.rb:82:in `open'
        1: from /home/perro/.rvm/gems/ruby-2.5.1/gems/googleauth-0.14.0/lib/googleauth/client_id.rb:85:in `block in from_file'
/home/perro/.rvm/gems/ruby-2.5.1/gems/googleauth-0.14.0/lib/googleauth/client_id.rb:99:in `from_hash': Expected top level property 'installed' or 'web' to be present. (RuntimeError)

Steps to Reproduce the Problem

    1. gem install google-api-client
    1. Get auth.json:
{
  "type": "service_account",
  "project_id": "xxxx",
  "private_key_id": "xxxx",
  "private_key": "xxxx",
  "client_email": "xxxx",
  "client_id": "xxxx",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "xxxx"
}
    1. Set up the sample:
require "google/apis/drive_v3"
require "googleauth"
require "googleauth/stores/file_token_store"
require "fileutils"

OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
APPLICATION_NAME = "Drive API Ruby Quickstart".freeze
CREDENTIALS_PATH = "auth.json".freeze
# The file token.yaml stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
TOKEN_PATH = "token.yaml".freeze
SCOPE = Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY

##
# Ensure valid credentials, either by restoring from the saved credentials
# files or intitiating an OAuth2 authorization. If authorization is required,
# the user's default browser will be launched to approve the request.
#
# @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
def authorize
  client_id = Google::Auth::ClientId.from_file CREDENTIALS_PATH
  token_store = Google::Auth::Stores::FileTokenStore.new file: TOKEN_PATH
  authorizer = Google::Auth::UserAuthorizer.new client_id, SCOPE, token_store
  user_id = "default"
  credentials = authorizer.get_credentials user_id
  if credentials.nil?
    url = authorizer.get_authorization_url base_url: OOB_URI
    puts "Open the following URL in the browser and enter the " \
         "resulting code after authorization:\n" + url
    code = gets
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI
    )
  end
  credentials
end

# Initialize the API
drive_service = Google::Apis::DriveV3::DriveService.new
drive_service.client_options.application_name = APPLICATION_NAME
drive_service.authorization = authorize

# List the 10 most recently modified files.
response = drive_service.list_files(page_size: 10,
                                    fields:    "nextPageToken, files(id, name)")
puts "Files:"
puts "No files found" if response.files.empty?
response.files.each do |file|
  puts "#{file.name} (#{file.id})"
end

Specifications

  • ruby 2.5.1p57 (2018-03-29 revision 63029)
  • [x86_64-linux]

Sheets Quickstart fails due to NoMethodError

When I ran Sheets API's Quickstart, I encountered the error below.

hash@hh-mbp ~/w/google-sheets-api-sample> ruby quickstart.rb
Name, Major:
Traceback (most recent call last):
quickstart.rb:48:in `<main>': undefined method `each_values' for #<Google::Apis::SheetsV4::ValueRange:0x00007fb11c1f1dd0> (NoMethodError)

Error 400 following admin_sdk directory quickstart

Expected Behavior

I should be able to complete OAuth flow and get a list of users.

Actual Behavior

When I click on the URL I receive in my console, I get a notice that the OAuth out-of-band (OOB) flow has been deprecated.

Clicking details shows the following:
image

Steps to Reproduce the Problem

  1. Create a project.
  2. Give it admin SDK permissions.
  3. Create OAuth Credentials.
  4. Attempt to run admin_sdk/directory/quickstart.rb.

Specifications

  • Ruby 3.1.2
  • Mac OS Monterey

Scope NameError - DriveV3 or TasksV1?

Expected Behavior

SCOPE constant to initialize

Actual Behavior

NameError - uninitialized constant Google::Apis::DriveV3

Specifications

  • Ruby version (ruby -v): 2.5.1
  • OS (Mac/Linux/Windows): macOS 10.13.6

Question

In the SCOPE constant declaration, it calls for the Google::Apis::DriveV3::AUTH_TASKS_READONLY

Is this meant to be Google::Apis::TasksV1::AUTH_TASKS_READONLY? I swapped and was able to get past the NameError.

Load Error sheets_v4

Expected Behavior

Read sheets

Actual Behavior

require': cannot load such file -- google/apis/sheet_v4 (LoadError)

Steps to Reproduce the Problem

Specifications

  • Ruby version (ruby -v)
  • OS (Mac/Linux/Windows)

Google calendar api

Expected Behavior

The first time you run the sample, it will prompt you to authorize access:

The sample will attempt to open a new window or tab in your default browser. If this fails, copy the URL from the console and manually open it in your browser.

If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.
Click the Accept button.
The sample will proceed automatically, and you may close the window/tab.

Actual Behavior

C:\Users\WEBSITE\Desktop\gcapi>ruby quickstart.rb
Traceback (most recent call last):
2: from quickstart.rb:1:in <main>' 1: from C:/Ruby25-x64/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in require'
C:/Ruby25-x64/lib/ruby/2.5.0/rubygems/core_ext/kernel_require.rb:59:in `require': cannot load such file -- google/apis/calendar_v3 (LoadError)

Steps to Reproduce the Problem

  1. Tried to check if the code is wrong
  2. Checked if the gem installed well

Specifications

  • Ruby version (ruby -v)
  • OS (Mac/Linux/Windows)

Example for accessing google sheets api with service account

Hello!

This is a request, not an issue. I am trying to access Google Sheets API from my Ruby script, but with a service account. My script will be running on Jenkins, so it's shouldn't have user input.

The example I found here works fine with my own oauth2 json file - https://developers.google.com/sheets/api/quickstart/ruby, but I can't seem to figure out how to make it work with a service account. This is what I've tried so far,

  • Gave 'Editor' access to my service account
  • Enabled domain wide delegation, and google api console automatically created a client id for service account client. But this does not have a json file attached to it.
  • Enabled Google Sheets & Drive APIs
  • And, tried the following code,
service = Google::Apis::SheetsV4::SheetsService.new
  service.client_options.application_name = 'test panne ruby'
  service.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
    json_key_io: File.open('path_to_my_serviceaccount_json_file'),
    scope: Google::Apis::SheetsV4::AUTH_SPREADSHEETS_READONLY)

The above does not throw any error, but when I try to access a sheet, I get forbidden: The caller does not havepermission (Google::Apis::ClientError) error.

    # Query the spreadsheet
  spreadsheet_id = 'long___________spreadsheetid'
  range = 'characters!A1:E'

  response = service.get_spreadsheet_values(spreadsheet_id, range)

Does anyone know how I can make this work? or what I am missing, please? Any help is greatly appreciated.

(I managed to figure it out from C# (my code works with service accounts also), but having hard time figuring it out from Ruby.)

Add Gemfile to all Quickstart

Expected Behavior

Each quickstart should have a Gemfile with the correct dependencies.

Actual Behavior

These files don't exist.

documentation missing

There is a general lack of how to authenticate with most of google ruby gems. The credentials.json file is not well documented.. each project should explicitly provide instructions for setting this up... IMO this is a big barrier to entry with google projects and code in general...

error on puts response

Expected Behavior

puts row[0] and row[4]

Actual Behavior

NoMethodError (undefined method `each_value' for #Google::Apis::SheetsV4::ValueRange:0x00007ff91294f008)

Steps to Reproduce the Problem

  1. Run the sample file
  2. see the error on console

Specifications

  • Ruby version (ruby -v)
    2.5.1p57
  • OS (Mac/Linux/Windows)
    mac 10.13.16

Another fix and a suggestion for output

I don't know much about Git, i will tell you here what i found,

again in reference to : https://developers.google.com/people/quickstart/ruby

to have the code working I subsitued line
service = Google::Apis::PeopleV1::PeopleService.new
with :
service = Google::Apis::PeopleV1::PeopleServiceService.new

Then, to have the the code actually print something i would close with someting like this:

    # Fetch the next 600 events for the user
    response = service.list_person_connections(
      'people/me',
      page_size: 600,
      person_fields: ["names", "phoneNumbers", "emailAddresses"]
      # person_fields: 'names,emailAddresses,phoneNumbers'
    )
    
    # print first name, phone and email for each connection
    response.connections.each do |con|
      name = "???"; phone = "???"; mail = "???";
      begin name = con.names.first.display_name;  rescue;  end
      begin phone = con.phone_numbers.first.canonical_form; rescue; end 
      begin mail = con.email_addresses.first.value; rescue; end 
      # don't print connections with all undefined values 
      next if ((name == phone)  && (phone == mail))
      puts "#{name} === #{phone} == #{mail}"  
    end

Remove the begin-rescue block from quickstart

Expected Behavior

Expected the quickstart to authenticate me after visiting the link and pasting in the authorization code.

Actual Behavior

It got caught in the begin-rescue block and threw a Google::Apis::ClientError error.

Steps to Reproduce the Problem

  1. run ruby quickstart.rb
  2. click the link and authorize Google account
  3. Copy/paste the authorization code into the terminal
  4. Get the Google::Apis::ClientError error with the message "The request is invalid and should not be retried without modification."

Specifications

  • Ruby version 2.4.4
  • OS Linux Ubuntu 18.04

I simply removed the begin-rescue block from the quickstart.rb code altogether and it then gave me a much more helpful error that I was able to fix.

That error was this: "User has not enabled the Apps Script API. Enable it by visiting https://script.google.com/home/usersettings then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systemsand retry."

Thanks!

How to get page_id for creating slides

Expected Behavior

Actual Behavior

Steps to Reproduce the Problem

presentation_id = "1lMmb9kr1VGLe-GNtIAQGEYOH_gNWXceM5VFOIEDDTkM"
presentation = service.get_presentation presentation_id

def create_slide(presentation_id, page_id)
# [START slides_create_slide]
body = Google::Apis::SlidesV1::Presentation.new
requests = [{
create_slide: {
# object_id_prop: page_id,
insertion_index: '1',
slide_layout_reference: {
predefined_layout: 'TITLE_AND_TWO_COLUMNS'
}
}
}]

Specifications

  • Ruby version (ruby -v).
  • OS (Mac/Linux/Windows)

How to get page_id for above

`connect_nonblock': SSL_connect returned=1 errno=0

Expected Behavior

After copying the code into the console app it should authenticate with google service

Actual Behavior

I do not know if it is a problem with google gem or may be something else

C:/Ruby/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock': SSL_connect returned=1 errno=0 state=error: certificate verify failed (Faraday::SSLError)
        from C:/Ruby/lib/ruby/2.3.0/net/http.rb:933:in `connect'
        from C:/Ruby/lib/ruby/2.3.0/net/http.rb:863:in `do_start'
        from C:/Ruby/lib/ruby/2.3.0/net/http.rb:852:in `start'
        from C:/Ruby/lib/ruby/2.3.0/net/http.rb:1398:in `request'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/faraday-0.12.2/lib/faraday/adapter/net_http.rb:80:in `perform_request'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/faraday-0.12.2/lib/faraday/adapter/net_http.rb:38:in `block in call'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/faraday-0.12.2/lib/faraday/adapter/net_http.rb:85:in `with_net_http_connection'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/faraday-0.12.2/lib/faraday/adapter/net_http.rb:33:in `call'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/faraday-0.12.2/lib/faraday/request/url_encoded.rb:15:in `call'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/faraday-0.12.2/lib/faraday/rack_builder.rb:141:in `build_response'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/faraday-0.12.2/lib/faraday/connection.rb:386:in `run_request'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/faraday-0.12.2/lib/faraday/connection.rb:186:in `post'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/signet-0.7.3/lib/signet/oauth_2/client.rb:960:in `fetch_access_token'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/signet-0.7.3/lib/signet/oauth_2/client.rb:998:in `fetch_access_token!'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/googleauth-0.5.1/lib/googleauth/signet.rb:69:in `fetch_access_token!'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/googleauth-0.5.1/lib/googleauth/user_authorizer.rb:179:in `get_credentials_from_code'
        from C:/Ruby/lib/ruby/gems/2.3.0/gems/googleauth-0.5.1/lib/googleauth/user_authorizer.rb:201:in `get_and_store_credentials_from_code'
        from quickstart.rb:29:in `authorize'
        from quickstart.rb:39:in `<main>'

Steps to Reproduce the Problem

  1. ruby quickstart.rb
  2. Open the following URL in the browser and enter the resulting code after authorization
  3. Paste code form website into console

Specifications

  • Ruby version: ruby 2.3.3p222 (2016-11-21 revision 56859) [x64-mingw32]
  • Windows

Create empty file

I was looking at the spreadsheet api documentation and saw that it is possible to create an empty file using Divre API
https://developers.google.com/sheets/api/guides/create#work_with_google_drive_folders

but I didn't find exactly in that step in that repository

anyway, I tried this code taken from the examples in that repository:

file_metadata = { name: "My new Sheet #{Time.now.strftime('%d/%m/%Y %H:%M')}",
                  mimeType: 'application/vnd.google-apps.spreadsheet' }
file = drive_service.create_file(file_metadata)

but I always get this error:

Traceback (most recent call last):
	2: from quickstart.rb:80:in `<main>'
	1: from quickstart.rb:60:in `create_file'
/home/vagrant/.rvm/gems/ruby-2.7.2/gems/google-api-client-0.53.0/generated/google/apis/drive_v3/service.rb:895:in `create_file': unknown keywords: :name, :mimeType (ArgumentError)

How could I make this work?

Expected Behavior

The file created successfully

Actual Behavior

Error:

Traceback (most recent call last):
	2: from quickstart.rb:80:in `<main>'
	1: from quickstart.rb:60:in `create_file'
/home/vagrant/.rvm/gems/ruby-2.7.2/gems/google-api-client-0.53.0/generated/google/apis/drive_v3/service.rb:895:in `create_file': unknown keywords: :name, :mimeType (ArgumentError)

Steps to Reproduce the Problem

1.Create a new instance of google drive service (I did this based on: Ruby quickstart)
2. Use the method create_file passing file_metadata

Specifications

  • Ruby version (2.7.2)
  • OS (Linux)

[SyncRepoSettings bot] - Invalid config file

Failed to validate the config schema at '.github/sync-repo-settings.yaml': [
{
"instancePath": "/permissionRules/1/permission",
"schemaPath": "#/properties/permissionRules/items/properties/permission/enum",
"keyword": "enum",
"params": {
"allowedValues": [
"pull",
"push",
"admin"
]
},
"message": "must be equal to one of the allowed values"
}
]

Schema can be found at https://github.com/googleapis/repo-automation-bots/blob/main/packages/sync-repo-settings/src/schema.json

Ruby Google Sheets API Quickstart - authorize step fails

Expected Behavior

After allowing the app to access my account via the browser, I can paste the code displayed in the browser into the prompt and be authenticated.

Actual Behavior

After allowing access, pasting the code into the terminal, and pressing enter, an error is returned
Screen Shot 2020-09-13 at 2 18 53 PM

Steps to Reproduce the Problem

  1. Follow the instructions written at Google Sheets API Docs to setup the project.
  2. run ruby quickstart.rb
  3. Allow access to the app via the browser
  4. paste the auth code from the browser to the terminal. The error is returned at this step.

Specifications

  • Ruby version (ruby -v) : Ruby 2.7.1
  • OS (Mac/Linux/Windows) : Mac

Changing sheets/quickstart/quickstart.rb:31 to:

  code = gets.strip

fixes the problem and allows me to successfully authenticate the quickstart app.

Gmail quickstart.rb Runtime error

Expected Behavior

puts labels

Actual Behavior

C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/googleauth-0.6.7/lib/googleauth/client_id.rb:99:in from_hash': Expected top level property 'installed' or 'web' to be present. (RuntimeError) from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/googleauth-0.6.7/lib/googleauth/client_id.rb:85:in block in from_file'
from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/googleauth-0.6.7/lib/googleauth/client_id.rb:82:in open' from C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/googleauth-0.6.7/lib/googleauth/client_id.rb:82:in from_file'
from quickstart.rb:22:in authorize' from quickstart.rb:42:in

'

Steps to Reproduce the Problem

  1. Followed the steps in the Gmail API guide.

Specifications

  • Ruby version (ruby -v)
  • OS (Mac/Linux/Windows)
    ruby 2.4.4p296 Windows

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.