Sample code for 30+ languages & platforms
Visual FoxPro 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 Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL loToken
LOCAL loHttp
LOCAL loResp
LOCAL loResult
LOCAL lcFolderId
LOCAL loFac
LOCAL lcCachePath
LOCAL lcBackupPath
LOCAL loState
LOCAL loEndpoint
LOCAL loHash
LOCAL loLink
LOCAL loItemPath
LOCAL loSeenLinks
LOCAL loPrevious
LOCAL lnPageCount
LOCAL lcUrl
LOCAL lnNextType
LOCAL lnDeltaType
LOCAL lnFinished
LOCAL lcResumeUrl
LOCAL i
LOCAL lcContactId
LOCAL lcItemKey
LOCAL lnDisplayNameType
LOCAL lnMobilePhoneType
LOCAL lnEmailType
LOCAL j

lnSuccess = 0

*  Assumes Chilkat is unlocked. See Global Unlock Sample.
lnSuccess = 0
*  Obtain a delegated Microsoft Graph token using the contacts authorization example.
*  See Authorize Outlook Contacts with OAuth2 and PKCE.
loToken = CreateObject('Chilkat.JsonObject')
loToken.Strict = 1
lnSuccess = loToken.LoadFile("qa_data/tokens/outlookContacts.json")
IF (lnSuccess <> 1) THEN
    ? "Could not read the private contacts token cache."
    RELEASE loToken
    CANCEL
ENDIF

IF ((loToken.JsonTypeOf("access_token") <> 1) OR (loToken.StringOfEquals("access_token","",1) = 1)) THEN
    ? "Expected a nonempty access_token in the JSON."
    RELEASE loToken
    CANCEL
ENDIF

loHttp = CreateObject('Chilkat.Http')
loHttp.AuthToken = loToken.StringOf("access_token")
loHttp.RequireSslCertVerify = 1
loHttp.FollowRedirects = 0
loHttp.ConnectTimeout = 20
loHttp.ReadTimeout = 30
loHttp.SetRequestHeader("Accept","application/json")
loResp = CreateObject('Chilkat.HttpResponse')
loResult = CreateObject('Chilkat.JsonObject')
loResult.Strict = 1
loHttp.SetRequestHeader("Prefer",'IdType="ImmutableId", odata.maxpagesize=50')
lcFolderId = "YOUR_CONTACT_FOLDER_ID"
loFac = CreateObject('Chilkat.FileAccess')
lnSuccess = loFac.DirEnsureExists("qa_data/outlookContacts")
IF (lnSuccess <> 1) THEN
    ? "Could not create the private synchronization directory."
    RELEASE loToken
    RELEASE loHttp
    RELEASE loResp
    RELEASE loResult
    RELEASE loFac
    CANCEL
ENDIF

lcCachePath = "qa_data/outlookContacts/contacts-sync.json"
lcBackupPath = "qa_data/outlookContacts/contacts-sync.json.bak"
loState = CreateObject('Chilkat.JsonObject')
loState.Strict = 1
IF (loFac.FileExists(lcCachePath) = 1) THEN
    lnSuccess = loState.LoadFile(lcCachePath)
    IF (lnSuccess <> 1) THEN
        ? "Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

    IF ((loState.JsonTypeOf("resumeUrl") <> 1) OR (loState.StringOfEquals("resumeUrl","",1) = 1)) THEN
        ? "Expected a nonempty resumeUrl in the JSON."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

    IF ((loState.JsonTypeOf("folderId") <> 1) OR (loState.StringOfEquals("folderId","",1) = 1)) THEN
        ? "Expected a nonempty folderId in the JSON."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

    IF (loState.StringOfEquals("folderId",lcFolderId,1) <> 1) THEN
        ? "This checkpoint belongs to another folder. Use a separate cache."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

    IF (loState.JsonTypeOf("items") <> 3) THEN
        ? "Expected an items object in the checkpoint."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        CANCEL
    ENDIF

ELSE
    loEndpoint = CreateObject('Chilkat.StringBuilder')
    loEndpoint.Append("https://graph.microsoft.com/v1.0/me/contactFolders/")
    loEndpoint.Append(loHttp.UrlEncode(lcFolderId))
    loEndpoint.Append("/contacts/delta?$select=id,displayName,emailAddresses,mobilePhone")
    loState.UpdateString("folderId",lcFolderId)
    loState.UpdateString("resumeUrl",loEndpoint.GetAsString())
    loState.UpdateNewObject("items")
ENDIF

