Working with Google Sheets in Rails
  • Set up and configure a Project in Google Developer Console

  • Create a project from here

  • Enable the Google Sheets API for your project from here

  • Create a service Account (to get credentials to test with)

  • (Credentials -> Service Accounts -> "Create Service Account" )

  • Create a key (Select Service Account -> Keys -> "Add Key" -> "Create New Key" -> "Json")

  • This should download a .json file. Add this file to your app

  • Create a google sheet and give the Service Account access

  • Get the Service Account email from the "Details" tab of the Service Account

  • Open/create a sheet, hit "Share", then enter the email address of the Service Account.

  • The following code snippet should get you authenticated and accessing data

  • scope = 'https://www.googleapis.com/auth/spreadsheets'
    
    file = File.join(Rails.root, 'config', 'googleauth.json')
    
    authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
      json_key_io: File.open(file),
      scope: scope)
    
    authorizer.fetch_access_token!
    
    service = Google::Apis::SheetsV4::SheetsService.new
    service.authorization = authorizer
    
    spreadsheet_id = "1ENkiF9XBfmToZAVPPS61TwSQs0tiumjDrmp9_1hOWn0"
    range = "Sheet1!A1:B1"
    
    response = service.get_spreadsheet_values spreadsheet_id, range
    

  • Website Page