Advanced Calendar Service

  • The advanced Calendar service in Apps Script allows access to the public Google Calendar API, offering more features than the built-in service, such as setting event background colors.

  • This is an advanced service that requires explicit enabling before use.

  • The advanced Calendar service uses the same objects, methods, and parameters as the public Google Calendar API reference documentation.

  • You can use HTTP request headers likeIf-Match andIf-None-Match with the advanced Calendar service for conditional operations.

  • Sample code is provided for common tasks like creating, listing, conditionally modifying, conditionally retrieving, and synchronizing Calendar events.

The advanced Calendar service allows you to use the publicGoogle Calendar API in Apps Script. Much like Apps Script'sbuilt-in Calendar service, this APIallows scripts to access and modify the user's Google Calendar, includingadditional calendars that the user is subscribed to. In most cases, the built-inservice is easier to use, but this advanced service provides a few extrafeatures, including setting the background color for individual events.

Note: This is an advanced service that must beenabled before use.

Reference

For detailed information on this service, see thereference documentation for the publicGoogle Calendar API. Like all advanced services in Apps Script, the advancedCalendar service uses the same objects, methods, and parameters as the publicAPI. For more information, seeHow method signatures are determined.

To report issues and find other support, see theCalendar support guide.

HTTP request headers

The advanced Calendar service can accept the HTTP request headersIf-Match andIf-None-Match. For details, see thereference documentation.

Sample code

The sample code below usesversion 3 ofthe API.

Creating events

The following example demonstrates how to create an event in the user's defaultcalendar.

