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

Amazon S3: Download a Version or Remove a Delete Marker

See more S3 - REST Examples

The default download mode reads a selected data version without changing the current object. Requires s3:GetObjectVersion. Choose an opaque version ID from the versions listing, including the string null when appropriate. An archived version may first need restoration.

Recovery mode changes version history: set operation to remove-delete-marker and supply the particular marker ID. HEAD with that versionId must return 405 and x-amz-delete-marker=true before the code issues DELETE. A normal data version is never deleted by this branch. Requires s3:DeleteObjectVersion; MFA Delete can impose additional requirements not implemented here. Removing a current marker can expose an older version, but other remaining markers can still hide the object. List versions again; do not assume recovery is complete.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS GetObject reference

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
textCompare: HCkStringBuilder;
credentials: HCkJsonObject;
sameText1: Boolean;
sameText2: Boolean;
region: PWideChar;
bucketName: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
sameText3: Boolean;
connection: HCkSocket;
xml: HCkXml;
objectKey: PWideChar;
objectPath: HCkStringBuilder;
restoredSlashes: Integer;
versionId: PWideChar;
operation: PWideChar;
sameText4: Boolean;
sameText5: Boolean;
sameText6: Boolean;
markerStatus: Integer;
marker: PWideChar;
sameText7: Boolean;
responseBody: PWideChar;
sameText8: Boolean;
files: HCkFileAccess;
statusCode: Integer;
errorBody: PWideChar;
sameText9: Boolean;
returnedVersion: PWideChar;
sameText10: Boolean;
sameText11: Boolean;
expectedLength: PWideChar;
sameText12: Boolean;
output: HCkStream;
actualLength: PWideChar;
sameText13: Boolean;

begin
success := False;

//  StringBuilder compares text by value in every generated language.
textCompare := CkStringBuilder_Create();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
success := False;
//  Private configuration, not a file in public web content or source control.
//  Load current IAM credentials authorized for the S3 operation.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/s3.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private AWS credentials.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'access_key'));
sameText1 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (sameText1 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'secret_key'));
sameText2 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (sameText2 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
//  General purpose bucket in the commercial AWS partition.
region := 'us-west-2';
bucketName := 'amzn-s3-demo-bucket';
endpoint := CkStringBuilder_Create();
success := CkStringBuilder_Append(endpoint,bucketName);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,'.');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,'s3.');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,region);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Append(endpoint,'.amazonaws.com');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'s3');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure AWS signing.');
    Exit;
  end;
//  Temporary credentials require this token in every signed query.
//  Keep request URLs private. Do not clear this parameter between requests.
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    if (CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) then
      begin
        Memo1.Lines.Add('session_token must be a string.');
        Exit;
      end;
    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'session_token'));
    sameText3 := CkStringBuilder_ContentsEqual(textCompare,'',True);
    if (sameText3 <> True) then
      begin
        success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
        if (success <> True) then
          begin
            Memo1.Lines.Add('Could not prepare the request.');
            Exit;
          end;
      end;
  end;
//  Connect to the SAME hostname used for TLS verification and request signing.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach the TLS connection.');
    Exit;
  end;
xml := CkXml_Create();
CkXml_putStrict(xml,True);
//  Supply an unencoded object key, not a URL. Preserve slashes in the key.
objectKey := 'documents/example.txt';
objectPath := CkStringBuilder_Create();
success := CkStringBuilder_Append(objectPath,objectKey);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not build text.');
    Exit;
  end;
success := CkStringBuilder_Encode(objectPath,'url_rfc3986','utf-8');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not encode the object key.');
    Exit;
  end;
restoredSlashes := CkStringBuilder_Replace(objectPath,'%2F','/');
success := CkStringBuilder_Prepend(objectPath,'/');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
//  Select an ID from ListObjectVersions. Never parse it as a number.
versionId := 'YOUR_VERSION_ID';
operation := 'download';
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,operation);
sameText4 := CkStringBuilder_ContentsEqual(textCompare,'download',True);
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,operation);
sameText5 := CkStringBuilder_ContentsEqual(textCompare,'remove-delete-marker',True);
if ((sameText4 <> True) and (sameText5 <> True)) then
  begin
    Memo1.Lines.Add('Choose download or remove-delete-marker.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'versionId',versionId);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not prepare the request.');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,operation);
