Adding/Deleting Events with the Google Calendar API

I recently had a chance to fool around with the Google Calendar API, specifically adding and deleting events.

I've talked in the past about using Google Client Logins to access the Google Data API and we'll use that same ClientLogin code to authenticate our requests to the Calendar API.

Authenticating

There are different ways to authenticate requests to Calendar depending on the type of application you're writing. If you're writing a front-end that a user is going to interact with, it's a good idea to use AuthSub proxy authentication which will redirect the user, let them login with their Google Account, and send them back to your application.

In our case, we're writing PHP code that will modify the calendar behind the scenes. For that scenario, we'll use ClientLogin authentication and use the class we wrote last time

In additional to needing a Google Account for authenticating, you'll also need the Calendar ID if the calendar being used is not the default calendar. The Calendar ID can be found near the bottom of the page in the Settings for the calendar and is just a special, randomly generated email address.

image

Adding an Event

Adding an event is pretty straightforward. It's just a matter of sending an authenticated <entry> XML packet via HTTP POST to the calendar URL which is the following:

http://www.google.com/calendar/feeds/userId/private/full

The userId is either your Google Account email address (if using the default calendar) or the Calendar ID mentioned above (if using any other calendar). You also need to make sure the Content-Type of the POST request is application/atom+xml.

The event XML looks like this:

~~~~ {.php name="code"} $xml = " xmlns:gd='http://schemas.google.com/g/2005'> term='http://schemas.google.com/g/2005#event'> {$params["title"]} {$params["content"]} value='http://schemas.google.com/g/2005#event.opaque'> value='http://schemas.google.com/g/2005#event.confirmed'> endTime='{$params["endTime"]}'> "; wzxhzdk:0

Here's a simple example that adds an entry. The GoogleClientLogin class can be found here:

~~~~ {.php name="code"} define("APP_NAME", "MY APP");$email = "my.account@gmail.com";$password = "mypassword";$altEmail = "this_is_the_random_email_from_the_calendar_settings";$login = new GoogleClientLogin($email, $password, GoogleClientLogin::$CALENDAR_SERVICE, APP_NAME);$cal = new GoogleCalendar($login);$cal->altEmail = $altEmail;$entryData = $cal->addEvent(array( "title"=> "Auto Test event", "content"=> "This is a test event", "where"=> "Test location", "startTime"=> time()+60*60*24*1 ));print_r($entryData); ~~~~