Sample code for 30+ languages & platforms
AutoIt Requires Chilkat v11.6.0+

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.

Microsoft documentation

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

;  Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
;  Obtain a delegated Microsoft Graph token using the calendar authorization example.
;  See Authorize Outlook Calendar with OAuth2 and PKCE.
$oToken = ObjCreate("Chilkat.JsonObject")
$oToken.Strict = True
$bSuccess = $oToken.LoadFile("qa_data/tokens/outlookCalendar.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not read the private calendar token cache." & @CRLF)
    Exit
EndIf

If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
    ConsoleWrite("Expected a nonempty access_token in the JSON." & @CRLF)
    Exit
EndIf

$oHttp = ObjCreate("Chilkat.Http")
$oHttp.AuthToken = $oToken.StringOf("access_token")
$oHttp.RequireSslCertVerify = True
$oHttp.FollowRedirects = False
$oHttp.ConnectTimeout = 20
$oHttp.ReadTimeout = 30
$oHttp.SetRequestHeader "Accept","application/json"
$oResp = ObjCreate("Chilkat.HttpResponse")
$oResult = ObjCreate("Chilkat.JsonObject")
$oResult.Strict = True
$oHttp.SetRequestHeader "Prefer","outlook.timezone=""UTC"", IdType=""ImmutableId"", odata.maxpagesize=50"
$oFac = ObjCreate("Chilkat.FileAccess")
$bSuccess = $oFac.DirEnsureExists("qa_data/outlookCalendar")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not create the private synchronization directory." & @CRLF)
    Exit
EndIf

Local $sCachePath = "qa_data/outlookCalendar/calendar-sync.json"
Local $sBackupPath = "qa_data/outlookCalendar/calendar-sync.json.bak"
$oState = ObjCreate("Chilkat.JsonObject")
$oState.Strict = True
If ($oFac.FileExists($sCachePath) = True) Then
    $bSuccess = $oState.LoadFile($sCachePath)
    If ($bSuccess <> True) Then
        ConsoleWrite("Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing." & @CRLF)
        Exit
    EndIf

    If (($oState.JsonTypeOf("resumeUrl") <> 1) Or ($oState.StringOfEquals("resumeUrl","",True) = True)) Then
        ConsoleWrite("Expected a nonempty resumeUrl in the JSON." & @CRLF)
        Exit
    EndIf

    If (($oState.JsonTypeOf("startDateTime") <> 1) Or ($oState.StringOfEquals("startDateTime","",True) = True)) Then
        ConsoleWrite("Expected a nonempty startDateTime in the JSON." & @CRLF)
        Exit
    EndIf

    If (($oState.JsonTypeOf("endDateTime") <> 1) Or ($oState.StringOfEquals("endDateTime","",True) = True)) Then
        ConsoleWrite("Expected a nonempty endDateTime in the JSON." & @CRLF)
        Exit
    EndIf

    If ($oState.JsonTypeOf("items") <> 3) Then
        ConsoleWrite("Expected an items object in the checkpoint." & @CRLF)
        Exit
    EndIf

Else
    $oWindowTime = ObjCreate("Chilkat.CkDateTime")
    $bSuccess = $oWindowTime.SetFromCurrentSystemTime()
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not get the current time." & @CRLF)
        Exit
    EndIf

Local $sWindowStart = $oWindowTime.GetAsTimestamp(False)
    $bSuccess = $oWindowTime.AddDays(30)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not calculate the window end." & @CRLF)
        Exit
    EndIf

Local $sWindowEnd = $oWindowTime.GetAsTimestamp(False)
    $oEndpoint = ObjCreate("Chilkat.StringBuilder")
    $oEndpoint.Append("https://graph.microsoft.com/v1.0/me/calendarView/delta?startDateTime=")
    $oEndpoint.Append($oHttp.UrlEncode($sWindowStart))
    $oEndpoint.Append("&endDateTime=")
    $oEndpoint.Append($oHttp.UrlEncode($sWindowEnd))
    $oState.UpdateString("startDateTime",$sWindowStart)
    $oState.UpdateString("endDateTime",$sWindowEnd)
    $oState.UpdateString("resumeUrl",$oEndpoint.GetAsString())
    $oState.UpdateNewObject("items")
EndIf

$oHash = ObjCreate("Chilkat.Crypt2")
$oHash.HashAlgorithm = "sha256"
$oHash.Charset = "utf-8"
$oHash.EncodingMode = "hex"
$oLink = ObjCreate("Chilkat.StringBuilder")
$oItemPath = ObjCreate("Chilkat.StringBuilder")
$oSeenLinks = ObjCreate("Chilkat.Hashtable")
$oPrevious = ObjCreate("Chilkat.JsonObject")
$oPrevious.Strict = True
Local $iPageCount = 0
While ($iPageCount < 100)
Local $sUrl = $oState.StringOf("resumeUrl")
    $oLink.Clear 
    $oLink.Append($sUrl)
    If ($oLink.StartsWith("https://graph.microsoft.com/v1.0/",True) <> True) Then
        ConsoleWrite("Unexpected continuation host or API version; no request sent." & @CRLF)
        Exit
    EndIf

    If ($oSeenLinks.Contains($sUrl) = True) Then
        ConsoleWrite("Repeated continuation URL; stopping." & @CRLF)
        Exit
    EndIf

    $oSeenLinks.AddInt($sUrl,1)
    $bSuccess = $oHttp.HttpNoBody("GET",$sUrl,$oResp)
    ;  A false result can still include an HTTP error response.
    If (($bSuccess <> True) And ($oResp.StatusCode = 0)) Then
        ConsoleWrite("No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying." & @CRLF)
        Exit
    EndIf

    If ($oResp.StatusCode <> 200) Then
        ConsoleWrite("Unexpected HTTP status: " & $oResp.StatusCode & @CRLF)
        ConsoleWrite("Request ID: " & $oResp.GetHeaderField("request-id") & @CRLF)
        If ($oResp.StatusCode = 429) Then
            ConsoleWrite("Retry-After: " & $oResp.GetHeaderField("Retry-After") & @CRLF)
        EndIf

        If ($oResp.StatusCode = 401) Then
            ConsoleWrite("Refresh the Graph access token or authorize again." & @CRLF)
        EndIf

        Exit
    EndIf

    $bSuccess = $oResult.Load($oResp.BodyStr)
    If ($bSuccess <> True) Then
        ConsoleWrite("Expected a well-formed JSON response." & @CRLF)
        Exit
    EndIf

    If ($oResult.JsonTypeOf("value") <> 4) Then
        ConsoleWrite("Expected a value array; checkpoint unchanged." & @CRLF)
        Exit
    EndIf

    ;  Exactly one continuation member must be a nonempty string.
