Harshwardhan
Harshwardhan

Reputation: 11

Get list of all calendars of logged in user (Google calendar API)

I am trying to get all the calendars of the logged in user via oauth google. As of now I can get all the events in the primary calendar but I also want to display all the public calendars of the user.

Tried everything but could not find any method to fetch calendars. This is a ruby on rails 5 app I am working on.

Code to fetch events of current month

response = client.execute(api_method: service.events.list,
            parameters: { 'calendarId' => 'primary',
              'timeMin': Time.now.beginning_of_month.iso8601,
              'showDeleted': false,
              'singleEvents': true,
              'maxResults': 10,
              'orderBy': 'startTime'},
                headers: { 'Content-Type' => 'application/json' })

I tried client.calendarList.list but it shows error "Undefined method calendarList"

Thanks for help in advance.

Upvotes: 0

Views: 870

Answers (1)

Harshwardhan
Harshwardhan

Reputation: 11

Okay So I have found the solution to this problem and want to share in case someone else comes across same problem.

Here is the code service = client.discovered_api('calendar' , 'v3') @response = client.execute(api_method: service.calendar_list.list, parameters: {'calendarId' => 'secondary'}, 'showDeleted': false, 'maxResults': 10, headers: { 'Content-Type' => 'application/json' })

The problem was that you would need to use calendar_list instead of calendarList.

This was the reason it was throwing method not found error.

Here is the code you will need to initiate google api client.

client = Google::APIClient.new(:auto_refresh_token => true)
 client.authorization.access_token = oauth_token
 client.authorization.refresh_token = refresh_token
 client.authorization.client_id = ENV["GOOGLE_CLIENT_ID"]
 client.authorization.client_secret = ENV["GOOGLE_SECRET"]

 if client.authorization.refresh_token && client.authorization.expired?
     client.authorization.fetch_access_token!
 end

refresh_token and oauth_token will be obtained from google after successful oauth login.

ENV["GOOGLE_CLIENT_ID"] put the client_id obtained from the google while creating app. ENV["GOOGLE_CLIENT_ID"] put the client secret.

Upvotes: 1

Related Questions