sameText6 := CkStringBuilder_ContentsEqual(textCompare,'remove-delete-marker',True);
if (sameText6 = True) then
  begin
    //  This permanently removes ONLY the selected marker, not a data version.
    success := CkRest_SendReqNoBody(rest,'HEAD',CkStringBuilder__getAsString(objectPath));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not send HEAD request.');
        Exit;
      end;
    markerStatus := CkRest_ReadResponseHeader(rest);
    if (markerStatus < 0) then
      begin
        Memo1.Lines.Add('Could not read the response header.');
        Exit;
      end;
    //  HEAD has no response body; do not call a body-reading method.
    marker := CkRest__responseHdrByName(rest,'x-amz-delete-marker');
    if (CkRest_getLastMethodSuccess(rest) <> True) then
      begin
        marker := '';
      end;
    CkStringBuilder_Clear(textCompare);
    CkStringBuilder_SetString(textCompare,marker);
    sameText7 := CkStringBuilder_ContentsEqual(textCompare,'true',True);
    if ((markerStatus <> 405) or (sameText7 <> True)) then
      begin
        Memo1.Lines.Add('Selected ID was not confirmed as a delete marker; nothing was deleted.');
        Exit;
      end;
    responseBody := CkRest__fullRequestNoBody(rest,'DELETE',CkStringBuilder__getAsString(objectPath));
    if (CkRest_getLastMethodSuccess(rest) <> True) then
      begin
        Memo1.Lines.Add('Request did not complete; inspect diagnostics privately.');
        Exit;
      end;
    if (CkRest_getResponseStatusCode(rest) <> 204) then
      begin
        Memo1.Lines.Add('S3 HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
        success := CkXml_LoadXml(xml,responseBody);
        CkStringBuilder_Clear(textCompare);
        CkStringBuilder_SetString(textCompare,CkXml__tag(xml));
        sameText8 := CkStringBuilder_ContentsEqual(textCompare,'Error',True);
        if ((success = True) and (sameText8 = True)) then
          begin
            Memo1.Lines.Add('S3 error code: ' + CkXml__getChildContent(xml,'Code'));
          end;
        //  Keep signed headers, credentials, URLs, and full diagnostics private.
        //  A timeout may leave a write's outcome uncertain. Check before retrying.
        Exit;
      end;
    Memo1.Lines.Add('Selected delete marker removed. List versions again to inspect the current entry.');
    //  Other markers can still hide the object. Do not automatically delete those.
    Exit;
  end;
files := CkFileAccess_Create();
if (CkFileAccess_FileExists(files,'s3-version-download.part') = True) then
  begin
    Memo1.Lines.Add('Choose an unused output path.');
    Exit;
  end;
success := CkRest_SendReqNoBody(rest,'GET',CkStringBuilder__getAsString(objectPath));
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not send download request.');
    Exit;
  end;
statusCode := CkRest_ReadResponseHeader(rest);
if (statusCode < 0) then
  begin
    Memo1.Lines.Add('Could not read download headers.');
    Exit;
  end;
if (statusCode <> 200) then
  begin
    Memo1.Lines.Add('Download HTTP status: ' + IntToStr(statusCode));
    errorBody := CkRest__readRespBodyString(rest);
    if (CkRest_getLastMethodSuccess(rest) = True) then
      begin
        success := CkXml_LoadXml(xml,errorBody);
        CkStringBuilder_Clear(textCompare);
        CkStringBuilder_SetString(textCompare,CkXml__tag(xml));
        sameText9 := CkStringBuilder_ContentsEqual(textCompare,'Error',True);
        if ((success = True) and (sameText9 = True)) then
          begin
            Memo1.Lines.Add('S3 error code: ' + CkXml__getChildContent(xml,'Code'));
          end;
      end;
    Exit;
  end;
returnedVersion := CkRest__responseHdrByName(rest,'x-amz-version-id');
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,returnedVersion);
sameText10 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkRest_getLastMethodSuccess(rest) <> True) or (sameText10 = True)) then
  begin
    Memo1.Lines.Add('Missing response header: x-amz-version-id');
    Exit;
  end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,returnedVersion);
sameText11 := CkStringBuilder_ContentsEqual(textCompare,versionId,True);
if (sameText11 <> True) then
  begin
    Memo1.Lines.Add('Unexpected version returned; output was not written.');
    Exit;
  end;
expectedLength := CkRest__responseHdrByName(rest,'Content-Length');
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,expectedLength);
sameText12 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkRest_getLastMethodSuccess(rest) <> True) or (sameText12 = True)) then
  begin
    Memo1.Lines.Add('Missing response header: Content-Length');
    Exit;
  end;
output := CkStream_Create();
CkStream_putSinkFile(output,'s3-version-download.part');
success := CkRest_ReadRespBodyStream(rest,output,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Download incomplete; do not publish the partial file.');
    Exit;
  end;
actualLength := CkFileAccess__fileSizeStr(files,'s3-version-download.part');
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,actualLength);
sameText13 := CkStringBuilder_ContentsEqual(textCompare,expectedLength,True);
if ((CkFileAccess_getLastMethodSuccess(files) <> True) or (sameText13 <> True)) then
  begin
    Memo1.Lines.Add('Downloaded length mismatch.');
    Exit;
  end;
Memo1.Lines.Add('Selected version downloaded to s3-version-download.part.');

CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(objectPath);
CkFileAccess_Dispose(files);
CkStream_Dispose(output);