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

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Obtain a delegated Microsoft Graph token using the contacts authorization example.
-- See Authorize Outlook Contacts with OAuth2 and PKCE.
local token = chilkat.JsonObject.new()
token.strict = true
success = token:load_file("qa_data/tokens/outlookContacts.json")
if not success then
    print("Could not read the private contacts 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", "IdType=\"ImmutableId\", odata.maxpagesize=50")
local folderId = "YOUR_CONTACT_FOLDER_ID"
local fac = chilkat.FileAccess.new()
success = fac:dir_ensure_exists("qa_data/outlookContacts")
if not success then
    print("Could not create the private synchronization directory.")
    return
end

local cachePath = "qa_data/outlookContacts/contacts-sync.json"
local backupPath = "qa_data/outlookContacts/contacts-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("folderId") ~= 1) or (state:string_of_equals("folderId", "", true)) then
        print("Expected a nonempty folderId in the JSON.")
        return
    end

    if not state:string_of_equals("folderId", folderId, true) then
        print("This checkpoint belongs to another folder. Use a separate cache.")
        return
    end

    if state:json_type_of("items") ~= 3 then
        print("Expected an items object in the checkpoint.")
        return
    end
else
    local endpoint = chilkat.StringBuilder.new()
    endpoint:append("https://graph.microsoft.com/v1.0/me/contactFolders/")
    endpoint:append(http:url_encode(folderId))
    endpoint:append("/contacts/delta?$select=id,displayName,emailAddresses,mobilePhone")
    state:update_string("folderId", folderId)
    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 contactId = result:string_of("value[i].id")
        local itemKey = hash:hash_string_enc(contactId)
        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", contactId)
        if result:json_type_of("value[i].@removed") == 3 then
            -- Hide records with removed=true from the local folder view.
            state:update_bool("removed", true)
            print("Removed from the local view: " .. contactId)
        else
            state:update_bool("removed", false)
            local displayNameType = result:json_type_of("value[i].displayName")
            if displayNameType == 1 then
                state:update_string("displayName", result:string_of("value[i].displayName"))
            elseif displayNameType == 6 then
                state:update_null("displayName")
            elseif displayNameType ~= (-1) then
                print("Invalid contact field; checkpoint unchanged.")
                return
            end

            local mobilePhoneType = result:json_type_of("value[i].mobilePhone")
            if mobilePhoneType == 1 then
                state:update_string("mobilePhone", result:string_of("value[i].mobilePhone"))
            elseif mobilePhoneType == 6 then
                state:update_null("mobilePhone")
            elseif mobilePhoneType ~= (-1) then
                print("Invalid contact field; checkpoint unchanged.")
                return
            end

            local emailType = result:json_type_of("value[i].emailAddresses")
            if emailType == 4 then
                -- Replace this collection when present, including an empty array that clears it.
                state:update_new_array("emailAddresses")
                local j = 0
                while j < result:size_of_array("value[i].emailAddresses") do
                    result.j = j
                    state.j = j
                    if (result:json_type_of("value[i].emailAddresses[j].address") ~= 1) or (result:string_of_equals("value[i].emailAddresses[j].address", "", true)) then
                        print("Expected a nonempty value[i].emailAddresses[j].address in the JSON.")
                        return
                    end

                    state:update_string("emailAddresses[j].address", result:string_of("value[i].emailAddresses[j].address"))
                    if result:json_type_of("value[i].emailAddresses[j].name") == 1 then
                        state:update_string("emailAddresses[j].name", result:string_of("value[i].emailAddresses[j].name"))
                    end

                    j = j + 1
                end
            elseif emailType ~= (-1) then
                print("Invalid email collection; checkpoint unchanged.")
                return
            end

            state.path_prefix = ""
            print("Updated local contact: " .. contactId)
        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.")