OneDrive: List Versions and Download a Previous Version
See more OneDrive Examples
Enumerate a file's version history, then optionally download an explicitly selected older version. The default only lists. Keep version IDs such as 1.0 as strings and do not infer the latest version by numeric sorting. Available history and fields depend on the drive and retention settings. The version-content API cannot download the current version; use the ordinary file-content download example for that.
Accepts direct content or the documented redirect response. Binary bytes, including empty files, are saved to a generated local filename only after HTTP success. This demonstration buffers the version in memory; use streamed download handling for large files. Downloading a version does not restore or change the current file.
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.
Microsoft has announced changes to preauthenticated URLs beginning April 1, 2027. The example supports Graph-hosted URLs with the Graph token and an explicitly configured SharePoint host with a separate SharePoint-audience token. A legacy preauthenticated URL is requested without a bearer token. Never forward the Graph token to a SharePoint or content host. If required, prepare private qa_data/tokens/oneDrive-sharepoint.json with host and access_token from a separately authorized SharePoint token acquisition; token refresh must preserve that audience. A 401 requires checking the correct token audience or URL expiry, not blindly adding credentials.
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.
Chilkat Lazarus Pascal Downloads
program ChilkatDemo;
// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
CkDllLoader,
Chilkat.Http,
Chilkat.Url,
Chilkat.FileAccess,
Chilkat.HttpResponse,
Chilkat.StringBuilder,
Chilkat.JsonObject,
Chilkat.Crypt2,
Chilkat.StringArray,
Chilkat.BinData;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
token: TJsonObject;
http: THttp;
resp: THttpResponse;
result: TJsonObject;
driveId: string;
itemId: string;
endpoint: TStringBuilder;
versionId: string;
foundVersion: Boolean;
url: string;
nextLink: TStringBuilder;
seenLinks: TStringArray;
pageCount: Integer;
i: Integer;
nextType: Integer;
contents: TBinData;
downloadUrl: string;
serviceUrl: TUrl;
downloadHttp: THttp;
serviceHost: TStringBuilder;
tokenFiles: TFileAccess;
sharepointToken: TJsonObject;
downloadResponse: THttpResponse;
fac: TFileAccess;
uuid: TCrypt2;
localId: string;
target: TStringBuilder;
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 := TJsonObject.Create;
token.Strict := True;
success := token.LoadFile('qa_data/tokens/oneDrive.json');
if (success <> True) then
begin
WriteLn('Could not load the private OneDrive token cache.');
Exit;
end;
if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('Expected a nonempty access_token in the JSON.');
Exit;
end;
http := THttp.Create;
http.AuthToken := token.StringOf('access_token');
http.RequireSslCertVerify := True;
http.FollowRedirects := False;
http.ConnectTimeout := 20;
http.ReadTimeout := 120;
http.SetRequestHeader('Accept','application/json');
resp := THttpResponse.Create;
result := TJsonObject.Create;
result.Strict := True;
driveId := 'YOUR_DRIVE_ID';
itemId := 'YOUR_ITEM_ID';
endpoint := TStringBuilder.Create;
endpoint.Append('https://graph.microsoft.com/v1.0/drives/');
endpoint.Append(http.UrlEncode(driveId));
endpoint.Append('/items/');
endpoint.Append(http.UrlEncode(itemId));
// Leave empty to list only. Set an explicit previous version ID to download it.
// A version ID such as 1.0 is a STRING, not a decimal number.
versionId := '';
foundVersion := False;
endpoint.Append('/versions');
url := endpoint.GetAsString();
nextLink := TStringBuilder.Create;
seenLinks := TStringArray.Create;
pageCount := 0;
while ((url <> '') and (pageCount < 100)) do
begin
nextLink.SetString(url);
if (nextLink.StartsWith('https://graph.microsoft.com/v1.0/',True) <> True) then
begin
WriteLn('Unexpected pagination host or API version; no request sent.');
Exit;
end;
if (seenLinks.Find(url,0) >= 0) then
begin
WriteLn('Repeated pagination URL; stopping.');
Exit;
end;
seenLinks.Append(url);
success := http.HttpNoBody('GET',url,resp);
if ((success <> True) and (resp.StatusCode = 0)) then
begin
WriteLn('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((resp.StatusCode <> 200)) then
begin
WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
if (resp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
end;
Exit;
end;
success := result.Load(resp.BodyStr);
if (success <> True) then
begin
WriteLn('Expected a well-formed JSON response.');
Exit;
end;
if (result.JsonTypeOf('value') <> 4) then
begin
WriteLn('Expected a value array.');
Exit;
end;
i := 0;
while (i < result.SizeOfArray('value')) do
begin
result.I := i;
if ((result.JsonTypeOf('value[i].id') <> 1) or (result.StringOfEquals('value[i].id','',True) = True)) then
begin
WriteLn('Expected a nonempty value[i].id in the JSON.');
Exit;
end;
WriteLn('Version ID: ' + result.StringOf('value[i].id'));
WriteLn('Modified: ' + result.StringOf('value[i].lastModifiedDateTime'));
WriteLn('Size in bytes: ' + result.StringOf('value[i].size'));
if (result.StringOfEquals('value[i].id',versionId,True) = True) then
begin
foundVersion := True;
end;
i := i + 1;
end;
pageCount := pageCount + 1;
// A quoted JSON path treats the period in @odata.nextLink literally.
nextType := result.JsonTypeOf('"@odata.nextLink"');
if ((nextType = -1) or (nextType = 6)) then
begin
url := '';
end
else
begin
if ((nextType <> 1) or (result.StringOfEquals('"@odata.nextLink"','',True) = True)) then
begin
WriteLn('Invalid continuation link; cannot establish completeness.');
Exit;
end;
url := result.StringOf('"@odata.nextLink"');
end;
end;
if (url <> '') then
begin
WriteLn('Stopped at the example''s 100-page limit; save the continuation privately to resume.');
Exit;
end;
WriteLn('Completed pages: ' + pageCount);
if (versionId = '') then
begin
WriteLn('Listing only. Select a previous version ID to download.');
Exit;
end;
if (foundVersion <> True) then
begin
WriteLn('The selected version was not in the completed listing; nothing downloaded.');
Exit;
end;
endpoint.Append('/');
endpoint.Append(http.UrlEncode(versionId));
endpoint.Append('/content');
http.SetRequestHeader('Accept','*/*');
success := http.HttpNoBody('GET',endpoint.GetAsString(),resp);
if ((success <> True) and (resp.StatusCode = 0)) then
begin
WriteLn('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((resp.StatusCode <> 200) and (resp.StatusCode <> 302)) then
begin
WriteLn('Unexpected HTTP status: ' + resp.StatusCode);
WriteLn('Request ID: ' + resp.GetHeaderField('request-id'));
if (resp.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + resp.GetHeaderField('Retry-After'));
end;
Exit;
end;
contents := TBinData.Create;
if (resp.StatusCode = 200) then
begin
success := resp.GetBodyBd(contents);
if (success <> True) then
begin
WriteLn('Could not read the version bytes.');
Exit;
end;
end
else
begin
downloadUrl := resp.GetHeaderField('Location');
serviceUrl := TUrl.Create;
success := serviceUrl.ParseUrl(downloadUrl);
if (success <> True) then
begin
WriteLn('Invalid service URL.');
Exit;
end;
if ((serviceUrl.Ssl <> True) or (serviceUrl.Host = '') or (serviceUrl.Login <> '') or (serviceUrl.Password <> '')) then
begin
WriteLn('Expected an HTTPS service URL without embedded login credentials.');
Exit;
end;
downloadHttp := THttp.Create;
downloadHttp.RequireSslCertVerify := True;
downloadHttp.FollowRedirects := False;
downloadHttp.ConnectTimeout := 20;
downloadHttp.ReadTimeout := 120;
serviceHost := TStringBuilder.Create;
serviceHost.Append(serviceUrl.Host);
if ((serviceHost.ContentsEqual('graph.microsoft.com',False) = True) and (serviceUrl.Port = 443)) then
begin
downloadHttp.AuthToken := token.StringOf('access_token');
end
else
begin
tokenFiles := TFileAccess.Create;
if (tokenFiles.FileExists('qa_data/tokens/oneDrive-sharepoint.json') = True) then
begin
sharepointToken := TJsonObject.Create;
sharepointToken.Strict := True;
success := sharepointToken.LoadFile('qa_data/tokens/oneDrive-sharepoint.json');
if (success <> True) then
begin
WriteLn('Could not read the private SharePoint token cache.');
Exit;
end;
if ((sharepointToken.JsonTypeOf('host') <> 1) or (sharepointToken.StringOfEquals('host','',True) = True)) then
begin
WriteLn('Expected a nonempty host in the JSON.');
Exit;
end;
if ((sharepointToken.JsonTypeOf('access_token') <> 1) or (sharepointToken.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('Expected a nonempty access_token in the JSON.');
Exit;
end;
// host is a configured exact hostname, not a URL and not obtained from the service response.
if ((serviceHost.ContentsEqual(sharepointToken.StringOf('host'),False) = True) and (serviceUrl.Port = 443)) then
begin
downloadHttp.AuthToken := sharepointToken.StringOf('access_token');
end;
end;
end;
// With no matching token configured, only a still-valid preauthenticated URL can succeed.
downloadResponse := THttpResponse.Create;
success := downloadHttp.HttpNoBody('GET',downloadUrl,downloadResponse);
if ((success <> True) and (downloadResponse.StatusCode = 0)) then
begin
WriteLn('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((downloadResponse.StatusCode <> 200)) then
begin
WriteLn('Unexpected HTTP status: ' + downloadResponse.StatusCode);
WriteLn('Request ID: ' + downloadResponse.GetHeaderField('request-id'));
if (downloadResponse.StatusCode = 429) then
begin
WriteLn('Retry-After: ' + downloadResponse.GetHeaderField('Retry-After'));
end;
Exit;
end;
success := downloadResponse.GetBodyBd(contents);
if (success <> True) then
begin
WriteLn('Could not read the version download.');
Exit;
end;
end;
// Hold binary bytes without text conversion. This example expects a version that fits in memory.
fac := TFileAccess.Create;
success := fac.DirEnsureExists('qa_output/oneDrive');
if (success <> True) then
begin
WriteLn('Could not create the output directory.');
Exit;
end;
uuid := TCrypt2.Create;
localId := uuid.GenerateUuid();
if (uuid.LastMethodSuccess <> True) then
begin
WriteLn('Could not generate a local filename.');
Exit;
end;
target := TStringBuilder.Create;
target.Append('qa_output/oneDrive/');
target.Append(localId);
target.Append('.bin');
if (fac.FileExists(target.GetAsString()) = True) then
begin
WriteLn('The output file already exists; nothing overwritten.');
Exit;
end;
success := contents.WriteFile(target.GetAsString());
if (success <> True) then
begin
WriteLn('Could not write the downloaded version.');
Exit;
end;
WriteLn('Saved previous version: ' + target.GetAsString());
token.Free;
http.Free;
resp.Free;
result.Free;
endpoint.Free;
nextLink.Free;
seenLinks.Free;
contents.Free;
serviceUrl.Free;
downloadHttp.Free;
serviceHost.Free;
tokenFiles.Free;
sharepointToken.Free;
downloadResponse.Free;
fac.Free;
uuid.Free;
target.Free;
end;
// ---------------------------------------------------------------------------
begin
try
RunDemo;
except
on E: Exception do
WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
end;
WriteLn;
{$IFDEF MSWINDOWS}
WriteLn('Press Enter to exit...');
ReadLn;
{$ENDIF}
end.