tachiken's blog

開発、プログラミング、その他

Ruby on Rails Google calendar APIを使ってカレンダー情報を取得する。

Google calendar APIを使ってカレンダー情報を取得を試してみた。 以下はAPIインスタンス作成から情報取得までの流れ。

def update_schedule
  client = Google::APIClient.new #APIのインスタンス作成
  client.authorization.access_token = current_user.token #トークンを入れる(もしかしたら不要かも)
  client.authorization.client_id = ENV['GOOGLE_CLIENT_ID'] # Google Developerで取得したclient id を入れる。.envに記載
  client.authorization.client_secret = ENV['GOOGLE_CLIENT_SECRET'] #Google Developerで取得したclient secret を入れる。.envに記載
  client.authorization.refresh_token = current_user.refresh_token #リフレッシュトークンを入れる
  service = client.discovered_api('calendar', 'v3') #APIの種類を指定(google calendarAPIを指定)
  
@responses = client.execute(
  :api_method => service.events.list,
  :parameters => {'calendarId' => 'primary',
    'timeMin'=> (Time.now - 10.months).iso8601,
    'timeMax'=> (Time.now + 1.months).iso8601,
    'maxResults' => 2500},
  :headers => {'Content-Type' => 'application/json'})
#インスタンスを実行する。executeの引数には色々指定でき、取得期間などが指定できる。
 @responseにAPIからのレスポンスがはいる。

  events = []
  @responses.data.items.each do |item|
    events << item
  end
#レスポンスからイベントのデータのみを取ってきてリストに入れる。