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

OneDrive: Synchronize a Local File Index with Delta Queries

See more OneDrive Examples

Build and maintain a local metadata index for one drive. The first run follows root/delta to a deltaLink; later runs start at that saved URL. Keep a separate checkpoint for each account, drive, and projection. Empty pages still have to be followed. OneDrive reports deletion with the deleted facet, not Outlook's @removed annotation.

Repeated item IDs are applied in received order, with the last occurrence winning. Partial updates preserve omitted fields; parent IDs support renames and moves without relying on returned paths. IDs remain strings and large sizes are stored as decimal text. Tombstones are retained rather than deleting local data. A real file synchronizer must download changed content, reconcile local edits, and remove a deleted folder only after the round is complete and it is empty.

The checkpoint stores data and continuation together, with a private matching backup before replacement. Use atomic durable storage and one writer in production. Intermediate pages are not a completed snapshot; roundComplete becomes true only at deltaLink. An expired state (410) requires reconciliation and a fresh baseline, not silent loss of local changes. The 100-page execution bound saves progress for the next run. Continuation URLs are private and must not be edited.

Keep drive IDs and item IDs as opaque strings, retaining the drive context with each item. Encode individual path segments, not an entire URL or a slash-separated path in one call. An item ID remains stable across rename/move within its drive; a name-based path changes. OneDrive does not use Outlook's ImmutableId preference.

Permission: Files.Read.

Uses direct Chilkat.Http requests to Microsoft Graph v1.0 in the global cloud. The delegated token is read from the private qa_data/tokens/oneDrive.json file created by the PKCE authorization example. Personal Microsoft accounts and Microsoft 365 work/school accounts can use delegated authorization when the app registration supports them. Refresh expired tokens; scopes and actual file access both matter.

For app-only Microsoft 365 access, use client credentials with administrator-approved application permissions. /me requires a signed-in user; app-only calls must address an authorized user, site, or drive explicitly. Client credentials do not grant access to personal OneDrive accounts. National clouds use their own authority and Graph hosts.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
#  Obtain a delegated Graph token with this example's file permissions.
#  See OneDrive OAuth2 with PKCE.
token = Chilkat::CkJsonObject.new()
token.put_Strict(true)
success = token.LoadFile("qa_data/tokens/oneDrive.json")
if (success != true)
    print "Could not load the private OneDrive 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(120)
http.SetRequestHeader("Accept","application/json")
resp = Chilkat::CkHttpResponse.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)
driveId = "YOUR_DRIVE_ID"
#  Use a distinct stable application account key and cache path per account.
accountKey = "YOUR_LOCAL_ACCOUNT_KEY"
fac = Chilkat::CkFileAccess.new()
success = fac.DirEnsureExists("qa_data/oneDrive")
if (success != true)
    print "Could not create the private synchronization directory." + "\n";
    exit
end

cachePath = "qa_data/oneDrive/items-sync.json"
backupPath = "qa_data/oneDrive/items-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("driveId") != 1) or (state.StringOfEquals("driveId","",true) == true))
        print "Expected a nonempty driveId in the JSON." + "\n";
        exit
    end

    if (state.StringOfEquals("driveId",driveId,true) != true)
        print "This checkpoint belongs to another drive. Use a separate cache." + "\n";
        exit
    end

    if (state.StringOfEquals("accountKey",accountKey,true) != true)
        print "This checkpoint belongs to another account; nothing requested." + "\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/drives/")
    endpoint.Append(http.urlEncode(driveId))
    endpoint.Append("/root/delta?$select=id,name,size,parentReference,file,folder,eTag,deleted")
    state.UpdateString("driveId",driveId)
    state.UpdateString("accountKey",accountKey)
    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() == 410)
        print "Delta state expired. Reconcile local edits and rebuild a fresh drive baseline; preserve the existing cache." + "\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

        itemId = result.stringOf("value[i].id")
        itemKey = hash.hashStringENC(itemId)
        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",itemId)
        if (result.JsonTypeOf("value[i].deleted") == 3)
            #  Retain a tombstone; this example does not delete local files or folders.
            #  Process folder deletion only after the full round and only when the folder is empty.
            state.UpdateBool("removed",true)
            print "Removed from the local view: " + itemId + "\n";
        else
            state.UpdateBool("removed",false)
            if (result.HasMember("value[i].name") == true)
                if ((result.JsonTypeOf("value[i].name") != 1) or (result.StringOfEquals("value[i].name","",true) == true))
                    print "Expected a nonempty value[i].name in the JSON." + "\n";
                    exit
                end

                state.UpdateString("name",result.stringOf("value[i].name"))
            end

            if (result.HasMember("value[i].eTag") == true)
                if ((result.JsonTypeOf("value[i].eTag") != 1) or (result.StringOfEquals("value[i].eTag","",true) == true))
                    print "Expected a nonempty value[i].eTag in the JSON." + "\n";
                    exit
                end

                state.UpdateString("eTag",result.stringOf("value[i].eTag"))
            end

            if (result.HasMember("value[i].parentReference.id") == true)
                if ((result.JsonTypeOf("value[i].parentReference.id") != 1) or (result.StringOfEquals("value[i].parentReference.id","",true) == true))
                    print "Expected a nonempty value[i].parentReference.id in the JSON." + "\n";
                    exit
                end

                state.UpdateString("parentReference.id",result.stringOf("value[i].parentReference.id"))
            end

            if (result.HasMember("value[i].parentReference.driveId") == true)
                if ((result.JsonTypeOf("value[i].parentReference.driveId") != 1) or (result.StringOfEquals("value[i].parentReference.driveId","",true) == true))
                    print "Expected a nonempty value[i].parentReference.driveId in the JSON." + "\n";
                    exit
                end

                state.UpdateString("parentReference.driveId",result.stringOf("value[i].parentReference.driveId"))
            end

            #  Omitted fields are unchanged. Do not erase an earlier name or parent on a partial delta.
            #  Keep large sizes as decimal text in this demonstration's local index.
            if (result.HasMember("value[i].size") == true)
                state.UpdateString("sizeBytes",result.stringOf("value[i].size"))
            end

            if (result.JsonTypeOf("value[i].folder") == 3)
                state.UpdateString("kind","folder")
            end

            if (result.JsonTypeOf("value[i].file") == 3)
                state.UpdateString("kind","file")
            end

            state.put_PathPrefix("")
            print "Updated local item: " + itemId + "\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";