0PricingLogin
AI Agents · Lesson

Calendar Event Creation and Querying

Google Calendar API: listing events, creating meetings, setting reminders.

Google Calendar API Overview

The Google Calendar API lets agents read, create, update, and delete calendar events. It uses the same Google OAuth authentication as Gmail. The primary resource is the Event object, and events belong to a Calendar. The 'primary' calendar ID refers to the authenticated user's main calendar.

from googleapiclient.discovery import build

# Build calendar service (same credentials as Gmail)
calendar = build(
    'calendar', 'v3',
    credentials=creds,
    cache_discovery=False
)

# Get a list of the user's calendars
cal_list = calendar.calendarList().list().execute()
for cal in cal_list.get('items', []):
    print(f'{cal["summary"]}: {cal["id"]}')
    # Primary calendar ID is the user's email address

Listing Upcoming Events

Use service.events().list() to retrieve events. The timeMin and timeMax parameters filter by time range. Always use RFC 3339 datetime strings with a timezone offset. Set singleEvents=True to expand recurring events into individual instances.

import datetime
import pytz

def get_upcoming_events(service, calendar_id='primary', max_results=10):
    now = datetime.datetime.now(pytz.utc)
    time_min = now.isoformat()  # RFC 3339 format
    time_max = (now + datetime.timedelta(days=7)).isoformat()

    events_result = service.events().list(
        calendarId=calendar_id,
        timeMin=time_min,
        timeMax=time_max,
        maxResults=max_results,
        singleEvents=True,      # expand recurring events
        orderBy='startTime'
    ).execute()

    events = events_result.get('items', [])
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        print(f'{start}: {event["summary"]}')

    return events

All lessons in this course

  1. Connecting to Gmail via the API
  2. Reading and Sending Emails Programmatically
  3. Calendar Event Creation and Querying
  4. Building a Simple Email Assistant Agent
← Back to AI Agents