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

Outlook Contacts: Synchronize Contacts in a Folder with Delta Queries

See more Outlook Contact Examples

Build a local contact projection for one folder, then retrieve incremental changes on later runs. Supply a folder ID from folder enumeration or a contact's parentFolderId. This uses /me/contactFolders/{id}/contacts/delta, not a calendar-style date window. The initial $select requests id, displayName, emailAddresses, and mobilePhone. The saved projection is not a full contact archive.

Follow exact nextLink URLs within a round; save the final deltaLink for the next round. Do not rebuild opaque tokens or re-add query options. Preserve the same ID preference and field selection. Contact IDs remain strings; their hashes are only JSON-safe local keys. @removed records are tombstones (removed=true) to exclude from this local folder view. A removal can reflect a move out of the folder, not necessarily a global deletion. Repeated changes update the same record; omitted fields are retained, explicit nulls clear scalar values, and present email arrays replace the saved array.

The checkpoint stores contact data and the continuation URL together, with a backup of the previous matching pair before replacement. HTTP/validation failures do not advance it. If the main file is damaged, recover the private .bak pair. Replaying a page is safe for these upserts and tombstones. Production storage should atomically commit data and cursor. Use one writer and a separate cache for each account/folder/projection. The sample rejects a different folder ID and pauses after 100 pages with its nextLink saved. A rejected or expired sync state requires a new baseline and deliberate reconciliation of the old view.

Delegated permission: Contacts.Read.

Uses Microsoft Graph v1.0 for contacts stored in an Outlook.com or Microsoft 365 mailbox. These are personal mailbox contacts, not Microsoft Entra directory users, organizational contacts (/contacts), or the People API. Obtain a delegated token with the contacts OAuth2 example; the cache is qa_data/tokens/outlookContacts.json. A token for Calendar, SMTP, or another resource without the needed Graph contacts permission is insufficient.

/me requires a signed-in user. An authorized unattended Microsoft 365 application instead needs application permissions and administrator consent, and targets /users/{id-or-UPN}. App-only access does not apply to personal Outlook.com mailboxes. Shared folders require actual sharing rights and Contacts.Read.Shared or Contacts.ReadWrite.Shared delegated consent. The examples target the global cloud.

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 contact data private.

Microsoft documentation

Chilkat PowerBuilder Downloads

PowerBuilder
integer li_rc
long li_Success
oleobject loo_Token
oleobject loo_Http
oleobject loo_Resp
oleobject loo_Result
string ls_FolderId
oleobject loo_Fac
string ls_CachePath
string ls_BackupPath
oleobject loo_State
oleobject loo_Endpoint
oleobject loo_Hash
oleobject loo_Link
oleobject loo_ItemPath
oleobject loo_SeenLinks
oleobject loo_Previous
long li_PageCount
string ls_Url
long li_NextType
long li_DeltaType
long li_Finished
string ls_ResumeUrl
long i
string ls_ContactId
string ls_ItemKey
long li_DisplayNameType
long li_MobilePhoneType
long li_EmailType
long j

li_Success = 0

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
//  Obtain a delegated Microsoft Graph token using the contacts authorization example.
//  See Authorize Outlook Contacts with OAuth2 and PKCE.
loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
    destroy loo_Token
    MessageBox("Error","Connecting to COM object failed")
    return
end if
loo_Token.Strict = 1
li_Success = loo_Token.LoadFile("qa_data/tokens/outlookContacts.json")
if li_Success <> 1 then
    Write-Debug "Could not read the private contacts token cache."
    destroy loo_Token
    return
end if

if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
    Write-Debug "Expected a nonempty access_token in the JSON."
    destroy loo_Token
    return
end if

loo_Http = create oleobject
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")

loo_Http.AuthToken = loo_Token.StringOf("access_token")
loo_Http.RequireSslCertVerify = 1
loo_Http.FollowRedirects = 0
loo_Http.ConnectTimeout = 20
loo_Http.ReadTimeout = 30
loo_Http.SetRequestHeader("Accept","application/json")
loo_Resp = create oleobject
li_rc = loo_Resp.ConnectToNewObject("Chilkat.HttpResponse")

loo_Result = create oleobject
li_rc = loo_Result.ConnectToNewObject("Chilkat.JsonObject")

loo_Result.Strict = 1
loo_Http.SetRequestHeader("Prefer","IdType=~"ImmutableId~", odata.maxpagesize=50")
ls_FolderId = "YOUR_CONTACT_FOLDER_ID"
loo_Fac = create oleobject
li_rc = loo_Fac.ConnectToNewObject("Chilkat.FileAccess")

