Calendar Event Creation and Querying
Google Calendar API: listing events, creating meetings, setting reminders.
Calendar Event Creation and Querying is a free AI Agents lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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 addressListing 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 eventsParsing Event Start and End Times
Calendar events have two types of times: dateTime (specific time with timezone) for regular events and date (date only, no time) for all-day events. Always check which field exists before parsing.
from datetime import datetime
import re
def parse_event_time(time_dict):
if 'dateTime' in time_dict:
# Parse RFC 3339 datetime: '2026-05-29T14:00:00+03:00'
dt_str = time_dict['dateTime']
# Python 3.7+ fromisoformat handles this
return datetime.fromisoformat(dt_str), False # not all-day
else:
# All-day event: '2026-05-29'
date_str = time_dict['date']
return datetime.strptime(date_str, '%Y-%m-%d'), True # all-day
for event in events:
start_dt, is_all_day = parse_event_time(event['start'])
end_dt, _ = parse_event_time(event['end'])
duration = end_dt - start_dt if not is_all_day else None
print(f'{event["summary"]}: {start_dt.strftime("%H:%M")} '
f'({"all-day" if is_all_day else str(duration)})')Creating a Simple Event
Use service.events().insert() to create a new event. The minimum required fields are summary (title), start, and end. Times must be RFC 3339 format with timezone. The timeZone field in start/end specifies the timezone name.
def create_event(service, title, start_datetime, end_datetime,
description='', timezone='UTC', calendar_id='primary'):
event = {
'summary': title,
'description': description,
'start': {
'dateTime': start_datetime.isoformat(),
'timeZone': timezone
},
'end': {
'dateTime': end_datetime.isoformat(),
'timeZone': timezone
}
}
created = service.events().insert(
calendarId=calendar_id,
body=event
).execute()
print(f'Event created: {created["summary"]}')
print(f'Event ID: {created["id"]}')
print(f'Link: {created["htmlLink"]}')
return created
# --- demo: minimal stand-in for the Calendar API's service object ---
import datetime
class _Exec:
def __init__(self, result):
self._result = result
def execute(self):
return self._result
class _FakeEvents:
def insert(self, calendarId, body):
return _Exec({**body, 'id': 'evt_123',
'htmlLink': 'https://calendar.google.com/event?eid=evt_123'})
class _FakeService:
def events(self):
return _FakeEvents()
service = _FakeService()
start = datetime.datetime(2026, 8, 10, 9, 0)
end = start + datetime.timedelta(hours=1)
create_event(service, 'Team Sync', start, end, description='Weekly sync')
Adding Attendees to Events
Add attendees to an event by including an attendees list with email addresses. Set sendUpdates='all' to send Google Calendar invitations to all attendees automatically. Use 'externalOnly' to notify only external guests.
import datetime
def schedule_meeting(service, title, start_iso, duration_minutes,
attendees, description=''):
start = datetime.datetime.fromisoformat(start_iso)
end = start + datetime.timedelta(minutes=duration_minutes)
event = {
'summary': title,
'description': description,
'start': {'dateTime': start.isoformat(), 'timeZone': 'UTC'},
'end': {'dateTime': end.isoformat(), 'timeZone': 'UTC'},
'attendees': [
{'email': email} for email in attendees
],
'conferenceData': {
'createRequest': {'requestId': f'meet-{start.timestamp()}'}
} # creates a Google Meet link
}
created = service.events().insert(
calendarId='primary',
body=event,
sendUpdates='all', # send invites
conferenceDataVersion=1 # enable Meet link creation
).execute()
return created
# --- demo: minimal stand-in for the Calendar API's service object ---
class _Exec:
def __init__(self, result):
self._result = result
def execute(self):
return self._result
class _FakeEvents:
def insert(self, calendarId, body, sendUpdates=None, conferenceDataVersion=None):
return _Exec({**body, 'id': 'evt_456'})
class _FakeService:
def events(self):
return _FakeEvents()
service = _FakeService()
created = schedule_meeting(
service, 'Sprint Planning', '2026-08-11T10:00:00', 30,
attendees=['alice@example.com', 'bob@example.com']
)
print(f'Meeting scheduled: {created["summary"]}')
print(f'Attendees: {[a["email"] for a in created["attendees"]]}')
Adding Reminders to Events
Events can have reminders — notifications sent before the event. Use 'popup' for in-browser/app notifications and 'email' for email reminders. Set useDefault: False to override calendar defaults with custom timings.
def create_event_with_reminders(service, title, start_iso, end_iso):
event = {
'summary': title,
'start': {'dateTime': start_iso, 'timeZone': 'UTC'},
'end': {'dateTime': end_iso, 'timeZone': 'UTC'},
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60}, # 1 day before
{'method': 'popup', 'minutes': 30}, # 30 min before
{'method': 'popup', 'minutes': 10} # 10 min before
]
}
}
return service.events().insert(
calendarId='primary',
body=event
).execute()
# --- demo: minimal stand-in for the Calendar API's service object ---
class _Exec:
def __init__(self, result):
self._result = result
def execute(self):
return self._result
class _FakeEvents:
def insert(self, calendarId, body):
return _Exec({**body, 'id': 'evt_789'})
class _FakeService:
def events(self):
return _FakeEvents()
service = _FakeService()
created = create_event_with_reminders(
service, 'Deploy Review', '2026-08-12T15:00:00', '2026-08-12T15:30:00'
)
print(f'Event id: {created["id"]}')
print('Reminders:', created['reminders']['overrides'])
Creating Recurring Events
Recurring events use an RRULE (recurrence rule) string — the same format as iCalendar RFC 5545. Common rules: FREQ=WEEKLY;BYDAY=MO,WE,FR for Mon/Wed/Fri, FREQ=MONTHLY;BYDAY=1MO for the first Monday of each month.
def create_recurring_event(service, title, start_iso, end_iso,
rrule, timezone='UTC'):
event = {
'summary': title,
'start': {'dateTime': start_iso, 'timeZone': timezone},
'end': {'dateTime': end_iso, 'timeZone': timezone},
'recurrence': [
f'RRULE:{rrule}' # recurrence rule string
]
}
return service.events().insert(
calendarId='primary',
body=event
).execute()
# Weekly team standup every Monday at 9am for 30 min
create_recurring_event(
service=calendar_service,
title='Team Standup',
start_iso='2026-06-01T09:00:00',
end_iso='2026-06-01T09:30:00',
rrule='FREQ=WEEKLY;BYDAY=MO;COUNT=52', # 52 weeks
timezone='America/New_York'
)Updating an Existing Event
Use service.events().patch() to update specific fields of an existing event without replacing the whole event. Use .update() to replace the entire event body. Both require the event ID from the original create or list response.
def reschedule_event(service, event_id, new_start_iso, new_end_iso,
timezone='UTC', calendar_id='primary'):
updated_fields = {
'start': {'dateTime': new_start_iso, 'timeZone': timezone},
'end': {'dateTime': new_end_iso, 'timeZone': timezone}
}
updated_event = service.events().patch(
calendarId=calendar_id,
eventId=event_id,
body=updated_fields,
sendUpdates='all' # notify attendees of the change
).execute()
print(f'Event rescheduled: {updated_event["summary"]}')
print(f'New start: {updated_event["start"]["dateTime"]}')
return updated_event
# --- demo: minimal stand-in for the Calendar API's service object ---
class _Exec:
def __init__(self, result):
self._result = result
def execute(self):
return self._result
class _FakeEvents:
def patch(self, calendarId, eventId, body, sendUpdates=None):
return _Exec({'summary': 'Team Sync', 'id': eventId, **body})
class _FakeService:
def events(self):
return _FakeEvents()
service = _FakeService()
reschedule_event(service, 'evt_123', '2026-08-13T09:00:00', '2026-08-13T10:00:00')
Deleting Events
Use service.events().delete() to cancel and remove an event. Setting sendUpdates='all' notifies attendees. For recurring events, you can delete a single instance or the entire series depending on the event ID used.
from googleapiclient.errors import HttpError
def cancel_event(service, event_id, notify_attendees=True,
calendar_id='primary'):
try:
service.events().delete(
calendarId=calendar_id,
eventId=event_id,
sendUpdates='all' if notify_attendees else 'none'
).execute()
print(f'Event {event_id} cancelled')
return True
except HttpError as e:
if e.resp.status == 404:
print(f'Event {event_id} not found (already deleted?)')
elif e.resp.status == 403:
print('No permission to delete this event')
else:
print(f'Delete failed: {e.resp.status}')
return FalseChecking Free/Busy Availability
Before scheduling a meeting, check attendees' availability using the freebusy API. It returns busy time blocks for a list of calendars in a given time window — perfect for finding open slots for scheduling agents.
import datetime
import pytz
def check_availability(service, attendees, duration_hours=1):
now = datetime.datetime.now(pytz.utc)
time_min = now.isoformat()
time_max = (now + datetime.timedelta(days=5)).isoformat()
body = {
'timeMin': time_min,
'timeMax': time_max,
'timeZone': 'UTC',
'items': [{'id': email} for email in attendees]
}
result = service.freebusy().query(body=body).execute()
for email in attendees:
busy_slots = result['calendars'].get(email, {}).get('busy', [])
print(f'{email}: {len(busy_slots)} busy slots in next 5 days')
for slot in busy_slots[:3]:
print(f' Busy: {slot["start"]} -> {slot["end"]}')
return resultSearching Events by Query
Use the q parameter in events().list() to search events by text — the search covers title, description, location, and attendee names. Combine with timeMin/timeMax to narrow results to a specific period.
def search_events(service, query, days_back=30, days_forward=30,
calendar_id='primary'):
import datetime, pytz
now = datetime.datetime.now(pytz.utc)
result = service.events().list(
calendarId=calendar_id,
q=query,
timeMin=(now - datetime.timedelta(days=days_back)).isoformat(),
timeMax=(now + datetime.timedelta(days=days_forward)).isoformat(),
singleEvents=True,
orderBy='startTime',
maxResults=50
).execute()
events = result.get('items', [])
print(f'Found {len(events)} events matching "{query}"')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(f' {start}: {event["summary"]}')
return eventsQuick Check: singleEvents Parameter
Test your understanding of the Calendar API.
Calendar API Recap
Your agents can now manage Google Calendar programmatically:
- List events:
events().list(timeMin=now, singleEvents=True, orderBy='startTime') - Create events:
events().insert(body={summary, start, end, attendees}) - Recurring events: add
recurrence: ['RRULE:FREQ=WEEKLY;BYDAY=MO'] - Reminders: use
reminders.overrideswithmethod: popup/emailandminutes - Update:
events().patch()for partial updates;sendUpdates='all'to notify attendees - Free/busy:
freebusy().query()to check availability before scheduling
Frequently asked questions
Is the “Calendar Event Creation and Querying” lesson free?
Yes — the full text of “Calendar Event Creation and Querying” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.
What will I learn in “Calendar Event Creation and Querying”?
Google Calendar API: listing events, creating meetings, setting reminders. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Agents?
No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Calendar Event Creation and Querying” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Agents lesson?
Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Connecting to Gmail via the API
- Reading and Sending Emails Programmatically
- Calendar Event Creation and Querying
- Building a Simple Email Assistant Agent