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

Delphi DLL
var
success: Boolean;
token: HCkJsonObject;
http: HCkHttp;
resp: HCkHttpResponse;
result: HCkJsonObject;
driveId: PWideChar;
accountKey: PWideChar;
fac: HCkFileAccess;
cachePath: PWideChar;
backupPath: PWideChar;
state: HCkJsonObject;
endpoint: HCkStringBuilder;
hash: HCkCrypt2;
link: HCkStringBuilder;
itemPath: HCkStringBuilder;
seenLinks: HCkHashtable;
previous: HCkJsonObject;
pageCount: Integer;
url: PWideChar;
nextType: Integer;
deltaType: Integer;
finished: Boolean;
resumeUrl: PWideChar;
i: Integer;
itemId: PWideChar;
itemKey: PWideChar;

begin
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 := CkJsonObject_Create();
CkJsonObject_putStrict(token,True);
success := CkJsonObject_LoadFile(token,'qa_data/tokens/oneDrive.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load the private OneDrive token cache.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(token,'access_token') <> 1) or (CkJsonObject_StringOfEquals(token,'access_token','',True) = True)) then
  begin
    Memo1.Lines.Add('Expected a nonempty access_token in the JSON.');
    Exit;
  end;
http := CkHttp_Create();
CkHttp_putAuthToken(http,CkJsonObject__stringOf(token,'access_token'));
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
CkHttp_putConnectTimeout(http,20);
CkHttp_putReadTimeout(http,120);
CkHttp_SetRequestHeader(http,'Accept','application/json');
resp := CkHttpResponse_Create();
result := CkJsonObject_Create();
CkJsonObject_putStrict(result,True);
driveId := 'YOUR_DRIVE_ID';
//  Use a distinct stable application account key and cache path per account.
accountKey := 'YOUR_LOCAL_ACCOUNT_KEY';
fac := CkFileAccess_Create();
success := CkFileAccess_DirEnsureExists(fac,'qa_data/oneDrive');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not create the private synchronization directory.');
    Exit;
  end;
cachePath := 'qa_data/oneDrive/items-sync.json';
backupPath := 'qa_data/oneDrive/items-sync.json.bak';
state := CkJsonObject_Create();
CkJsonObject_putStrict(state,True);
if (CkFileAccess_FileExists(fac,cachePath) = True) then
  begin
    success := CkJsonObject_LoadFile(state,cachePath);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Invalid checkpoint; recover the matching data and cursor from the private .bak file before continuing.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(state,'resumeUrl') <> 1) or (CkJsonObject_StringOfEquals(state,'resumeUrl','',True) = True)) then
      begin
        Memo1.Lines.Add('Expected a nonempty resumeUrl in the JSON.');
        Exit;
      end;
    if ((CkJsonObject_JsonTypeOf(state,'driveId') <> 1) or (CkJsonObject_StringOfEquals(state,'driveId','',True) = True)) then
      begin
        Memo1.Lines.Add('Expected a nonempty driveId in the JSON.');
        Exit;
      end;
    if (CkJsonObject_StringOfEquals(state,'driveId',driveId,True) <> True) then
      begin
        Memo1.Lines.Add('This checkpoint belongs to another drive. Use a separate cache.');
        Exit;
      end;
    if (CkJsonObject_StringOfEquals(state,'accountKey',accountKey,True) <> True) then
      begin
        Memo1.Lines.Add('This checkpoint belongs to another account; nothing requested.');
        Exit;
      end;
    if (CkJsonObject_JsonTypeOf(state,'items') <> 3) then
      begin
        Memo1.Lines.Add('Expected an items object in the checkpoint.');
        Exit;
      end;
  end
else
  begin
    endpoint := CkStringBuilder_Create();
    CkStringBuilder_Append(endpoint,'https://graph.microsoft.com/v1.0/drives/');
    CkStringBuilder_Append(endpoint,CkHttp__urlEncode(http,driveId));
    CkStringBuilder_Append(endpoint,'/root/delta?$select=id,name,size,parentReference,file,folder,eTag,deleted');
    CkJsonObject_UpdateString(state,'driveId',driveId);
    CkJsonObject_UpdateString(state,'accountKey',accountKey);
    CkJsonObject_UpdateString(state,'resumeUrl',CkStringBuilder__getAsString(endpoint));
    CkJsonObject_UpdateNewObject(state,'items');
  end;
