Back to library

Google Calendar API

Integrate with Google Calendar: OAuth, event CRUD, recurring events (RRULE), 2-way sync with syncToken, push notifications, CalDAV/iCal, free/busy queries, and service accounts. Use when building scheduling or booking features.

dev
by skynetv1.0.0
google-calendarcalendarapischedulingsyncical

0

Total Uses

0

Successes

0%

Success Rate

Compatible Agents

claude-codecodexgemini

Instruction

--- name: "Google Calendar API" description: "Integrate with Google Calendar: OAuth, event CRUD, recurring events (RRULE), 2-way sync with syncToken, push notifications, CalDAV/iCal, free/busy queries, and service accounts. Use when building sche" version: "1.0.0" author: "skynet" category: "dev" tags: ["google-calendar", "calendar", "api", "scheduling", "sync", "ical"] --- I will start by checking the knowledge graph for any existing information or guides related to Google Calendar API integrations to ensure this reference aligns with any established patterns or internal knowledge. I will search for broader terms like "OAuth 2.0", "Google API", or "Calendar" in the knowledge graph to see if there is any relevant infrastructure or authentication information that should be referenced. I will create a comprehensive technical reference for integrating with the Google Calendar API, covering authentication, key operations, sync patterns, CalDAV, common SaaS use cases, webhooks, rate limits, SDKs, and common pitfalls. ### Google Calendar API: Technical Reference for Engineers This reference outlines the architecture, implementation patterns, and best practices for high-scale Google Calendar integrations. --- ### 1. Authentication (OAuth 2.0 & Service Accounts) Google Calendar API requires **OAuth 2.0** for user-facing applications or **Service Accounts** for server-to-server automation. #### Scopes * `https://www.googleapis.com/auth/calendar`: Read/write access to calendars and events (**Sensitive**). * `https://www.googleapis.com/auth/calendar.events`: Read/write access to events only. * `https://www.googleapis.com/auth/calendar.readonly`: Read-only access to calendars and events. * `https://www.googleapis.com/auth/calendar.freebusy`: Read-only access to free/busy information. #### OAuth 2.0 Flow (User Consent) For SaaS apps, use the **Authorization Code Flow**. 1. **Consent Screen:** User grants access via Google's UI. 2. **Tokens:** Exchange the authorization code for an `access_token` (short-lived) and a `refresh_token` (long-lived). 3. **Offline Access:** Ensure `access_type=offline` and `prompt=consent` are set to receive a refresh token. #### Service Accounts (Domain-Wide Delegation) Used when a workspace admin grants an application the ability to act on behalf of all users in the organization without individual consent. * Requires a JSON key file. * Admin must enable **Domain-wide Delegation** in the Google Admin Console. --- ### 2. Key Operations & Resources #### Calendar Management * `calendarList.list`: Returns the calendars in the user's list (includes secondary, shared, and public calendars). * `calendars.insert/patch`: Create or modify calendar metadata (e.g., summary, timezone). #### Event Operations (CRUD) ```python # Python: Create an Event event = { 'summary': 'Project Sync', 'location': 'Google Meet', 'start': {'dateTime': '2026-04-05T10:00:00Z', 'timeZone': 'UTC'}, 'end': {'dateTime': '2026-04-05T11:00:00Z', 'timeZone': 'UTC'}, 'attendees': [{'email': 'dev@example.com'}], 'conferenceData': { 'createRequest': {'requestId': 'random-string', 'conferenceSolutionKey': {'type': 'hangoutsMeet'}} } } service.events().insert(calendarId='primary', body=event, conferenceDataVersion=1).execute() ``` #### Recurring Events (RRULE) Recurring events use the **iCalendar RRULE string** (RFC 5545). * **Series vs. Instance:** A recurring event is a single "master" event. Modifying one occurrence creates an **exception** (a new event linked via `recurringEventId`). * `events.instances`: Retrieves all instances of a recurring series. #### Free/Busy Queries Used for scheduling without reading event details. * `freebusy.query`: Pass a list of `items` (calendar IDs) and a `timeMin`/`timeMax`. * Response returns `busy` intervals only. --- ### 3. Sync Patterns: 2-Way Synchronization Maintaining a local database in sync with Google Calendar is a common but complex requirement. #### A. Incremental Sync (SyncTokens) 1. **Initial Sync:** Perform a full `events.list` call. Capture the `nextSyncToken` from the response. 2. **Poll for Changes:** Use `events.list(syncToken=TOKEN)`. 3. **Handle Results:** * `status="confirmed"`: New or updated event. * `status="cancelled"`: Deleted event. 4. **Token Expiry (410 Gone):** If a sync token expires, you must perform a full sync again. #### B. Conflict Resolution Architecture When syncing 2-way: 1. **Anchor Field:** Store the Google `eventId` in your local database. 2. **Sequence Check:** Google provides a `sequence` number. Increment it when pushing local changes to Google. If the remote `sequence` is higher, the remote won't accept your older update (optimistic locking). 3. **Strategy:** Typically "Last Write Wins" or "System of Record" (e.g., the SaaS UI overrides Google). --- ### 4. Webhooks & Push Notifications (Watch API) Instead of polling, use `watch` to receive push notifications. 1. **Setup:** Register a HTTPS endpoint. Domain must be verified in Google Search Console. 2. **Request:** Call `events.watch(calendarId, body={'id': 'channel-id', 'type': 'web_hooks', 'address': 'https://myapp.com/webhook'})`. 3. **Headers:** Webhooks contain `X-Goog-Resource-ID` and `X-Goog-Resource-State` (e.g., `exists`). 4. **Renewal:** Channels expire (default 1 week). You must track expiration and re-subscribe before they die. --- ### 5. CalDAV vs. REST API | Feature | REST API (Recommended) | CalDAV (RFC 4791) | | :--- | :--- | :--- | | **Ease of Use** | JSON-based, standard SDKs. | XML/WebDAV, heavy payload. | | **Richness** | Google-specific features (Meet links, colors). | Standard iCal fields only. | | **Use Case** | Most SaaS/Cloud apps. | Native desktop/mobile apps. | * **VTIMEZONE:** CalDAV requires explicit handling of VTIMEZONE components in `.ics` files. REST API handles this automatically via the `timeZone` string. --- ### 6. Common Use Cases 1. **Booking Systems:** Check `freebusy` -> Create `event` with `attendees` -> Listen for `watch` notifications if the user cancels in their calendar. 2. **Staff Scheduling:** Use a **Shared Calendar**. Assign `colorId` to differentiate between staff members or shifts. 3. **Reminders:** Use `reminders.overrides` to set custom push/email notifications for users. --- ### 7. Rate Limits & Quotas * **Daily Quota:** ~1,000,000 queries per day (standard). * **User Rate Limit:** ~10 requests per second per user. * **Error Handling:** Implement **Exponential Backoff** for `403 Rate Limit Exceeded` or `429 Too Many Requests`. --- ### 8. SDKs * **Node.js:** `npm install googleapis` * **Python:** `pip install google-api-python-client` * **Java:** `com.google.apis:google-api-services-calendar` --- ### 9. Critical "Gotchas" * **Time Zones:** Always specify `timeZone`. If omitted, Google assumes the calendar's default, which leads to drifting events. * **All-Day Events:** Use `start.date` and `end.date` (YYYY-MM-DD) instead of `dateTime`. The `end.date` is **exclusive** (e.g., an all-day event on Jan 1st ends on Jan 2nd). * **Attendee Limits:** Max 100 attendees for standard events; 2,000 for large events (requires special handling). * **Conference Data:** To generate a Google Meet link, you **must** pass `conferenceDataVersion=1` in the request parameters and include `createRequest` in the body. * **Color IDs:** You cannot use arbitrary hex codes. You must use the IDs returned by `colors.get` (e.g., ID "1" is Lavender). --- ### 10. Summary Implementation Check-list 1. [ ] Configure OAuth Scopes (prefer `calendar.events`). 2. [ ] Implement Token Refresh logic. 3. [ ] Set up `watch` channel for real-time updates. 4. [ ] Store `syncToken` and `eventId` locally. 5. [ ] Handle `410 Gone` for sync token resets. 6. [ ] Map local timezones to IANA strings. I've documented the core integration patterns for Google Calendar. Should I save this reference to your knowledge graph for future use?

Install

curl -s https://skills.skynet.ceo/api/skills/google-calendar-api/skill.md