li_Success = loo_Fac.DirEnsureExists("qa_data/outlookContacts")
if li_Success <> 1 then
    Write-Debug "Could not create the private synchronization directory."
    destroy loo_Token
    destroy loo_Http
    destroy loo_Resp
    destroy loo_Result
    destroy loo_Fac
    return
end if

ls_CachePath = "qa_data/outlookContacts/contacts-sync.json"
ls_BackupPath = "qa_data/outlookContacts/contacts-sync.json.bak"
loo_State = create oleobject
li_rc = loo_State.ConnectToNewObject("Chilkat.JsonObject")

loo_State.Strict = 1
if loo_Fac.FileExists(ls_CachePath) = 1 then
    li_Success = loo_State.LoadFile(ls_CachePath)
    if li_Success <> 1 then
        Write-Debug "Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

    if (loo_State.JsonTypeOf("resumeUrl") <> 1) OR (loo_State.StringOfEquals("resumeUrl","",1) = 1) then
        Write-Debug "Expected a nonempty resumeUrl in the JSON."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

    if (loo_State.JsonTypeOf("folderId") <> 1) OR (loo_State.StringOfEquals("folderId","",1) = 1) then
        Write-Debug "Expected a nonempty folderId in the JSON."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

    if loo_State.StringOfEquals("folderId",ls_FolderId,1) <> 1 then
        Write-Debug "This checkpoint belongs to another folder. Use a separate cache."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

    if loo_State.JsonTypeOf("items") <> 3 then
        Write-Debug "Expected an items object in the checkpoint."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        return
    end if

else
    loo_Endpoint = create oleobject
    li_rc = loo_Endpoint.ConnectToNewObject("Chilkat.StringBuilder")

    loo_Endpoint.Append("https://graph.microsoft.com/v1.0/me/contactFolders/")
    loo_Endpoint.Append(loo_Http.UrlEncode(ls_FolderId))
    loo_Endpoint.Append("/contacts/delta?$select=id,displayName,emailAddresses,mobilePhone")
    loo_State.UpdateString("folderId",ls_FolderId)
    loo_State.UpdateString("resumeUrl",loo_Endpoint.GetAsString())
    loo_State.UpdateNewObject("items")
end if

loo_Hash = create oleobject
li_rc = loo_Hash.ConnectToNewObject("Chilkat.Crypt2")

loo_Hash.HashAlgorithm = "sha256"
loo_Hash.Charset = "utf-8"
loo_Hash.EncodingMode = "hex"
loo_Link = create oleobject
li_rc = loo_Link.ConnectToNewObject("Chilkat.StringBuilder")

loo_ItemPath = create oleobject
li_rc = loo_ItemPath.ConnectToNewObject("Chilkat.StringBuilder")

loo_SeenLinks = create oleobject
li_rc = loo_SeenLinks.ConnectToNewObject("Chilkat.Hashtable")

loo_Previous = create oleobject
li_rc = loo_Previous.ConnectToNewObject("Chilkat.JsonObject")

