Reputation: 661
It took me a bit of reading in several locations, as well as looking in Stack Overflow to figure out how to use the Google API Ruby client with Google Calendar in a server to server application without giving the server client full access to all users. I just wanted it to have the ability to get/create/update/delete events for a single calendar. There may be other ways to do this, but I'm documenting below how I did it as it may help someone else out.
Upvotes: 5
Views: 1641
Reputation: 661
Somewhat helpful link: https://developers.google.com/api-client-library/ruby/
A JSON file will be downloaded to your computer. Move this file to some place accessible by your application and rename it to "google_api.json" (or whatever you want as long as it matches the correct path below). Ensure that only the application can access this file (it contains a private key).
Here is a sample file to authorize and access the Googe Calendar API:
# http://www.rubydoc.info/github/google/google-api-ruby-client/Google/Apis/CalendarV3
require 'googleauth'
require 'google/apis/calendar_v3'
class MyApp::GoogleCalendar
def initialize
authorize
end
def service
@service
end
def events(reload=false)
# NOTE: This is just for demonstration purposes and not complete.
# If you have more than 2500 results, you'll need to get more than
# one set of results.
@events = nil if reload
@events ||= service.list_events(calendar_id, max_results: 2500).items
end
private
def calendar_id
@calendar_id ||= # The calendar ID you copied in step 20 above (or some reference to it).
end
def authorize
calendar = Google::Apis::CalendarV3::CalendarService.new
calendar.client_options.application_name = 'App Name' # This is optional
calendar.client_options.application_version = 'App Version' # This is optional
# An alternative to the following line is to set the ENV variable directly
# in the environment or use a gem that turns a YAML file into ENV variables
ENV['GOOGLE_APPLICATION_CREDENTIALS'] = "/path/to/your/google_api.json"
scopes = [Google::Apis::CalendarV3::AUTH_CALENDAR]
calendar.authorization = Google::Auth.get_application_default(scopes)
@service = calendar
end
end
So now you can call cal = MyApp::GoogleCalendar.new
and get the events with cal.events
. Or you can make calls directly with cal.service.some_method(some_args)
, rather than creating methods in this file.
Upvotes: 5