Quentius
Quentius

Reputation: 21

How do I access to Google Calendar through CalDAV API?

I'm trying to access to Google Calendar through CalDAV API with Google's API library for Ruby (I use service accounts as the application type).

I've written following code, but this doesn't work when the HTTP method is PUT or POST and outputs an error "HTTP method not allowed" with the status code 405. However, it works correctly when the method is GET or DELETE.

require 'google/api_client'

client = Google::APIClient.new(
  application_name: 'test',
  application_version: '1.0.0'
)

calendar_id = 'CALENDER_ID'
BASE_URL = "https://apidata.googleusercontent.com/caldav/v2/#{calendar_id}/events/"

key = Google::APIClient::KeyUtils.load_from_pkcs12('P12_FILE', 'notasecret')
client.authorization = Signet::OAuth2::Client.new(
  token_credential_uri: 'https://www.googleapis.com/oauth2/v3/token',
  audience:             'https://www.googleapis.com/oauth2/v3/token',
  scope:                'https://www.googleapis.com/auth/calendar',
  issuer:               '[email protected]',
  signing_key:          key)
client.authorization.fetch_access_token!

body = <<EOS
BEGIN:VCALENDAR
VERSION:2.0
PRODID:test
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-WR-CALNAME:CAMPHOR- Schedule 201503
BEGIN:VTIMEZONE
TZID:Asia/Tokyo
BEGIN:STANDARD
DTSTART:19700101T000000
TZOFFSETFROM:+0900
TZOFFSETTO:+0900
TZNAME:JST
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
DTSTAMP:20150224T080050Z
UID:4807869c-ba02-48cc-aed5-0e0f5ff19022
DTSTART:20150331T150000
DTEND:20150331T200000
DESCRIPTION:
SUMMARY:DEST 2015-03-31 15:00:00 +0900 2015-03-31 20:00:00 +0900
END:VEVENT
END:VCALENDAR
EOS

request = Google::APIClient::Request.new(
  uri: BASE_URL,
  body: body,
  http_method: :post,
  headers: {
    'Content-Type' => 'application/xml; charset=utf-8'
  }
)

result = client.execute(request)

puts result.response.status
puts result.response.env

Could you tell me how should I fix this code to be able to use the all methods?

Upvotes: 2

Views: 3264

Answers (1)

Steve Bazyl
Steve Bazyl

Reputation: 11672

The initial problem is you can't PUT to the collection resource like that in CalDAV. See section 5.3.2 of the spec for more details. In other words, the URL should be something like ".../events/somerandomeventid.ics"

That said, you're headed down a bad path here.

  • The API client you're using isn't meant to be used with CalDAV.
  • Unless you have a good reason to use CalDAV, don't. Use the calendar API.
  • Calendar isn't meant to be used with non-user accounts like that. Sure, it might work, but it's not in the spirit of the product/API.

Upvotes: 1

Related Questions