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 Delphi DLL Downloads
var
success: Boolean;
token: HCkJsonObject;
http: HCkHttp;
resp: HCkHttpResponse;
result: HCkJsonObject;
driveId: PWideChar;
itemId: PWideChar;
endpoint: HCkStringBuilder;
versionId: PWideChar;
foundVersion: Boolean;
url: PWideChar;
nextLink: HCkStringBuilder;
seenLinks: HCkHashtable;
pageCount: Integer;
i: Integer;
nextType: Integer;
contents: HCkBinData;
downloadUrl: PWideChar;
serviceUrl: HCkUrl;
downloadHttp: HCkHttp;
serviceHost: HCkStringBuilder;
tokenFiles: HCkFileAccess;
sharepointToken: HCkJsonObject;
downloadResponse: HCkHttpResponse;
fac: HCkFileAccess;
uuid: HCkCrypt2;
localId: PWideChar;
target: HCkStringBuilder;
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';
itemId := 'YOUR_ITEM_ID';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'https://graph.microsoft.com/v1.0/drives/');
CkStringBuilder_Append(endpoint,CkHttp__urlEncode(http,driveId));
CkStringBuilder_Append(endpoint,'/items/');
CkStringBuilder_Append(endpoint,CkHttp__urlEncode(http,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;
CkStringBuilder_Append(endpoint,'/versions');
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('Version ID: ' + CkJsonObject__stringOf(result,'value[i].id'));
Memo1.Lines.Add('Modified: ' + CkJsonObject__stringOf(result,'value[i].lastModifiedDateTime'));
Memo1.Lines.Add('Size in bytes: ' + CkJsonObject__stringOf(result,'value[i].size'));
if (CkJsonObject_StringOfEquals(result,'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 := 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));
if (versionId = '') then
begin
Memo1.Lines.Add('Listing only. Select a previous version ID to download.');
Exit;
end;
if (foundVersion <> True) then
begin
Memo1.Lines.Add('The selected version was not in the completed listing; nothing downloaded.');
Exit;
end;
CkStringBuilder_Append(endpoint,'/');
CkStringBuilder_Append(endpoint,CkHttp__urlEncode(http,versionId));
CkStringBuilder_Append(endpoint,'/content');
CkHttp_SetRequestHeader(http,'Accept','*/*');
success := CkHttp_HttpNoBody(http,'GET',CkStringBuilder__getAsString(endpoint),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) and (CkHttpResponse_getStatusCode(resp) <> 302)) 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;
contents := CkBinData_Create();
if (CkHttpResponse_getStatusCode(resp) = 200) then
begin
success := CkHttpResponse_GetBodyBd(resp,contents);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read the version bytes.');
Exit;
end;
end
else
begin
downloadUrl := CkHttpResponse__getHeaderField(resp,'Location');
serviceUrl := CkUrl_Create();
success := CkUrl_ParseUrl(serviceUrl,downloadUrl);
if (success <> True) then
begin
Memo1.Lines.Add('Invalid service URL.');
Exit;
end;
if ((CkUrl_getSsl(serviceUrl) <> True) or (CkUrl__host(serviceUrl) = '') or (CkUrl__login(serviceUrl) <> '') or (CkUrl__password(serviceUrl) <> '')) then
begin
Memo1.Lines.Add('Expected an HTTPS service URL without embedded login credentials.');
Exit;
end;
downloadHttp := CkHttp_Create();
CkHttp_putRequireSslCertVerify(downloadHttp,True);
CkHttp_putFollowRedirects(downloadHttp,False);
CkHttp_putConnectTimeout(downloadHttp,20);
CkHttp_putReadTimeout(downloadHttp,120);
serviceHost := CkStringBuilder_Create();
CkStringBuilder_Append(serviceHost,CkUrl__host(serviceUrl));
if ((CkStringBuilder_ContentsEqual(serviceHost,'graph.microsoft.com',False) = True) and (CkUrl_getPort(serviceUrl) = 443)) then
begin
CkHttp_putAuthToken(downloadHttp,CkJsonObject__stringOf(token,'access_token'));
end
else
begin
tokenFiles := CkFileAccess_Create();
if (CkFileAccess_FileExists(tokenFiles,'qa_data/tokens/oneDrive-sharepoint.json') = True) then
begin
sharepointToken := CkJsonObject_Create();
CkJsonObject_putStrict(sharepointToken,True);
success := CkJsonObject_LoadFile(sharepointToken,'qa_data/tokens/oneDrive-sharepoint.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not read the private SharePoint token cache.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(sharepointToken,'host') <> 1) or (CkJsonObject_StringOfEquals(sharepointToken,'host','',True) = True)) then
begin
Memo1.Lines.Add('Expected a nonempty host in the JSON.');
Exit;
end;
if ((CkJsonObject_JsonTypeOf(sharepointToken,'access_token') <> 1) or (CkJsonObject_StringOfEquals(sharepointToken,'access_token','',True) = True)) then
begin
Memo1.Lines.Add('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 ((CkStringBuilder_ContentsEqual(serviceHost,CkJsonObject__stringOf(sharepointToken,'host'),False) = True) and (CkUrl_getPort(serviceUrl) = 443)) then
begin
CkHttp_putAuthToken(downloadHttp,CkJsonObject__stringOf(sharepointToken,'access_token'));
end;
end;
end;
// With no matching token configured, only a still-valid preauthenticated URL can succeed.
downloadResponse := CkHttpResponse_Create();
success := CkHttp_HttpNoBody(downloadHttp,'GET',downloadUrl,downloadResponse);
if ((success <> True) and (CkHttpResponse_getStatusCode(downloadResponse) = 0)) then
begin
Memo1.Lines.Add('No HTTP response received; inspect diagnostics privately and reconcile writes before retrying.');
Exit;
end;
if ((CkHttpResponse_getStatusCode(downloadResponse) <> 200)) then
begin
Memo1.Lines.Add('Unexpected HTTP status: ' + IntToStr(CkHttpResponse_getStatusCode(downloadResponse)));
Memo1.Lines.Add('Request ID: ' + CkHttpResponse__getHeaderField(downloadResponse,'request-id'));
if (CkHttpResponse_getStatusCode(downloadResponse) = 429) then
begin
Memo1.Lines.Add('Retry-After: ' + CkHttpResponse__getHeaderField(downloadResponse,'Retry-After'));
end;
Exit;
end;
success := CkHttpResponse_GetBodyBd(downloadResponse,contents);
if (success <> True) then
begin
Memo1.Lines.Add('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 := CkFileAccess_Create();
success := CkFileAccess_DirEnsureExists(fac,'qa_output/oneDrive');
if (success <> True) then
begin
Memo1.Lines.Add('Could not create the output directory.');
Exit;
end;
uuid := CkCrypt2_Create();
localId := CkCrypt2__generateUuid(uuid);
if (CkCrypt2_getLastMethodSuccess(uuid) <> True) then
begin
Memo1.Lines.Add('Could not generate a local filename.');
Exit;
end;
target := CkStringBuilder_Create();
CkStringBuilder_Append(target,'qa_output/oneDrive/');
CkStringBuilder_Append(target,localId);
CkStringBuilder_Append(target,'.bin');
if (CkFileAccess_FileExists(fac,CkStringBuilder__getAsString(target)) = True) then
begin
Memo1.Lines.Add('The output file already exists; nothing overwritten.');
Exit;
end;
success := CkBinData_WriteFile(contents,CkStringBuilder__getAsString(target));
if (success <> True) then
begin
Memo1.Lines.Add('Could not write the downloaded version.');
Exit;
end;
Memo1.Lines.Add('Saved previous version: ' + CkStringBuilder__getAsString(target));
CkJsonObject_Dispose(token);
CkHttp_Dispose(http);
CkHttpResponse_Dispose(resp);
CkJsonObject_Dispose(result);
CkStringBuilder_Dispose(endpoint);
CkStringBuilder_Dispose(nextLink);
CkHashtable_Dispose(seenLinks);
CkBinData_Dispose(contents);
CkUrl_Dispose(serviceUrl);
CkHttp_Dispose(downloadHttp);
CkStringBuilder_Dispose(serviceHost);
CkFileAccess_Dispose(tokenFiles);
CkJsonObject_Dispose(sharepointToken);
CkHttpResponse_Dispose(downloadResponse);
CkFileAccess_Dispose(fac);
CkCrypt2_Dispose(uuid);
CkStringBuilder_Dispose(target);