advanced/calendar.gs
/** * Creates an event in the user's default calendar. * @see https://developers.google.com/calendar/api/v3/reference/events/insert */functioncreateEvent(){constcalendarId="primary";conststart=getRelativeDate(1,12);constend=getRelativeDate(1,13);// event details for creating event.letevent={summary:"Lunch Meeting",location:"The Deli",description:"To discuss our plans for the presentation next week.",start:{dateTime:start.toISOString(),},end:{dateTime:end.toISOString(),},attendees:[{email:"gduser1@workspacesample.dev"},{email:"gduser2@workspacesample.dev"},],// Red background. Use Calendar.Colors.get() for the full list.colorId:11,};try{// call method to insert/create new event in provided calandarevent=Calendar.Events.insert(event,calendarId);console.log(`Event ID:${event.id}`);}catch(err){console.log("Failed with error %s",err.message);}}/** * Helper function to get a new Date object relative to the current date. * @param {number} daysOffset The number of days in the future for the new date. * @param {number} hour The hour of the day for the new date, in the time zone *     of the script. * @return {Date} The new date. */functiongetRelativeDate(daysOffset,hour){constdate=newDate();date.setDate(date.getDate()+daysOffset);date.setHours(hour);date.setMinutes(0);date.setSeconds(0);date.setMilliseconds(0);returndate;}

Listing calendars

The following example demonstrates how to retrieve details about the calendarsshown in the user's calendar list.

advanced/calendar.gs
/** * Lists the calendars shown in the user's calendar list. * @see https://developers.google.com/calendar/api/v3/reference/calendarList/list */functionlistCalendars(){letcalendars;letpageToken;do{calendars=Calendar.CalendarList.list({maxResults:100,pageToken:pageToken,});if(!calendars.items||calendars.items.length===0){console.log("No calendars found.");return;}// Print the calendar id and calendar summaryfor(constcalendarofcalendars.items){console.log("%s (ID: %s)",calendar.summary,calendar.id);}pageToken=calendars.nextPageToken;}while(pageToken);}

Listing events

The following example demonstrates how to list the next 10 upcoming events inthe user's default calendar.

advanced/calendar.gs
/** * Lists the next 10 upcoming events in the user's default calendar. * @see https://developers.google.com/calendar/api/v3/reference/events/list */functionlistNext10Events(){constcalendarId="primary";constnow=newDate();constevents=Calendar.Events.list(calendarId,{timeMin:now.toISOString(),singleEvents:true,orderBy:"startTime",maxResults:10,});if(!events.items||events.items.length===0){console.log("No events found.");return;}for(consteventofevents.items){if(event.start.date){// All-day event.conststart=newDate(event.start.date);console.log("%s (%s)",event.summary,start.toLocaleDateString());continue;}conststart=newDate(event.start.dateTime);console.log("%s (%s)",event.summary,start.toLocaleString());}}

Conditionally modifying an event

The following example shows how to conditionally update a Calendar event usingtheIf-Match header. The script creates a new event, waits 30 seconds, thenupdates the event only if no event details have changed since the event wascreated.

advanced/calendar.gs
/** * Creates an event in the user's default calendar, waits 30 seconds, then * attempts to update the event's location, on the condition that the event * has not been changed since it was created.  If the event is changed during * the 30-second wait, then the subsequent update will throw a 'Precondition * Failed' error. * * The conditional update is accomplished by setting the 'If-Match' header * to the etag of the new event when it was created. */functionconditionalUpdate(){constcalendarId="primary";conststart=getRelativeDate(1,12);constend=getRelativeDate(1,13);letevent={summary:"Lunch Meeting",location:"The Deli",description:"To discuss our plans for the presentation next week.",start:{dateTime:start.toISOString(),},end:{dateTime:end.toISOString(),},attendees:[{email:"gduser1@workspacesample.dev"},{email:"gduser2@workspacesample.dev"},],// Red background. Use Calendar.Colors.get() for the full list.colorId:11,};event=Calendar.Events.insert(event,calendarId);console.log(`Event ID:${event.getId()}`);// Wait 30 seconds to see if the event has been updated outside this script.Utilities.sleep(30*1000);// Try to update the event, on the condition that the event state has not// changed since the event was created.event.location="The Coffee Shop";try{event=Calendar.Events.update(event,calendarId,event.id,{},{"If-Match":event.etag},);console.log(`Successfully updated event:${event.id}`);}catch(e){console.log(`Fetch threw an exception:${e}`);}}

Conditionally retrieving an event

The following example shows how to conditionally fetch a Calendar event usingtheIf-None-Match header. The script creates a new event, then polls theevent for changes for 30 seconds. Any time the event changes, the new versionis fetched.

advanced/calendar.gs
/** * Creates an event in the user's default calendar, then re-fetches the event * every second, on the condition that the event has changed since the last * fetch. * * The conditional fetch is accomplished by setting the 'If-None-Match' header * to the etag of the last known state of the event. */functionconditionalFetch(){constcalendarId="primary";conststart=getRelativeDate(1,12);constend=getRelativeDate(1,13);letevent={summary:"Lunch Meeting",location:"The Deli",description:"To discuss our plans for the presentation next week.",start:{dateTime:start.toISOString(),},end:{dateTime:end.toISOString(),},attendees:[{email:"gduser1@workspacesample.dev"},{email:"gduser2@workspacesample.dev"},],// Red background. Use Calendar.Colors.get() for the full list.colorId:11,};try{// insert eventevent=Calendar.Events.insert(event,calendarId);console.log(`Event ID:${event.getId()}`);// Re-fetch the event each second, but only get a result if it has changed.for(leti=0;i <30;i++){Utilities.sleep(1000);event=Calendar.Events.get(calendarId,event.id,{},{"If-None-Match":event.etag},);console.log(`New event description:${event.start.dateTime}`);}}catch(e){console.log(`Fetch threw an exception:${e}`);}}

Synchronizing events

The following example demonstrates how to retrieve events using sync tokens.When you include a sync token in a Calendar advanced service request, theresulting response only includes items that have changed since that tokenwas generated, enabling more efficient processing. SeeSynchronize Resources Efficiently for more details onthe syncing process.

The following example makes use of the samegetRelativeDate(daysOffset, hour)method defined in the above examples.

advanced/calendar.gs
/** * Retrieve and log events from the given calendar that have been modified * since the last sync. If the sync token is missing or invalid, log all * events from up to a month ago (a full sync). * * @param {string} calendarId The ID of the calender to retrieve events from. * @param {boolean} fullSync If true, throw out any existing sync token and *        perform a full sync; if false, use the existing sync token if possible. */functionlogSyncedEvents(calendarId,fullSync){constproperties=PropertiesService.getUserProperties();constoptions={maxResults:100,};constsyncToken=properties.getProperty("syncToken");if(syncToken &&!fullSync){options.syncToken=syncToken;}else{// Sync events up to thirty days in the past.options.timeMin=getRelativeDate(-30,0).toISOString();}// Retrieve events one page at a time.letevents;letpageToken;do{try{options.pageToken=pageToken;events=Calendar.Events.list(calendarId,options);}catch(e){// Check to see if the sync token was invalidated by the server;// if so, perform a full sync instead.if(e.message==="Sync token is no longer valid, a full sync is required."){properties.deleteProperty("syncToken");logSyncedEvents(calendarId,true);return;}thrownewError(e.message);}if(events.items &&events.items.length===0){console.log("No events found.");return;}for(consteventofevents.items){if(event.status==="cancelled"){console.log("Event id %s was cancelled.",event.id);return;}if(event.start.date){conststart=newDate(event.start.date);console.log("%s (%s)",event.summary,start.toLocaleDateString());return;}// Events that don't last all day; they have defined start times.conststart=newDate(event.start.dateTime);console.log("%s (%s)",event.summary,start.toLocaleString());}pageToken=events.nextPageToken;}while(pageToken);properties.setProperty("syncToken",events.nextSyncToken);}

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-11 UTC.