Amazon S3: Delete Multiple Objects and Check Each Result
See more S3 - REST Examples
Deletes the explicitly supplied objects. Load qa_data/aws/delete-objects.json with {"objects":[{"key":"documents/old.txt"},{"key":"documents/older.txt","version_id":"VERSION_ID"}]}. Supply 1–1000 unique entries per request. The example does not enumerate a prefix or automatically retry. Requires s3:DeleteObject and, for explicit versions, s3:DeleteObjectVersion.
Without versionId, an unversioned object is permanently removed; a versioned bucket normally creates a delete marker. Explicit data-version deletion is permanent. Retention, legal holds and MFA Delete can restrict deletion. Absent keys can still be acknowledged as deleted. HTTP 200 may contain per-object errors; each returned key/version is matched against the intended batch. Reconcile uncertain or missing results before any retry.
General purpose DeleteObjects uses Content-MD5. The tested AuthAws path omits that header, so this example explicitly constructs Signature Version 4 for the fixed POST /?delete= request and sends it through Rest. This is deliberately not a general URL signer. Do not change the body, hostname, query, or signed headers after signing, or attach AuthAws as a second signer.
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.
Chilkat Delphi DLL Downloads
var
success: Boolean;
textCompare: HCkStringBuilder;
credentials: HCkJsonObject;
sameText1: Boolean;
sameText2: Boolean;
region: PWideChar;
bucketName: PWideChar;
endpoint: HCkStringBuilder;
rest: HCkRest;
connection: HCkSocket;
xml: HCkXml;
batch: HCkJsonObject;
count: Integer;
requested: HCkHashtable;
identity: HCkJsonObject;
i: Integer;
sameText3: Boolean;
key: PWideChar;
version: PWideChar;
sameText4: Boolean;
requestIdentity: PWideChar;
requestBody: PWideChar;
host: HCkStringBuilder;
now: HCkDateTime;
timestamp: HCkStringBuilder;
removedDashes: Integer;
removedColons: Integer;
amzDate: PWideChar;
dateStamp: PWideChar;
crypt: HCkCrypt2;
contentMd5: PWideChar;
payloadHash: PWideChar;
signedHeaders: HCkStringBuilder;
canonical: HCkStringBuilder;
sameText5: Boolean;
canonicalHash: PWideChar;
scope: HCkStringBuilder;
stringToSign: HCkStringBuilder;
initialKey: HCkStringBuilder;
derivedKey: PWideChar;
signature: PWideChar;
authorization: HCkStringBuilder;
responseBody: PWideChar;
sameText6: Boolean;
sameText7: Boolean;
deleted: Integer;
failed: Integer;
received: HCkHashtable;
resultType: Integer;
itemTag: PWideChar;
resultCount: Integer;
j: Integer;
itemPath: HCkStringBuilder;
item: HCkXml;
resultKey: PWideChar;
resultVersion: PWideChar;
responseIdentity: PWideChar;
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;
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
// 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);
CkRest_putHost(rest,CkStringBuilder__getAsString(endpoint));
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;
end;
// One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
batch := CkJsonObject_Create();
CkJsonObject_putStrict(batch,True);
success := CkJsonObject_LoadFile(batch,'qa_data/aws/delete-objects.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load the intended deletion batch.');
Exit;
end;
count := CkJsonObject_SizeOfArray(batch,'objects');
if ((count < 1) or (count > 1000)) then
begin
Memo1.Lines.Add('Supply 1 to 1000 objects in the batch.');
Exit;
end;
CkXml_putTag(xml,'Delete');
success := CkXml_AddAttribute(xml,'xmlns','http://s3.amazonaws.com/doc/2006-03-01/');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
CkXml_UpdateChildContent(xml,'Quiet','false');
requested := CkHashtable_Create();
identity := CkJsonObject_Create();
i := 0;
while (i < count) do
begin
CkJsonObject_putI(batch,i);
CkXml_putI(xml,i);
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(batch,'objects[i].key'));
sameText3 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkJsonObject_JsonTypeOf(batch,'objects[i].key') <> 1) or (sameText3 = True)) then
begin
Memo1.Lines.Add('Each object needs a nonempty key.');
Exit;
end;
key := CkJsonObject__stringOf(batch,'objects[i].key');
version := '';
if (CkJsonObject_HasMember(batch,'objects[i].version_id') = True) then
begin
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(batch,'objects[i].version_id'));
sameText4 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if ((CkJsonObject_JsonTypeOf(batch,'objects[i].version_id') <> 1) or (sameText4 = True)) then
begin
Memo1.Lines.Add('version_id must be a nonempty string when present.');
Exit;
end;
version := CkJsonObject__stringOf(batch,'objects[i].version_id');
CkXml_UpdateChildContent(xml,'Object[i]|VersionId',version);
end;
CkXml_UpdateChildContent(xml,'Object[i]|Key',key);
success := CkJsonObject_UpdateString(identity,'key',key);
if (success <> True) then
begin
Memo1.Lines.Add('Could not build saved state.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'version',version);
if (success <> True) then
begin
Memo1.Lines.Add('Could not build saved state.');
Exit;
end;
requestIdentity := CkJsonObject__emit(identity);
if (CkHashtable_Contains(requested,requestIdentity) = True) then
begin
Memo1.Lines.Add('Duplicate key/version in deletion batch.');
Exit;
end;
success := CkHashtable_AddInt(requested,requestIdentity,1);
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
i := i + 1;
end;
requestBody := CkXml__getXml(xml);
// Explicit signing is used only for this fixed request so Content-MD5 survives.
// Rest sends it; AuthAws must NOT also be configured on this Rest instance.
// Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
// Do not change signed headers, body, endpoint, or query after signing.
host := CkStringBuilder_Create();
CkStringBuilder_Append(host,CkStringBuilder__getAsString(endpoint));
now := CkDateTime_Create();
success := CkDateTime_SetFromCurrentSystemTime(now);
if (success <> True) then
begin
Memo1.Lines.Add('Could not read system time.');
Exit;
end;
timestamp := CkStringBuilder_Create();
CkStringBuilder_Append(timestamp,CkDateTime__getAsTimestamp(now,False));
removedDashes := CkStringBuilder_Replace(timestamp,'-','');
removedColons := CkStringBuilder_Replace(timestamp,':','');
amzDate := CkStringBuilder__getAsString(timestamp);
dateStamp := CkStringBuilder__getRange(timestamp,0,8,False);
crypt := CkCrypt2_Create();
CkCrypt2_putCharset(crypt,'utf-8');
CkCrypt2_putHashAlgorithm(crypt,'md5');
CkCrypt2_putEncodingMode(crypt,'base64');
contentMd5 := CkCrypt2__hashStringENC(crypt,requestBody);
if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
begin
Memo1.Lines.Add('Could not hash delete body.');
Exit;
end;
CkCrypt2_putHashAlgorithm(crypt,'sha256');
CkCrypt2_putEncodingMode(crypt,'hexlower');
payloadHash := CkCrypt2__hashStringENC(crypt,requestBody);
if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
begin
Memo1.Lines.Add('Could not hash delete body.');
Exit;
end;
signedHeaders := CkStringBuilder_Create();
CkStringBuilder_Append(signedHeaders,'content-md5;host;x-amz-content-sha256;x-amz-date');
canonical := CkStringBuilder_Create();
CkStringBuilder_Append(canonical,'POST' + #10 + '/' + #10 + 'delete=' + #10 + 'content-md5:');
CkStringBuilder_Append(canonical,contentMd5);
CkStringBuilder_Append(canonical,#10 + 'host:');
CkStringBuilder_Append(canonical,CkStringBuilder__getAsString(host));
CkStringBuilder_Append(canonical,#10 + 'x-amz-content-sha256:');
CkStringBuilder_Append(canonical,payloadHash);
CkStringBuilder_Append(canonical,#10 + 'x-amz-date:');
CkStringBuilder_Append(canonical,amzDate);
CkStringBuilder_Append(canonical,#10);
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
begin
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkJsonObject__stringOf(credentials,'session_token'));
sameText5 := CkStringBuilder_ContentsEqual(textCompare,'',True);
if (sameText5 <> True) then
begin
CkStringBuilder_Append(signedHeaders,';x-amz-security-token');
CkStringBuilder_Append(canonical,'x-amz-security-token:');
CkStringBuilder_Append(canonical,CkJsonObject__stringOf(credentials,'session_token'));
CkStringBuilder_Append(canonical,#10);
success := CkRest_AddHeader(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;
CkStringBuilder_Append(canonical,#10);
CkStringBuilder_Append(canonical,CkStringBuilder__getAsString(signedHeaders));
CkStringBuilder_Append(canonical,#10);
CkStringBuilder_Append(canonical,payloadHash);
canonicalHash := CkCrypt2__hashStringENC(crypt,CkStringBuilder__getAsString(canonical));
if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
begin
Memo1.Lines.Add('Could not hash canonical request.');
Exit;
end;
scope := CkStringBuilder_Create();
CkStringBuilder_Append(scope,dateStamp);
CkStringBuilder_Append(scope,'/');
CkStringBuilder_Append(scope,region);
CkStringBuilder_Append(scope,'/s3/aws4_request');
stringToSign := CkStringBuilder_Create();
CkStringBuilder_Append(stringToSign,'AWS4-HMAC-SHA256' + #10);
CkStringBuilder_Append(stringToSign,amzDate);
CkStringBuilder_Append(stringToSign,#10);
CkStringBuilder_Append(stringToSign,CkStringBuilder__getAsString(scope));
CkStringBuilder_Append(stringToSign,#10);
CkStringBuilder_Append(stringToSign,canonicalHash);
initialKey := CkStringBuilder_Create();
CkStringBuilder_Append(initialKey,'AWS4');
CkStringBuilder_Append(initialKey,CkJsonObject__stringOf(credentials,'secret_key'));
CkCrypt2_putMacAlgorithm(crypt,'hmac');
success := CkCrypt2_SetMacKeyString(crypt,CkStringBuilder__getAsString(initialKey));
if (success <> True) then
begin
Memo1.Lines.Add('Could not set signing key.');
Exit;
end;
derivedKey := CkCrypt2__macStringENC(crypt,dateStamp);
if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
begin
Memo1.Lines.Add('Could not derive date signing key.');
Exit;
end;
success := CkCrypt2_SetMacKeyEncoded(crypt,derivedKey,'hex');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set derived signing key.');
Exit;
end;
derivedKey := CkCrypt2__macStringENC(crypt,region);
if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := CkCrypt2_SetMacKeyEncoded(crypt,derivedKey,'hex');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set derived signing key.');
Exit;
end;
derivedKey := CkCrypt2__macStringENC(crypt,'s3');
if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := CkCrypt2_SetMacKeyEncoded(crypt,derivedKey,'hex');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set derived signing key.');
Exit;
end;
derivedKey := CkCrypt2__macStringENC(crypt,'aws4_request');
if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
begin
Memo1.Lines.Add('Could not derive signing key.');
Exit;
end;
success := CkCrypt2_SetMacKeyEncoded(crypt,derivedKey,'hex');
if (success <> True) then
begin
Memo1.Lines.Add('Could not set final signing key.');
Exit;
end;
signature := CkCrypt2__macStringENC(crypt,CkStringBuilder__getAsString(stringToSign));
if (CkCrypt2_getLastMethodSuccess(crypt) <> True) then
begin
Memo1.Lines.Add('Could not sign delete request.');
Exit;
end;
authorization := CkStringBuilder_Create();
CkStringBuilder_Append(authorization,'AWS4-HMAC-SHA256 Credential=');
CkStringBuilder_Append(authorization,CkJsonObject__stringOf(credentials,'access_key'));
CkStringBuilder_Append(authorization,'/');
CkStringBuilder_Append(authorization,CkStringBuilder__getAsString(scope));
CkStringBuilder_Append(authorization,', SignedHeaders=');
CkStringBuilder_Append(authorization,CkStringBuilder__getAsString(signedHeaders));
CkStringBuilder_Append(authorization,', Signature=');
CkStringBuilder_Append(authorization,signature);
success := CkRest_AddHeader(rest,'Authorization',CkStringBuilder__getAsString(authorization));
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := CkRest_AddHeader(rest,'Content-MD5',contentMd5);
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := CkRest_AddHeader(rest,'x-amz-content-sha256',payloadHash);
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := CkRest_AddHeader(rest,'x-amz-date',amzDate);
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
success := CkRest_AddQueryParam(rest,'delete','');
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
responseBody := CkRest__fullRequestString(rest,'POST','/',requestBody);
if (CkRest_getLastMethodSuccess(rest) <> True) then
begin
Memo1.Lines.Add('Request did not complete; inspect diagnostics privately.');
Exit;
end;
if (CkRest_getResponseStatusCode(rest) <> 200) 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));
sameText6 := CkStringBuilder_ContentsEqual(textCompare,'Error',True);
if ((success = True) and (sameText6 = 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;
success := CkXml_LoadXml(xml,responseBody);
if (success <> True) then
begin
Memo1.Lines.Add('Expected well-formed XML.');
Exit;
end;
CkStringBuilder_Clear(textCompare);
CkStringBuilder_SetString(textCompare,CkXml__tag(xml));
sameText7 := CkStringBuilder_ContentsEqual(textCompare,'DeleteResult',True);
if (sameText7 <> True) then
begin
Memo1.Lines.Add('Unexpected S3 response element; this is not a successful result.');
Exit;
end;
deleted := CkXml_NumChildrenHavingTag(xml,'Deleted');
failed := CkXml_NumChildrenHavingTag(xml,'Error');
if (deleted + failed <> count) then
begin
Memo1.Lines.Add('Incomplete result: reconcile every requested object before retrying.');
Exit;
end;
received := CkHashtable_Create();
resultType := 0;
while (resultType < 2) do
begin
itemTag := 'Deleted';
resultCount := deleted;
if (resultType = 1) then
begin
itemTag := 'Error';
resultCount := failed;
end;
j := 0;
while (j < resultCount) do
begin
CkXml_putI(xml,j);
itemPath := CkStringBuilder_Create();
success := CkStringBuilder_Append(itemPath,itemTag);
if (success <> True) then
begin
Memo1.Lines.Add('Could not build text.');
Exit;
end;
success := CkStringBuilder_Append(itemPath,'[i]');
if (success <> True) then
begin
Memo1.Lines.Add('Could not build text.');
Exit;
end;
item := CkXml_FindChild(xml,CkStringBuilder__getAsString(itemPath));
if (CkXml_getLastMethodSuccess(xml) <> True) then
begin
Memo1.Lines.Add('Missing deletion result entry.');
Exit;
end;
resultKey := CkXml__getChildContent(item,'Key');
resultVersion := '';
if (CkXml_HasChildWithTag(item,'VersionId') = True) then
begin
resultVersion := CkXml__getChildContent(item,'VersionId');
end;
success := CkJsonObject_UpdateString(identity,'key',resultKey);
if (success <> True) then
begin
Memo1.Lines.Add('Could not build saved state.');
Exit;
end;
success := CkJsonObject_UpdateString(identity,'version',resultVersion);
if (success <> True) then
begin
Memo1.Lines.Add('Could not build saved state.');
Exit;
end;
responseIdentity := CkJsonObject__emit(identity);
if ((CkHashtable_Contains(requested,responseIdentity) <> True) or (CkHashtable_Contains(received,responseIdentity) = True)) then
begin
Memo1.Lines.Add('Unexpected or duplicated deletion result; reconcile manually.');
Exit;
end;
success := CkHashtable_AddInt(received,responseIdentity,1);
if (success <> True) then
begin
Memo1.Lines.Add('Could not prepare the request.');
Exit;
end;
Memo1.Lines.Add(itemTag + ': ' + resultKey);
if (resultType = 1) then
begin
Memo1.Lines.Add('Error code: ' + CkXml__getChildContent(item,'Code'));
end;
CkXml_Dispose(item);
j := j + 1;
end;
resultType := resultType + 1;
end;
if (failed > 0) then
begin
Memo1.Lines.Add('Batch has per-object failures. Do not retry successful entries.');
Exit;
end;
Memo1.Lines.Add('All requested deletions acknowledged.');
CkStringBuilder_Dispose(textCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkRest_Dispose(rest);
CkSocket_Dispose(connection);
CkXml_Dispose(xml);
CkJsonObject_Dispose(batch);
CkHashtable_Dispose(requested);
CkJsonObject_Dispose(identity);
CkStringBuilder_Dispose(host);
CkDateTime_Dispose(now);
CkStringBuilder_Dispose(timestamp);
CkCrypt2_Dispose(crypt);
CkStringBuilder_Dispose(signedHeaders);
CkStringBuilder_Dispose(canonical);
CkStringBuilder_Dispose(scope);
CkStringBuilder_Dispose(stringToSign);
CkStringBuilder_Dispose(initialKey);
CkStringBuilder_Dispose(authorization);
CkHashtable_Dispose(received);
CkStringBuilder_Dispose(itemPath);