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

OneDrive: Use Application Credentials for Microsoft 365

See more OneDrive Examples

Retains Chilkat.Http's automatic OAuth2 client-credentials support: AuthToken can contain the credential JSON, and Http obtains and caches tokens internally. Load tenant_id, client_id, client_secret, and user_id from private onedrive-app.json. Keep this file outside public web content and source control; use protected configuration in production. Reuse the Http object to benefit from its token cache.

This is for a controlled application accessing Microsoft 365 OneDrive for Business or SharePoint. It is not personal OneDrive authentication and must not embed an application secret in software distributed to the public. Grant application Files.Read.All and administrator consent for this listing request, or use an appropriate supported restricted-access design. A consented permission does not provision a user's OneDrive. Use a tenant-specific authority and explicitly address the user, site, or drive; never /me. App-only tokens have no refresh token.

Follows complete @odata.nextLink URLs, including after empty pages. It validates the Graph host/API path, rejects repeated links, and reports a stop at the demonstration bound of 100 pages. $top is page size, not the total result count. Enumeration is not a transactionally consistent snapshot during concurrent changes.

Permission: Application Files.Read.All for this request.

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;
config: HCkJsonObject;
http: HCkHttp;
credentials: HCkJsonObject;
tokenEndpoint: HCkStringBuilder;
resp: HCkHttpResponse;
result: HCkJsonObject;
endpoint: HCkStringBuilder;
url: PWideChar;
nextLink: HCkStringBuilder;
seenLinks: HCkHashtable;
pageCount: Integer;
i: Integer;
nextType: Integer;

begin
success := False;

//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
//  Private file: tenant_id, client_id, client_secret, and user_id (object ID or UPN).
//  The secret VALUE is required, not its secret identifier.
config := CkJsonObject_Create();
CkJsonObject_putStrict(config,True);
success := CkJsonObject_LoadFile(config,'onedrive-app.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load the private application configuration.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(config,'tenant_id') <> 1) or (CkJsonObject_StringOfEquals(config,'tenant_id','',True) = True)) then
  begin
    Memo1.Lines.Add('Expected a nonempty tenant_id in the JSON.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(config,'client_id') <> 1) or (CkJsonObject_StringOfEquals(config,'client_id','',True) = True)) then
  begin
    Memo1.Lines.Add('Expected a nonempty client_id in the JSON.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(config,'client_secret') <> 1) or (CkJsonObject_StringOfEquals(config,'client_secret','',True) = True)) then
  begin
    Memo1.Lines.Add('Expected a nonempty client_secret in the JSON.');
    Exit;
  end;
if ((CkJsonObject_JsonTypeOf(config,'user_id') <> 1) or (CkJsonObject_StringOfEquals(config,'user_id','',True) = True)) then
  begin
    Memo1.Lines.Add('Expected a nonempty user_id in the JSON.');
    Exit;
  end;
http := CkHttp_Create();
credentials := CkJsonObject_Create();
CkJsonObject_UpdateString(credentials,'client_id',CkJsonObject__stringOf(config,'client_id'));
CkJsonObject_UpdateString(credentials,'client_secret',CkJsonObject__stringOf(config,'client_secret'));
CkJsonObject_UpdateString(credentials,'scope','https://graph.microsoft.com/.default');
tokenEndpoint := CkStringBuilder_Create();
CkStringBuilder_Append(tokenEndpoint,'https://login.microsoftonline.com/');
CkStringBuilder_Append(tokenEndpoint,CkHttp__urlEncode(http,CkJsonObject__stringOf(config,'tenant_id')));
CkStringBuilder_Append(tokenEndpoint,'/oauth2/v2.0/token');
CkJsonObject_UpdateString(credentials,'token_endpoint',CkStringBuilder__getAsString(tokenEndpoint));
//  Http recognizes this credential JSON and acquires/caches application tokens internally.
//  Reuse the Http object for subsequent requests; never print the credential JSON.
CkHttp_putAuthToken(http,CkJsonObject__emit(credentials));
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);
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'https://graph.microsoft.com/v1.0/users/');
CkStringBuilder_Append(endpoint,CkHttp__urlEncode(http,CkJsonObject__stringOf(config,'user_id')));
CkStringBuilder_Append(endpoint,'/drives?$select=id,name,driveType,quota&$top=50');
url := CkStringBuilder__getAsString(endpoint);
nextLink := CkStringBuilder_Create();
seenLinks := CkHashtable_Create();
pageCount := 0;
while ((url <> '') and (pageCount < 100)) do
  begin
    CkStringBuilder_SetString(nextLink,url);
    if (CkStringBuilder_StartsWith(nextLink,'https://graph.microsoft.com/v1.0/',True) <> True) then
      begin
        Memo1.Lines.Add('Unexpected pagination host or API version; no request sent.');
        Exit;
      end;
    if (CkHashtable_Contains(seenLinks,url) = True) then
      begin
        Memo1.Lines.Add('Repeated pagination URL; stopping.');
        Exit;
      end;
    CkHashtable_AddInt(seenLinks,url,1);
    success := CkHttp_HttpNoBody(http,'GET',url,resp);
    if ((success <> True) and (CkHttpResponse_getStatusCode(resp) = 0)) then
      begin
        Memo1.Lines.Add('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
        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;
        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.');
        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;
        Memo1.Lines.Add('Drive ID: ' + CkJsonObject__stringOf(result,'value[i].id'));
        Memo1.Lines.Add('Name: ' + CkJsonObject__stringOf(result,'value[i].name'));
        Memo1.Lines.Add('Drive type: ' + CkJsonObject__stringOf(result,'value[i].driveType'));
        //  Quota values can be larger than int. Missing quota fields are not zero.
        if (CkJsonObject_HasMember(result,'value[i].quota.total') = True) then
          begin
            Memo1.Lines.Add('Total bytes: ' + CkJsonObject__stringOf(result,'value[i].quota.total'));
            Memo1.Lines.Add('Remaining bytes: ' + CkJsonObject__stringOf(result,'value[i].quota.remaining'));
          end;
        i := i + 1;
      end;

    pageCount := pageCount + 1;
    //  A quoted JSON path treats the period in @odata.nextLink literally.
    nextType := CkJsonObject_JsonTypeOf(result,'"@odata.nextLink"');
    if ((nextType = -1) or (nextType = 6)) then
      begin
        url := '';
      end
    else
      begin
        if ((nextType <> 1) or (CkJsonObject_StringOfEquals(result,'"@odata.nextLink"','',True) = True)) then
          begin
            Memo1.Lines.Add('Invalid continuation link; cannot establish completeness.');
            Exit;
          end;
        url := CkJsonObject__stringOf(result,'"@odata.nextLink"');
      end;
  end;

if (url <> '') then
  begin
    Memo1.Lines.Add('Stopped at the example''s 100-page limit; save the continuation privately to resume.');
    Exit;
  end;
Memo1.Lines.Add('Completed pages: ' + IntToStr(pageCount));

CkJsonObject_Dispose(config);
CkHttp_Dispose(http);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(tokenEndpoint);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(result);
CkStringBuilder_Dispose(endpoint);
CkStringBuilder_Dispose(nextLink);
CkHashtable_Dispose(seenLinks);