Outlook Calendar: Synchronize a Calendar View with Delta Queries
See more Outlook Calendar Examples
Build a local view of the default calendar for a fixed 30-day window, then retrieve changes on later runs. The first request uses /me/calendarView/delta. Each page can include new or updated events and @removed tombstones. Keep IDs as strings. This example stores a small projection (subject, type, start, end) under JSON-safe hash keys, retaining the original ID in each record. Repeated changes overwrite the same record; records with removed=true are tombstones to exclude from the local view. It is a demonstration cache, not a complete event archive.
The checkpoint saves the local data, original window and exact nextLink or deltaLink together. Follow these opaque URLs without adding or rebuilding query parameters, and send the same Prefer header on every request. Do not use $select with calendarView delta. The v1.0 API tracks the primary calendar. A removed item should be removed from this local date-range view; it does not always mean the event was globally deleted. Preserve omitted fields on partial updates.
Use one writer and a separate protected cache per account, window and ID preference. An intermediate nextLink resumes an unfinished round; a deltaLink starts the next round for the same fixed window. A moving agenda needs a new baseline when its window changes. HTTP 410 or a sync-state error requires a new full synchronization and deliberate reconciliation of the old view, not an endless retry of the rejected token.
Validation and HTTP failures do not advance the saved cursor. Before replacing a checkpoint, the example saves a backup containing the previous matching data and cursor. Recover that pair if the main file is damaged; replaying a page is safe for these upserts and tombstones. Production applications should commit the data and cursor atomically in a database transaction or equivalent storage operation. The 100-page limit saves a continuation before pausing.
Delegated permission: Calendars.Read.
Uses Microsoft Graph v1.0 in the global cloud with a delegated access token saved by the calendar OAuth2 example. Both personal Outlook.com accounts and Microsoft 365 work/school accounts with a mailbox can use this flow. The app registration must support the selected account type. A token for SMTP/IMAP/POP or another API is not a Graph token.
/me means the signed-in user and requires delegated authentication. An unattended Microsoft 365 service instead needs application permissions and administrator consent, and addresses an explicit mailbox through /users/{id-or-userPrincipalName}. That client-credentials flow does not apply to personal Outlook.com accounts. These samples target the global cloud; national clouds use different authority and Graph hosts.
HTTP methods can return false for an HTTP error as well as a connection failure. The code distinguishes those cases and checks the expected status before reading JSON. For 401, refresh the access token or authorize again; for 403, check permissions, mailbox access, and tenant policy. For 429, honor Retry-After before a bounded retry. Do not automatically repeat a write after an uncertain outcome. Keep detailed errors and calendar data private.
Chilkat Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Obtain a delegated Microsoft Graph token using the calendar authorization example.
-- See Authorize Outlook Calendar with OAuth2 and PKCE.
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load_file("qa_data/tokens/outlookCalendar.json")
if not success then
print("Could not read the private calendar token cache.")
return
end
if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
print("Expected a nonempty access_token in the JSON.")
return
end
local http = chilkat.Http.new()
http.auth_token = token:string_of("access_token")
http.require_ssl_cert_verify = true
http.follow_redirects = false
http.connect_timeout = 20
http.read_timeout = 30
http:set_request_header("Accept", "application/json")
local resp = chilkat.HttpResponse.new()
local result = chilkat.JsonObject.new()
result.strict = true
http:set_request_header("Prefer", "outlook.timezone=\"UTC\", IdType=\"ImmutableId\", odata.maxpagesize=50")
local fac = chilkat.FileAccess.new()
success = fac:dir_ensure_exists("qa_data/outlookCalendar")
if not success then
print("Could not create the private synchronization directory.")
return
end
local cachePath = "qa_data/outlookCalendar/calendar-sync.json"
local backupPath = "qa_data/outlookCalendar/calendar-sync.json.bak"
local state = chilkat.JsonObject.new()
state.strict = true
if fac:file_exists(cachePath) then
success = state:load_file(cachePath)
if not success then
print("Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.")
return
end
if (state:json_type_of("resumeUrl") ~= 1) or (state:string_of_equals("resumeUrl", "", true)) then
print("Expected a nonempty resumeUrl in the JSON.")
return
end
if (state:json_type_of("startDateTime") ~= 1) or (state:string_of_equals("startDateTime", "", true)) then
print("Expected a nonempty startDateTime in the JSON.")
return
end
if (state:json_type_of("endDateTime") ~= 1) or (state:string_of_equals("endDateTime", "", true)) then
print("Expected a nonempty endDateTime in the JSON.")
return
end
if state:json_type_of("items") ~= 3 then
print("Expected an items object in the checkpoint.")
return
end
else
local windowTime = chilkat.DateTime.new()
success = windowTime:set_from_current_system_time()
if not success then
print("Could not get the current time.")
return
end
local windowStart = windowTime:get_as_timestamp(false)
success = windowTime:add_days(30)
if not success then
print("Could not calculate the window end.")
return
end
local windowEnd = windowTime:get_as_timestamp(false)
local endpoint = chilkat.StringBuilder.new()
endpoint:append("https://graph.microsoft.com/v1.0/me/calendarView/delta?startDateTime=")
endpoint:append(http:url_encode(windowStart))
endpoint:append("&endDateTime=")
endpoint:append(http:url_encode(windowEnd))
state:update_string("startDateTime", windowStart)
state:update_string("endDateTime", windowEnd)
state:update_string("resumeUrl", endpoint:get_as_string())
state:update_new_object("items")
end
local hash = chilkat.Crypt2.new()
hash.hash_algorithm = "sha256"
hash.charset = "utf-8"
hash.encoding_mode = "hex"
local link = chilkat.StringBuilder.new()
local itemPath = chilkat.StringBuilder.new()
local seenLinks = chilkat.Hashtable.new()
local previous = chilkat.JsonObject.new()
previous.strict = true
local pageCount = 0
while pageCount < 100 do
local url = state:string_of("resumeUrl")
link:clear()
link:append(url)
if not link:starts_with("https://graph.microsoft.com/v1.0/", true) then
print("Unexpected continuation host or API version; no request sent.")
return
end
if seenLinks:contains(url) then
print("Repeated continuation URL; stopping.")
return
end
seenLinks:add_int(url, 1)
success = http:http_no_body("GET", url, resp)
-- A false result can still include an HTTP error response.
if (not success) and (resp.status_code == 0) then
print("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.")
return
end
if resp.status_code ~= 200 then
print("Unexpected HTTP status: " .. resp.status_code)
print("Request ID: " .. resp:get_header_field("request-id"))
if resp.status_code == 429 then
print("Retry-After: " .. resp:get_header_field("Retry-After"))
end
if resp.status_code == 401 then
print("Refresh the Graph access token or authorize again.")
end
return
end
success = result:load(resp.body_str)
if not success then
print("Expected a well-formed JSON response.")
return
end
if result:json_type_of("value") ~= 4 then
print("Expected a value array; checkpoint unchanged.")
return
end
-- Exactly one continuation member must be a nonempty string.
local nextType = result:json_type_of("\"@odata.nextLink\"")
local deltaType = result:json_type_of("\"@odata.deltaLink\"")
local finished = false
local resumeUrl = ""
if (nextType == 1) and (deltaType == (-1)) then
resumeUrl = result:string_of("\"@odata.nextLink\"")
else
if (deltaType ~= 1) or (nextType ~= (-1)) then
print("Invalid delta continuation; checkpoint unchanged.")
return
end
resumeUrl = result:string_of("\"@odata.deltaLink\"")
finished = true
end
link:clear()
link:append(resumeUrl)
if not link:starts_with("https://graph.microsoft.com/v1.0/", true) then
print("Invalid continuation URL; checkpoint unchanged.")
return
end
success = previous:load(state:emit())
if not success then
print("Could not snapshot the previous checkpoint.")
return
end
local i = 0
while i < result:size_of_array("value") do
result.i = i
if (result:json_type_of("value[i].id") ~= 1) or (result:string_of_equals("value[i].id", "", true)) then
print("Expected a nonempty value[i].id in the JSON.")
return
end
local eventId = result:string_of("value[i].id")
local itemKey = hash:hash_string_enc(eventId)
if not hash.last_method_success then
print("Could not form a local record key.")
return
end
-- Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
itemPath:clear()
itemPath:append("items.")
itemPath:append(itemKey)
if state:json_type_of(itemPath:get_as_string()) ~= 3 then
state:update_new_object(itemPath:get_as_string())
end
itemPath:append(".")
state.path_prefix = itemPath:get_as_string()
state:update_string("id", eventId)
if result:json_type_of("value[i].@removed") == 3 then
-- Hide records with removed=true from the local date-range view.
state:update_bool("removed", true)
print("Removed from the local view: " .. eventId)
else
state:update_bool("removed", false)
if result:json_type_of("value[i].subject") == 1 then
state:update_string("subject", result:string_of("value[i].subject"))
end
if result:json_type_of("value[i].type") == 1 then
state:update_string("type", result:string_of("value[i].type"))
end
if result:json_type_of("value[i].start.dateTime") == 1 then
state:update_string("start.dateTime", result:string_of("value[i].start.dateTime"))
end
if result:json_type_of("value[i].start.timeZone") == 1 then
state:update_string("start.timeZone", result:string_of("value[i].start.timeZone"))
end
if result:json_type_of("value[i].end.dateTime") == 1 then
state:update_string("end.dateTime", result:string_of("value[i].end.dateTime"))
end
if result:json_type_of("value[i].end.timeZone") == 1 then
state:update_string("end.timeZone", result:string_of("value[i].end.timeZone"))
end
state.path_prefix = ""
print("Updated local event: " .. eventId)
end
state.path_prefix = ""
i = i + 1
end
state:update_string("resumeUrl", resumeUrl)
state:update_bool("roundComplete", finished)
-- Save the data and cursor in one document. The backup contains the matching previous pair.
success = previous:write_file(backupPath)
if not success then
print("Could not back up the previous checkpoint; no replacement attempted.")
return
end
success = state:write_file(cachePath)
if not success then
print("Checkpoint write failed. Restore the private .bak before continuing.")
return
end
pageCount = pageCount + 1
if finished then
print("Synchronization round complete; saved the delta link for the next run.")
return
end
end
print("Paused after 100 pages; the saved nextLink resumes on the next run.")