loHash = CreateObject('Chilkat.Crypt2')
loHash.HashAlgorithm = "sha256"
loHash.Charset = "utf-8"
loHash.EncodingMode = "hex"
loLink = CreateObject('Chilkat.StringBuilder')
loItemPath = CreateObject('Chilkat.StringBuilder')
loSeenLinks = CreateObject('Chilkat.Hashtable')
loPrevious = CreateObject('Chilkat.JsonObject')
loPrevious.Strict = 1
lnPageCount = 0
DO WHILE (lnPageCount < 100)
    lcUrl = loState.StringOf("resumeUrl")
    loLink.Clear()
    loLink.Append(lcUrl)
    IF (loLink.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1) THEN
        ? "Unexpected continuation host or API version; no request sent."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    IF (loSeenLinks.Contains(lcUrl) = 1) THEN
        ? "Repeated continuation URL; stopping."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    loSeenLinks.AddInt(lcUrl,1)
    lnSuccess = loHttp.HttpNoBody("GET",lcUrl,loResp)
    *  A false result can still include an HTTP error response.
    IF ((lnSuccess <> 1) AND (loResp.StatusCode = 0)) THEN
        ? "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    IF (loResp.StatusCode <> 200) THEN
        ? "Unexpected HTTP status: " + STR(loResp.StatusCode)
        ? "Request ID: " + loResp.GetHeaderField("request-id")
        IF (loResp.StatusCode = 429) THEN
            ? "Retry-After: " + loResp.GetHeaderField("Retry-After")
        ENDIF

        IF (loResp.StatusCode = 401) THEN
            ? "Refresh the Graph access token or authorize again."
        ENDIF

        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    lnSuccess = loResult.Load(loResp.BodyStr)
    IF (lnSuccess <> 1) THEN
        ? "Expected a well-formed JSON response."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    IF (loResult.JsonTypeOf("value") <> 4) THEN
        ? "Expected a value array; checkpoint unchanged."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    *  Exactly one continuation member must be a nonempty string.
    lnNextType = loResult.JsonTypeOf('"@odata.nextLink"')
    lnDeltaType = loResult.JsonTypeOf('"@odata.deltaLink"')
    lnFinished = 0

    IF ((lnNextType = 1) AND (lnDeltaType = -1)) THEN
        lcResumeUrl = loResult.StringOf('"@odata.nextLink"')
    ELSE
        IF ((lnDeltaType <> 1) OR (lnNextType <> -1)) THEN
            ? "Invalid delta continuation; checkpoint unchanged."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loFac
            RELEASE loState
            RELEASE loEndpoint
            RELEASE loHash
            RELEASE loLink
            RELEASE loItemPath
            RELEASE loSeenLinks
            RELEASE loPrevious
            CANCEL
        ENDIF

        lcResumeUrl = loResult.StringOf('"@odata.deltaLink"')
        lnFinished = 1
    ENDIF

    loLink.Clear()
    loLink.Append(lcResumeUrl)
    IF (loLink.StartsWith("https://graph.microsoft.com/v1.0/",1) <> 1) THEN
        ? "Invalid continuation URL; checkpoint unchanged."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    lnSuccess = loPrevious.Load(loState.Emit())
    IF (lnSuccess <> 1) THEN
        ? "Could not snapshot the previous checkpoint."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    i = 0
    DO WHILE (i < loResult.SizeOfArray("value"))
        loResult.I = i
        IF ((loResult.JsonTypeOf("value[i].id") <> 1) OR (loResult.StringOfEquals("value[i].id","",1) = 1)) THEN
            ? "Expected a nonempty value[i].id in the JSON."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loFac
            RELEASE loState
            RELEASE loEndpoint
            RELEASE loHash
            RELEASE loLink
            RELEASE loItemPath
            RELEASE loSeenLinks
            RELEASE loPrevious
            CANCEL
        ENDIF

        lcContactId = loResult.StringOf("value[i].id")
        lcItemKey = loHash.HashStringENC(lcContactId)
        IF (loHash.LastMethodSuccess <> 1) THEN
            ? "Could not form a local record key."
            RELEASE loToken
            RELEASE loHttp
            RELEASE loResp
            RELEASE loResult
            RELEASE loFac
            RELEASE loState
            RELEASE loEndpoint
            RELEASE loHash
            RELEASE loLink
            RELEASE loItemPath
            RELEASE loSeenLinks
            RELEASE loPrevious
            CANCEL
        ENDIF

        *  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        loItemPath.Clear()
        loItemPath.Append("items.")
        loItemPath.Append(lcItemKey)
        IF (loState.JsonTypeOf(loItemPath.GetAsString()) <> 3) THEN
            loState.UpdateNewObject(loItemPath.GetAsString())
        ENDIF

        loItemPath.Append(".")
        loState.PathPrefix = loItemPath.GetAsString()
        loState.UpdateString("id",lcContactId)
        IF (loResult.JsonTypeOf("value[i].@removed") = 3) THEN
            *  Hide records with removed=true from the local folder view.
            loState.UpdateBool("removed",1)
            ? "Removed from the local view: " + lcContactId
        ELSE
            loState.UpdateBool("removed",0)
            lnDisplayNameType = loResult.JsonTypeOf("value[i].displayName")
            IF (lnDisplayNameType = 1) THEN
                loState.UpdateString("displayName",loResult.StringOf("value[i].displayName"))
            ELSE
                IF (lnDisplayNameType = 6) THEN
                    loState.UpdateNull("displayName")
                ELSE
                    IF (lnDisplayNameType <> -1) THEN
                        ? "Invalid contact field; checkpoint unchanged."
                        RELEASE loToken
                        RELEASE loHttp
                        RELEASE loResp
                        RELEASE loResult
                        RELEASE loFac
                        RELEASE loState
                        RELEASE loEndpoint
                        RELEASE loHash
                        RELEASE loLink
                        RELEASE loItemPath
                        RELEASE loSeenLinks
                        RELEASE loPrevious
                        CANCEL
                    ENDIF

                ENDIF

            ENDIF

            lnMobilePhoneType = loResult.JsonTypeOf("value[i].mobilePhone")
            IF (lnMobilePhoneType = 1) THEN
                loState.UpdateString("mobilePhone",loResult.StringOf("value[i].mobilePhone"))
            ELSE
                IF (lnMobilePhoneType = 6) THEN
                    loState.UpdateNull("mobilePhone")
                ELSE
                    IF (lnMobilePhoneType <> -1) THEN
                        ? "Invalid contact field; checkpoint unchanged."
                        RELEASE loToken
                        RELEASE loHttp
                        RELEASE loResp
                        RELEASE loResult
                        RELEASE loFac
                        RELEASE loState
                        RELEASE loEndpoint
                        RELEASE loHash
                        RELEASE loLink
                        RELEASE loItemPath
                        RELEASE loSeenLinks
                        RELEASE loPrevious
                        CANCEL
                    ENDIF

                ENDIF

            ENDIF

            lnEmailType = loResult.JsonTypeOf("value[i].emailAddresses")
            IF (lnEmailType = 4) THEN
                *  Replace this collection when present, including an empty array that clears it.
                loState.UpdateNewArray("emailAddresses")
                j = 0
                DO WHILE (j < loResult.SizeOfArray("value[i].emailAddresses"))
                    loResult.J = j
                    loState.J = j
                    IF ((loResult.JsonTypeOf("value[i].emailAddresses[j].address") <> 1) OR (loResult.StringOfEquals("value[i].emailAddresses[j].address","",1) = 1)) THEN
                        ? "Expected a nonempty value[i].emailAddresses[j].address in the JSON."
                        RELEASE loToken
                        RELEASE loHttp
                        RELEASE loResp
                        RELEASE loResult
                        RELEASE loFac
                        RELEASE loState
                        RELEASE loEndpoint
                        RELEASE loHash
                        RELEASE loLink
                        RELEASE loItemPath
                        RELEASE loSeenLinks
                        RELEASE loPrevious
                        CANCEL
                    ENDIF

                    loState.UpdateString("emailAddresses[j].address",loResult.StringOf("value[i].emailAddresses[j].address"))
                    IF (loResult.JsonTypeOf("value[i].emailAddresses[j].name") = 1) THEN
                        loState.UpdateString("emailAddresses[j].name",loResult.StringOf("value[i].emailAddresses[j].name"))
                    ENDIF

                    j = j + 1
                ENDDO
            ELSE
                IF (lnEmailType <> -1) THEN
                    ? "Invalid email collection; checkpoint unchanged."
                    RELEASE loToken
                    RELEASE loHttp
                    RELEASE loResp
                    RELEASE loResult
                    RELEASE loFac
                    RELEASE loState
                    RELEASE loEndpoint
                    RELEASE loHash
                    RELEASE loLink
                    RELEASE loItemPath
                    RELEASE loSeenLinks
                    RELEASE loPrevious
                    CANCEL
                ENDIF

            ENDIF

            loState.PathPrefix = ""
            ? "Updated local contact: " + lcContactId
        ENDIF

        loState.PathPrefix = ""
        i = i + 1
    ENDDO
    loState.UpdateString("resumeUrl",lcResumeUrl)
    loState.UpdateBool("roundComplete",lnFinished)
    *  Save the data and cursor in one document. The backup contains the matching previous pair.
    lnSuccess = loPrevious.WriteFile(lcBackupPath)
    IF (lnSuccess <> 1) THEN
        ? "Could not back up the previous checkpoint; no replacement attempted."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    lnSuccess = loState.WriteFile(lcCachePath)
    IF (lnSuccess <> 1) THEN
        ? "Checkpoint write failed. Restore the private .bak before continuing."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

    lnPageCount = lnPageCount + 1
    IF (lnFinished = 1) THEN
        ? "Synchronization round complete; saved the delta link for the next run."
        RELEASE loToken
        RELEASE loHttp
        RELEASE loResp
        RELEASE loResult
        RELEASE loFac
        RELEASE loState
        RELEASE loEndpoint
        RELEASE loHash
        RELEASE loLink
        RELEASE loItemPath
        RELEASE loSeenLinks
        RELEASE loPrevious
        CANCEL
    ENDIF

ENDDO
? "Paused after 100 pages; the saved nextLink resumes on the next run."

RELEASE loToken
RELEASE loHttp
RELEASE loResp
RELEASE loResult
RELEASE loFac
RELEASE loState
RELEASE loEndpoint
RELEASE loHash
RELEASE loLink
RELEASE loItemPath
RELEASE loSeenLinks
RELEASE loPrevious