hash := CkCrypt2_Create();
CkCrypt2_putHashAlgorithm(hash,'sha256');
CkCrypt2_putCharset(hash,'utf-8');
CkCrypt2_putEncodingMode(hash,'hex');
link := CkStringBuilder_Create();
itemPath := CkStringBuilder_Create();
seenLinks := CkHashtable_Create();
previous := CkJsonObject_Create();
CkJsonObject_putStrict(previous,True);
pageCount := 0;
while (pageCount < 100) do
  begin
    url := CkJsonObject__stringOf(state,'resumeUrl');
    CkStringBuilder_Clear(link);
    CkStringBuilder_Append(link,url);
    if (CkStringBuilder_StartsWith(link,'https://graph.microsoft.com/v1.0/',True) <> True) then
      begin
        Memo1.Lines.Add('Unexpected continuation host or API version; no request sent.');
        Exit;
      end;
    if (CkHashtable_Contains(seenLinks,url) = True) then
      begin
        Memo1.Lines.Add('Repeated continuation URL; stopping.');
        Exit;
      end;
    CkHashtable_AddInt(seenLinks,url,1);
    success := CkHttp_HttpNoBody(http,'GET',url,resp);
    //  A false result can still include an HTTP error response.
    if ((success <> True) and (CkHttpResponse_getStatusCode(resp) = 0)) then
      begin
        Memo1.Lines.Add('No HTTP response was received. Inspect diagnostics privately; reconcile a write before retrying.');
        Exit;
      end;
    if (CkHttpResponse_getStatusCode(resp) = 410) then
      begin
        Memo1.Lines.Add('Delta state expired. Reconcile local edits and rebuild a fresh drive baseline; preserve the existing cache.');
        Exit;
      end;
    if (CkHttpResponse_getStatusCode(resp) <> 200) then
      begin
        Memo1.Lines.Add('Unexpected HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(resp)));
        Memo1.Lines.Add('Request ID: ' + CkHttpResponse__getHeaderField(resp,'request-id'));
        if (CkHttpResponse_getStatusCode(resp) = 429) then
          begin
            Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(resp,'Retry-After'));
          end;
        if (CkHttpResponse_getStatusCode(resp) = 401) then
          begin
            Memo1.Lines.Add('Refresh the Graph access token or authorize again.');
          end;
        Exit;
      end;
    success := CkJsonObject_Load(result,CkHttpResponse__bodyStr(resp));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Expected a well-formed JSON response.');
        Exit;
      end;
    if (CkJsonObject_JsonTypeOf(result,'value') <> 4) then
      begin
        Memo1.Lines.Add('Expected a value array; checkpoint unchanged.');
        Exit;
      end;
    //  Exactly one continuation member must be a nonempty string.
    nextType := CkJsonObject_JsonTypeOf(result,'"@odata.nextLink"');
    deltaType := CkJsonObject_JsonTypeOf(result,'"@odata.deltaLink"');
    finished := False;

    if ((nextType = 1) and (deltaType = -1)) then
      begin
        resumeUrl := CkJsonObject__stringOf(result,'"@odata.nextLink"');
      end
    else
      begin
        if ((deltaType <> 1) or (nextType <> -1)) then
          begin
            Memo1.Lines.Add('Invalid delta continuation; checkpoint unchanged.');
            Exit;
          end;
        resumeUrl := CkJsonObject__stringOf(result,'"@odata.deltaLink"');
        finished := True;
      end;
    CkStringBuilder_Clear(link);
    CkStringBuilder_Append(link,resumeUrl);
    if (CkStringBuilder_StartsWith(link,'https://graph.microsoft.com/v1.0/',True) <> True) then
      begin
        Memo1.Lines.Add('Invalid continuation URL; checkpoint unchanged.');
        Exit;
      end;
    success := CkJsonObject_Load(previous,CkJsonObject__emit(state));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not snapshot the previous checkpoint.');
        Exit;
      end;
    i := 0;
    while (i < CkJsonObject_SizeOfArray(result,'value')) do
      begin
        CkJsonObject_putI(result,i);
        if ((CkJsonObject_JsonTypeOf(result,'value[i].id') <> 1) or (CkJsonObject_StringOfEquals(result,'value[i].id','',True) = True)) then
          begin
            Memo1.Lines.Add('Expected a nonempty value[i].id in the JSON.');
            Exit;
          end;
        itemId := CkJsonObject__stringOf(result,'value[i].id');
        itemKey := CkCrypt2__hashStringENC(hash,itemId);
        if (CkCrypt2_getLastMethodSuccess(hash) <> True) then
          begin
            Memo1.Lines.Add('Could not form a local record key.');
            Exit;
          end;
        //  Hash only for a JSON-safe local key. Preserve the original opaque ID in the record.
        CkStringBuilder_Clear(itemPath);
        CkStringBuilder_Append(itemPath,'items.');
        CkStringBuilder_Append(itemPath,itemKey);
        if (CkJsonObject_JsonTypeOf(state,CkStringBuilder__getAsString(itemPath)) <> 3) then
          begin
            CkJsonObject_UpdateNewObject(state,CkStringBuilder__getAsString(itemPath));
          end;
        CkStringBuilder_Append(itemPath,'.');
        CkJsonObject_putPathPrefix(state,CkStringBuilder__getAsString(itemPath));
        CkJsonObject_UpdateString(state,'id',itemId);
        if (CkJsonObject_JsonTypeOf(result,'value[i].deleted') = 3) then
          begin
            //  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.
            CkJsonObject_UpdateBool(state,'removed',True);
            Memo1.Lines.Add('Removed from the local view: ' + itemId);
          end
        else
          begin
            CkJsonObject_UpdateBool(state,'removed',False);
            if (CkJsonObject_HasMember(result,'value[i].name') = True) then
              begin
                if ((CkJsonObject_JsonTypeOf(result,'value[i].name') <> 1) or (CkJsonObject_StringOfEquals(result,'value[i].name','',True) = True)) then
                  begin
                    Memo1.Lines.Add('Expected a nonempty value[i].name in the JSON.');
                    Exit;
                  end;
                CkJsonObject_UpdateString(state,'name',CkJsonObject__stringOf(result,'value[i].name'));
              end;
            if (CkJsonObject_HasMember(result,'value[i].eTag') = True) then
              begin
                if ((CkJsonObject_JsonTypeOf(result,'value[i].eTag') <> 1) or (CkJsonObject_StringOfEquals(result,'value[i].eTag','',True) = True)) then
                  begin
                    Memo1.Lines.Add('Expected a nonempty value[i].eTag in the JSON.');
                    Exit;
                  end;
                CkJsonObject_UpdateString(state,'eTag',CkJsonObject__stringOf(result,'value[i].eTag'));
              end;
            if (CkJsonObject_HasMember(result,'value[i].parentReference.id') = True) then
              begin
                if ((CkJsonObject_JsonTypeOf(result,'value[i].parentReference.id') <> 1) or (CkJsonObject_StringOfEquals(result,'value[i].parentReference.id','',True) = True)) then
                  begin
                    Memo1.Lines.Add('Expected a nonempty value[i].parentReference.id in the JSON.');
                    Exit;
                  end;
                CkJsonObject_UpdateString(state,'parentReference.id',CkJsonObject__stringOf(result,'value[i].parentReference.id'));
              end;
            if (CkJsonObject_HasMember(result,'value[i].parentReference.driveId') = True) then
              begin
                if ((CkJsonObject_JsonTypeOf(result,'value[i].parentReference.driveId') <> 1) or (CkJsonObject_StringOfEquals(result,'value[i].parentReference.driveId','',True) = True)) then
                  begin
                    Memo1.Lines.Add('Expected a nonempty value[i].parentReference.driveId in the JSON.');
                    Exit;
                  end;
                CkJsonObject_UpdateString(state,'parentReference.driveId',CkJsonObject__stringOf(result,'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 (CkJsonObject_HasMember(result,'value[i].size') = True) then
              begin
                CkJsonObject_UpdateString(state,'sizeBytes',CkJsonObject__stringOf(result,'value[i].size'));
              end;
            if (CkJsonObject_JsonTypeOf(result,'value[i].folder') = 3) then
              begin
                CkJsonObject_UpdateString(state,'kind','folder');
              end;
            if (CkJsonObject_JsonTypeOf(result,'value[i].file') = 3) then
              begin
                CkJsonObject_UpdateString(state,'kind','file');
              end;
            CkJsonObject_putPathPrefix(state,'');
            Memo1.Lines.Add('Updated local item: ' + itemId);
          end;
        CkJsonObject_putPathPrefix(state,'');
        i := i + 1;
      end;

    CkJsonObject_UpdateString(state,'resumeUrl',resumeUrl);
    CkJsonObject_UpdateBool(state,'roundComplete',finished);
    //  Save the data and cursor in one document. The backup contains the matching previous pair.
    success := CkJsonObject_WriteFile(previous,backupPath);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not back up the previous checkpoint; no replacement attempted.');
        Exit;
      end;
    success := CkJsonObject_WriteFile(state,cachePath);
    if (success <> True) then
      begin
        Memo1.Lines.Add('Checkpoint write failed. Restore the private .bak before continuing.');
        Exit;
      end;
    pageCount := pageCount + 1;
    if (finished = True) then
      begin
        Memo1.Lines.Add('Synchronization round complete; saved the delta link for the next run.');
        Exit;
      end;
  end;

Memo1.Lines.Add('Paused after 100 pages; the saved nextLink resumes on the next run.');

CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(result);
CkFileAccess_Dispose(fac);
CkJsonObject_Dispose(state);
    CkStringBuilder_Dispose(endpoint);
CkCrypt2_Dispose(hash);
CkStringBuilder_Dispose(link);
CkStringBuilder_Dispose(itemPath);
CkHashtable_Dispose(seenLinks);
CkJsonObject_Dispose(previous);