loo_Previous.Strict = 1
li_PageCount = 0
do while (li_PageCount < 100)
    ls_Url = loo_State.StringOf("resumeUrl")
    loo_Link.Clear()
    loo_Link.Append(ls_Url)
    if loo_Link.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1 then
        Write-Debug "Unexpected continuation host or API version; no request sent."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    if loo_SeenLinks.Contains(ls_Url) = 1 then
        Write-Debug "Repeated continuation URL; stopping."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    loo_SeenLinks.AddInt(ls_Url,1)
    li_Success = loo_Http.HttpNoBody("GET",ls_Url,loo_Resp)
    //  A false result can still include an HTTP error response.
    if (li_Success <> 1) AND (loo_Resp.StatusCode = 0) then
        Write-Debug "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    if loo_Resp.StatusCode <> 200 then
        Write-Debug "Unexpected HTTP status: " + string(loo_Resp.StatusCode)
        Write-Debug "Request ID: " + loo_Resp.GetHeaderField("request-id")
        if loo_Resp.StatusCode = 429 then
            Write-Debug "Retry-After: " + loo_Resp.GetHeaderField("Retry-After")
        end if

        if loo_Resp.StatusCode = 401 then
            Write-Debug "Refresh the Graph access token or authorize again."
        end if

        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    li_Success = loo_Result.Load(loo_Resp.BodyStr)
    if li_Success <> 1 then
        Write-Debug "Expected a well-formed JSON response."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    if loo_Result.JsonTypeOf("value") <> 4 then
        Write-Debug "Expected a value array; checkpoint unchanged."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    //  Exactly one continuation member must be a nonempty string.
    li_NextType = loo_Result.JsonTypeOf("~"@odata.nextLink~"")
    li_DeltaType = loo_Result.JsonTypeOf("~"@odata.deltaLink~"")
    li_Finished = 0

    if (li_NextType = 1) AND (li_DeltaType = -1) then
        ls_ResumeUrl = loo_Result.StringOf("~"@odata.nextLink~"")
    else
        if (li_DeltaType <> 1) OR (li_NextType <> -1) then
            Write-Debug "Invalid delta continuation; checkpoint unchanged."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Result
            destroy loo_Fac
            destroy loo_State
            destroy loo_Endpoint
            destroy loo_Hash
            destroy loo_Link
            destroy loo_ItemPath
            destroy loo_SeenLinks
            destroy loo_Previous
            return
        end if

        ls_ResumeUrl = loo_Result.StringOf("~"@odata.deltaLink~"")
        li_Finished = 1
    end if

    loo_Link.Clear()
    loo_Link.Append(ls_ResumeUrl)
    if loo_Link.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1 then
        Write-Debug "Invalid continuation URL; checkpoint unchanged."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    li_Success = loo_Previous.Load(loo_State.Emit())
    if li_Success <> 1 then
        Write-Debug "Could not snapshot the previous checkpoint."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    i = 0
    do while (i < loo_Result.SizeOfArray("value"))
        loo_Result.I = i
        if (loo_Result.JsonTypeOf("value[i].id") <> 1) OR (loo_Result.StringOfEquals("value[i].id","",1) = 1) then
            Write-Debug "Expected a nonempty value[i].id in the JSON."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Result
            destroy loo_Fac
            destroy loo_State
            destroy loo_Endpoint
            destroy loo_Hash
            destroy loo_Link
            destroy loo_ItemPath
            destroy loo_SeenLinks
            destroy loo_Previous
            return
        end if

        ls_ContactId = loo_Result.StringOf("value[i].id")
        ls_ItemKey = loo_Hash.HashStringENC(ls_ContactId)
        if loo_Hash.LastMethodSuccess <> 1 then
            Write-Debug "Could not form a local record key."
            destroy loo_Token
            destroy loo_Http
            destroy loo_Resp
            destroy loo_Result
            destroy loo_Fac
            destroy loo_State
            destroy loo_Endpoint
            destroy loo_Hash
            destroy loo_Link
            destroy loo_ItemPath
            destroy loo_SeenLinks
            destroy loo_Previous
            return
        end if

        //  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        loo_ItemPath.Clear()
        loo_ItemPath.Append("items.")
        loo_ItemPath.Append(ls_ItemKey)
        if loo_State.JsonTypeOf(loo_ItemPath.GetAsString()) <> 3 then
            loo_State.UpdateNewObject(loo_ItemPath.GetAsString())
        end if

        loo_ItemPath.Append(".")
        loo_State.PathPrefix = loo_ItemPath.GetAsString()
        loo_State.UpdateString("id",ls_ContactId)
        if loo_Result.JsonTypeOf("value[i].@removed") = 3 then
            //  Hide records with removed=true from the local folder view.
            loo_State.UpdateBool("removed",1)
            Write-Debug "Removed from the local view: " + ls_ContactId
        else
            loo_State.UpdateBool("removed",0)
            li_DisplayNameType = loo_Result.JsonTypeOf("value[i].displayName")
            if li_DisplayNameType = 1 then
                loo_State.UpdateString("displayName",loo_Result.StringOf("value[i].displayName"))
            else
                if li_DisplayNameType = 6 then
                    loo_State.UpdateNull("displayName")
                else
                    if li_DisplayNameType <> -1 then
                        Write-Debug "Invalid contact field; checkpoint unchanged."
                        destroy loo_Token
                        destroy loo_Http
                        destroy loo_Resp
                        destroy loo_Result
                        destroy loo_Fac
                        destroy loo_State
                        destroy loo_Endpoint
                        destroy loo_Hash
                        destroy loo_Link
                        destroy loo_ItemPath
                        destroy loo_SeenLinks
                        destroy loo_Previous
                        return
                    end if

                end if

            end if

            li_MobilePhoneType = loo_Result.JsonTypeOf("value[i].mobilePhone")
            if li_MobilePhoneType = 1 then
                loo_State.UpdateString("mobilePhone",loo_Result.StringOf("value[i].mobilePhone"))
            else
                if li_MobilePhoneType = 6 then
                    loo_State.UpdateNull("mobilePhone")
                else
                    if li_MobilePhoneType <> -1 then
                        Write-Debug "Invalid contact field; checkpoint unchanged."
                        destroy loo_Token
                        destroy loo_Http
                        destroy loo_Resp
                        destroy loo_Result
                        destroy loo_Fac
                        destroy loo_State
                        destroy loo_Endpoint
                        destroy loo_Hash
                        destroy loo_Link
                        destroy loo_ItemPath
                        destroy loo_SeenLinks
                        destroy loo_Previous
                        return
                    end if

                end if

            end if

            li_EmailType = loo_Result.JsonTypeOf("value[i].emailAddresses")
            if li_EmailType = 4 then
                //  Replace this collection when present, including an empty array that clears it.
                loo_State.UpdateNewArray("emailAddresses")
                j = 0
                do while (j < loo_Result.SizeOfArray("value[i].emailAddresses"))
                    loo_Result.J = j
                    loo_State.J = j
                    if (loo_Result.JsonTypeOf("value[i].emailAddresses[j].address") <> 1) OR (loo_Result.StringOfEquals("value[i].emailAddresses[j].address","",1) = 1) then
                        Write-Debug "Expected a nonempty value[i].emailAddresses[j].address in the JSON."
                        destroy loo_Token
                        destroy loo_Http
                        destroy loo_Resp
                        destroy loo_Result
                        destroy loo_Fac
                        destroy loo_State
                        destroy loo_Endpoint
                        destroy loo_Hash
                        destroy loo_Link
                        destroy loo_ItemPath
                        destroy loo_SeenLinks
                        destroy loo_Previous
                        return
                    end if

                    loo_State.UpdateString("emailAddresses[j].address",loo_Result.StringOf("value[i].emailAddresses[j].address"))
                    if loo_Result.JsonTypeOf("value[i].emailAddresses[j].name") = 1 then
                        loo_State.UpdateString("emailAddresses[j].name",loo_Result.StringOf("value[i].emailAddresses[j].name"))
                    end if

                    j = j + 1
                loop
            else
                if li_EmailType <> -1 then
                    Write-Debug "Invalid email collection; checkpoint unchanged."
                    destroy loo_Token
                    destroy loo_Http
                    destroy loo_Resp
                    destroy loo_Result
                    destroy loo_Fac
                    destroy loo_State
                    destroy loo_Endpoint
                    destroy loo_Hash
                    destroy loo_Link
                    destroy loo_ItemPath
                    destroy loo_SeenLinks
                    destroy loo_Previous
                    return
                end if

            end if

            loo_State.PathPrefix = ""
            Write-Debug "Updated local contact: " + ls_ContactId
        end if

        loo_State.PathPrefix = ""
        i = i + 1
    loop
    loo_State.UpdateString("resumeUrl",ls_ResumeUrl)
    loo_State.UpdateBool("roundComplete",li_Finished)
    //  Save the data and cursor in one document. The backup contains the matching previous pair.
    li_Success = loo_Previous.WriteFile(ls_BackupPath)
    if li_Success <> 1 then
        Write-Debug "Could not back up the previous checkpoint; no replacement attempted."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    li_Success = loo_State.WriteFile(ls_CachePath)
    if li_Success <> 1 then
        Write-Debug "Checkpoint write failed. Restore the private .bak before continuing."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

    li_PageCount = li_PageCount + 1
    if li_Finished = 1 then
        Write-Debug "Synchronization round complete; saved the delta link for the next run."
        destroy loo_Token
        destroy loo_Http
        destroy loo_Resp
        destroy loo_Result
        destroy loo_Fac
        destroy loo_State
        destroy loo_Endpoint
        destroy loo_Hash
        destroy loo_Link
        destroy loo_ItemPath
        destroy loo_SeenLinks
        destroy loo_Previous
        return
    end if

loop
Write-Debug "Paused after 100 pages; the saved nextLink resumes on the next run."


destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Fac
destroy loo_State
destroy loo_Endpoint
destroy loo_Hash
destroy loo_Link
destroy loo_ItemPath
destroy loo_SeenLinks
destroy loo_Previous