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.
Chilkat Ruby Downloads
require 'chilkat'
success = false
# Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
# Obtain a delegated Microsoft Graph token using the contacts authorization example.
# See Authorize Outlook Contacts with OAuth2 and PKCE.
token = Chilkat::CkJsonObject.new()
token.put_Strict(true)
success = token.LoadFile("qa_data/tokens/outlookContacts.json")
if (success != true)
print "Could not read the private contacts token cache." + "\n";
exit
end
if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",true) == true))
print "Expected a nonempty access_token in the JSON." + "\n";
exit
end
http = Chilkat::CkHttp.new()
http.put_AuthToken(token.stringOf("access_token"))
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
http.put_ConnectTimeout(20)
http.put_ReadTimeout(30)
http.SetRequestHeader("Accept","application/json")
resp = Chilkat::CkHttpResponse.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
http.SetRequestHeader("Prefer","IdType=\"ImmutableId\", odata.maxpagesize=50")
folderId = "YOUR_CONTACT_FOLDER_ID"
fac = Chilkat::CkFileAccess.new()
success = fac.DirEnsureExists("qa_data/outlookContacts")
if (success != true)
print "Could not create the private synchronization directory." + "\n";
exit
end
cachePath = "qa_data/outlookContacts/contacts-sync.json"
backupPath = "qa_data/outlookContacts/contacts-sync.json.bak"
state = Chilkat::CkJsonObject.new()
state.put_Strict(true)
if (fac.FileExists(cachePath) == true)
success = state.LoadFile(cachePath)
if (success != true)
print "Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing." + "\n";
exit
end
if ((state.JsonTypeOf("resumeUrl") != 1) or (state.StringOfEquals("resumeUrl","",true) == true))
print "Expected a nonempty resumeUrl in the JSON." + "\n";
exit
end
if ((state.JsonTypeOf("folderId") != 1) or (state.StringOfEquals("folderId","",true) == true))
print "Expected a nonempty folderId in the JSON." + "\n";
exit
end
if (state.StringOfEquals("folderId",folderId,true) != true)
print "This checkpoint belongs to another folder. Use a separate cache." + "\n";
exit
end
if (state.JsonTypeOf("items") != 3)
print "Expected an items object in the checkpoint." + "\n";
exit
end
else
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("https://graph.microsoft.com/v1.0/me/contactFolders/")
endpoint.Append(http.urlEncode(folderId))
endpoint.Append("/contacts/delta?$select=id,displayName,emailAddresses,mobilePhone")
state.UpdateString("folderId",folderId)
state.UpdateString("resumeUrl",endpoint.getAsString())
state.UpdateNewObject("items")
end
hash = Chilkat::CkCrypt2.new()
hash.put_HashAlgorithm("sha256")
hash.put_Charset("utf-8")
hash.put_EncodingMode("hex")
link = Chilkat::CkStringBuilder.new()
itemPath = Chilkat::CkStringBuilder.new()
seenLinks = Chilkat::CkHashtable.new()
previous = Chilkat::CkJsonObject.new()
previous.put_Strict(true)
pageCount = 0
while (pageCount < 100)
url = state.stringOf("resumeUrl")
link.Clear()
link.Append(url)
if (link.StartsWith("https://graph.microsoft.com/v1.0/",true) != true)
print "Unexpected continuation host or API version; no request sent." + "\n";
exit
end
if (seenLinks.Contains(url) == true)
print "Repeated continuation URL; stopping." + "\n";
exit
end
seenLinks.AddInt(url,1)
success = http.HttpNoBody("GET",url,resp)
# A false result can still include an HTTP error response.
if ((success != true) and (resp.get_StatusCode() == 0))
print "No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying." + "\n";
exit
end
if (resp.get_StatusCode() != 200)
print "Unexpected HTTP status: " + resp.get_StatusCode().to_s() + "\n";
print "Request ID: " + resp.getHeaderField("request-id") + "\n";
if (resp.get_StatusCode() == 429)
print "Retry-After: " + resp.getHeaderField("Retry-After") + "\n";
end
if (resp.get_StatusCode() == 401)
print "Refresh the Graph access token or authorize again." + "\n";
end
exit
end
success = result.Load(resp.bodyStr())
if (success != true)
print "Expected a well-formed JSON response." + "\n";
exit
end
if (result.JsonTypeOf("value") != 4)
print "Expected a value array; checkpoint unchanged." + "\n";
exit
end
# Exactly one continuation member must be a nonempty string.
nextType = result.JsonTypeOf("\"@odata.nextLink\"")
deltaType = result.JsonTypeOf("\"@odata.deltaLink\"")
finished = false
if ((nextType == 1) and (deltaType == -1))
resumeUrl = result.stringOf("\"@odata.nextLink\"")
else
if ((deltaType != 1) or (nextType != -1))
print "Invalid delta continuation; checkpoint unchanged." + "\n";
exit
end
resumeUrl = result.stringOf("\"@odata.deltaLink\"")
finished = true
end
link.Clear()
link.Append(resumeUrl)
if (link.StartsWith("https://graph.microsoft.com/v1.0/",true) != true)
print "Invalid continuation URL; checkpoint unchanged." + "\n";
exit
end
success = previous.Load(state.emit())
if (success != true)
print "Could not snapshot the previous checkpoint." + "\n";
exit
end
i = 0
while (i < result.SizeOfArray("value"))
result.put_I(i)
if ((result.JsonTypeOf("value[i].id") != 1) or (result.StringOfEquals("value[i].id","",true) == true))
print "Expected a nonempty value[i].id in the JSON." + "\n";
exit
end
contactId = result.stringOf("value[i].id")
itemKey = hash.hashStringENC(contactId)
if (hash.get_LastMethodSuccess() != true)
print "Could not form a local record key." + "\n";
exit
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.JsonTypeOf(itemPath.getAsString()) != 3)
state.UpdateNewObject(itemPath.getAsString())
end
itemPath.Append(".")
state.put_PathPrefix(itemPath.getAsString())
state.UpdateString("id",contactId)
if (result.JsonTypeOf("value[i].@removed") == 3)
# Hide records with removed=true from the local folder view.
state.UpdateBool("removed",true)
print "Removed from the local view: " + contactId + "\n";
else
state.UpdateBool("removed",false)
displayNameType = result.JsonTypeOf("value[i].displayName")
if (displayNameType == 1)
state.UpdateString("displayName",result.stringOf("value[i].displayName"))
else
if (displayNameType == 6)
state.UpdateNull("displayName")
else
if (displayNameType != -1)
print "Invalid contact field; checkpoint unchanged." + "\n";
exit
end
end
end
mobilePhoneType = result.JsonTypeOf("value[i].mobilePhone")
if (mobilePhoneType == 1)
state.UpdateString("mobilePhone",result.stringOf("value[i].mobilePhone"))
else
if (mobilePhoneType == 6)
state.UpdateNull("mobilePhone")
else
if (mobilePhoneType != -1)
print "Invalid contact field; checkpoint unchanged." + "\n";
exit
end
end
end
emailType = result.JsonTypeOf("value[i].emailAddresses")
if (emailType == 4)
# Replace this collection when present, including an empty array that clears it.
state.UpdateNewArray("emailAddresses")
j = 0
while (j < result.SizeOfArray("value[i].emailAddresses"))
result.put_J(j)
state.put_J(j)
if ((result.JsonTypeOf("value[i].emailAddresses[j].address") != 1) or (result.StringOfEquals("value[i].emailAddresses[j].address","",true) == true))
print "Expected a nonempty value[i].emailAddresses[j].address in the JSON." + "\n";
exit
end
state.UpdateString("emailAddresses[j].address",result.stringOf("value[i].emailAddresses[j].address"))
if (result.JsonTypeOf("value[i].emailAddresses[j].name") == 1)
state.UpdateString("emailAddresses[j].name",result.stringOf("value[i].emailAddresses[j].name"))
end
j = j + 1
end
else
if (emailType != -1)
print "Invalid email collection; checkpoint unchanged." + "\n";
exit
end
end
state.put_PathPrefix("")
print "Updated local contact: " + contactId + "\n";
end
state.put_PathPrefix("")
i = i + 1
end
state.UpdateString("resumeUrl",resumeUrl)
state.UpdateBool("roundComplete",finished)
# Save the data and cursor in one document. The backup contains the matching previous pair.
success = previous.WriteFile(backupPath)
if (success != true)
print "Could not back up the previous checkpoint; no replacement attempted." + "\n";
exit
end
success = state.WriteFile(cachePath)
if (success != true)
print "Checkpoint write failed. Restore the private .bak before continuing." + "\n";
exit
end
pageCount = pageCount + 1
if (finished == true)
print "Synchronization round complete; saved the delta link for the next run." + "\n";
exit
end
end
print "Paused after 100 pages; the saved nextLink resumes on the next run." + "\n";