Local $iNextType = $oResult.JsonTypeOf("""@odata.nextLink""")
Local $iDeltaType = $oResult.JsonTypeOf("""@odata.deltaLink""")
Local $bFinished = False
Local $sResumeUrl
    If (($iNextType = 1) And ($iDeltaType = -1)) Then
        $sResumeUrl = $oResult.StringOf("""@odata.nextLink""")
    Else
        If (($iDeltaType <> 1) Or ($iNextType <> -1)) Then
            ConsoleWrite("Invalid delta continuation; checkpoint unchanged." & @CRLF)
            Exit
        EndIf

        $sResumeUrl = $oResult.StringOf("""@odata.deltaLink""")
        $bFinished = True
    EndIf

    $oLink.Clear 
    $oLink.Append($sResumeUrl)
    If ($oLink.StartsWith("https://graph.microsoft.com/v1.0/",True) <> True) Then
        ConsoleWrite("Invalid continuation URL; checkpoint unchanged." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oPrevious.Load($oState.Emit())
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not snapshot the previous checkpoint." & @CRLF)
        Exit
    EndIf

Local $i = 0
    While ($i < $oResult.SizeOfArray("value"))
        $oResult.I = $i
        If (($oResult.JsonTypeOf("value[i].id") <> 1) Or ($oResult.StringOfEquals("value[i].id","",True) = True)) Then
            ConsoleWrite("Expected a nonempty value[i].id in the JSON." & @CRLF)
            Exit
        EndIf

Local $sEventId = $oResult.StringOf("value[i].id")
Local $sItemKey = $oHash.HashStringENC($sEventId)
        If ($oHash.LastMethodSuccess <> True) Then
            ConsoleWrite("Could not form a local record key." & @CRLF)
            Exit
        EndIf

        ;  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        $oItemPath.Clear 
        $oItemPath.Append("items.")
        $oItemPath.Append($sItemKey)
        If ($oState.JsonTypeOf($oItemPath.GetAsString()) <> 3) Then
            $oState.UpdateNewObject($oItemPath.GetAsString())
        EndIf

        $oItemPath.Append(".")
        $oState.PathPrefix = $oItemPath.GetAsString()
        $oState.UpdateString("id",$sEventId)
        If ($oResult.JsonTypeOf("value[i].@removed") = 3) Then
            ;  Hide records with removed=true from the local date-range view.
            $oState.UpdateBool("removed",True)
            ConsoleWrite("Removed from the local view: " & $sEventId & @CRLF)
        Else
            $oState.UpdateBool("removed",False)
            If ($oResult.JsonTypeOf("value[i].subject") = 1) Then
                $oState.UpdateString("subject",$oResult.StringOf("value[i].subject"))
            EndIf

            If ($oResult.JsonTypeOf("value[i].type") = 1) Then
                $oState.UpdateString("type",$oResult.StringOf("value[i].type"))
            EndIf

            If ($oResult.JsonTypeOf("value[i].start.dateTime") = 1) Then
                $oState.UpdateString("start.dateTime",$oResult.StringOf("value[i].start.dateTime"))
            EndIf

            If ($oResult.JsonTypeOf("value[i].start.timeZone") = 1) Then
                $oState.UpdateString("start.timeZone",$oResult.StringOf("value[i].start.timeZone"))
            EndIf

            If ($oResult.JsonTypeOf("value[i].end.dateTime") = 1) Then
                $oState.UpdateString("end.dateTime",$oResult.StringOf("value[i].end.dateTime"))
            EndIf

            If ($oResult.JsonTypeOf("value[i].end.timeZone") = 1) Then
                $oState.UpdateString("end.timeZone",$oResult.StringOf("value[i].end.timeZone"))
            EndIf

            $oState.PathPrefix = ""
            ConsoleWrite("Updated local event: " & $sEventId & @CRLF)
        EndIf

        $oState.PathPrefix = ""
        $i = $i + 1
    Wend
    $oState.UpdateString("resumeUrl",$sResumeUrl)
    $oState.UpdateBool("roundComplete",$bFinished)
    ;  Save the data and cursor in one document. The backup contains the matching previous pair.
    $bSuccess = $oPrevious.WriteFile($sBackupPath)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not back up the previous checkpoint; no replacement attempted." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oState.WriteFile($sCachePath)
    If ($bSuccess <> True) Then
        ConsoleWrite("Checkpoint write failed. Restore the private .bak before continuing." & @CRLF)
        Exit
    EndIf

    $iPageCount = $iPageCount + 1
    If ($bFinished = True) Then
        ConsoleWrite("Synchronization round complete; saved the delta link for the next run." & @CRLF)
        Exit
    EndIf

Wend
ConsoleWrite("Paused after 100 pages; the saved nextLink resumes on the next run." & @CRLF)