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 B4X Downloads
Dim success As Boolean = False
' StringBuilder compares text by value in every generated language.
Dim textCompare As ChilkatStringBuilder
textCompare.Initialize
' 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.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/s3.json")
If success <> True Then
Log("Could not load private AWS credentials.")
Return
End If
textCompare.Clear
textCompare.SetString(credentials.StringOf("access_key"))
Dim sameText1 As Boolean = textCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("access_key") <> 1) Or (sameText1 = True) Then
Log("Missing or invalid access_key.")
Return
End If
textCompare.Clear
textCompare.SetString(credentials.StringOf("secret_key"))
Dim sameText2 As Boolean = textCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("secret_key") <> 1) Or (sameText2 = True) Then
Log("Missing or invalid secret_key.")
Return
End If
' General purpose bucket in the commercial AWS partition.
Dim region As String = "us-west-2"
Dim bucketName As String = "amzn-s3-demo-bucket"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
success = endpoint.Append(bucketName)
If success <> True Then
Log("Could not build text.")
Return
End If
success = endpoint.Append(".")
If success <> True Then
Log("Could not build text.")
Return
End If
success = endpoint.Append("s3.")
If success <> True Then
Log("Could not build text.")
Return
End If
success = endpoint.Append(region)
If success <> True Then
Log("Could not build text.")
Return
End If
success = endpoint.Append(".amazonaws.com")
If success <> True Then
Log("Could not build text.")
Return
End If
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
' Connect to the SAME hostname used for TLS verification and request signing.
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
Log("TLS connection failed; inspect diagnostics privately.")
Return
End If
success = rest.UseConnection(connection, True)
If success <> True Then
Log("Could not attach the TLS connection.")
Return
End If
Dim xml As ChilkatXml
xml.Initialize
xml.Strict = True
rest.Host = endpoint.GetAsString
If credentials.HasMember("session_token") = True Then
If credentials.JsonTypeOf("session_token") <> 1 Then
Log("session_token must be a string.")
Return
End If
End If
' One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
Dim batch As ChilkatJsonObject
batch.Initialize
batch.Strict = True
success = batch.LoadFile("qa_data/aws/delete-objects.json")
If success <> True Then
Log("Could not load the intended deletion batch.")
Return
End If
Dim count As Int = batch.SizeOfArray("objects")
If (count < 1) Or (count > 1000) Then
Log("Supply 1 to 1000 objects in the batch.")
Return
End If
xml.Tag = "Delete"
success = xml.AddAttribute("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
xml.UpdateChildContent("Quiet", "false")
Dim requested As ChilkatHashtable
requested.Initialize
Dim identity As ChilkatJsonObject
identity.Initialize
Dim i As Int = 0
Do While (i < count)
batch.I = i
xml.I = i
textCompare.Clear
textCompare.SetString(batch.StringOf("objects[i].key"))
Dim sameText3 As Boolean = textCompare.ContentsEqual("", True)
If (batch.JsonTypeOf("objects[i].key") <> 1) Or (sameText3 = True) Then
Log("Each object needs a nonempty key.")
Return
End If
Dim key As String = batch.StringOf("objects[i].key")
Dim version As String = ""
If batch.HasMember("objects[i].version_id") = True Then
textCompare.Clear
textCompare.SetString(batch.StringOf("objects[i].version_id"))
Dim sameText4 As Boolean = textCompare.ContentsEqual("", True)
If (batch.JsonTypeOf("objects[i].version_id") <> 1) Or (sameText4 = True) Then
Log("version_id must be a nonempty string when present.")
Return
End If
version = batch.StringOf("objects[i].version_id")
xml.UpdateChildContent("Object[i]|VersionId", version)
End If
xml.UpdateChildContent("Object[i]|Key", key)
success = identity.UpdateString("key", key)
If success <> True Then
Log("Could not build saved state.")
Return
End If
success = identity.UpdateString("version", version)
If success <> True Then
Log("Could not build saved state.")
Return
End If
Dim requestIdentity As String = identity.Emit
If requested.Contains(requestIdentity) = True Then
Log("Duplicate key/version in deletion batch.")
Return
End If
success = requested.AddInt(requestIdentity, 1)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
i = i + 1
Loop
Dim requestBody As String = xml.GetXml
' 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.
Dim host As ChilkatStringBuilder
host.Initialize
host.Append(endpoint.GetAsString)
Dim now As ChilkatDateTime
now.Initialize
success = now.SetFromCurrentSystemTime
If success <> True Then
Log("Could not read system time.")
Return
End If
Dim timestamp As ChilkatStringBuilder
timestamp.Initialize
timestamp.Append(now.GetAsTimestamp(False))
Dim removedDashes As Int = timestamp.Replace("-", "")
Dim removedColons As Int = timestamp.Replace(":", "")
Dim amzDate As String = timestamp.GetAsString
Dim dateStamp As String = timestamp.GetRange(0, 8, False)
Dim crypt As ChilkatCrypt2
crypt.Initialize("crypt")
crypt.Charset = "utf-8"
crypt.HashAlgorithm = "md5"
crypt.EncodingMode = "base64"
Dim contentMd5 As String = crypt.HashStringENC(requestBody)
If crypt.LastMethodSuccess <> True Then
Log("Could not hash delete body.")
Return
End If
crypt.HashAlgorithm = "sha256"
crypt.EncodingMode = "hexlower"
Dim payloadHash As String = crypt.HashStringENC(requestBody)
If crypt.LastMethodSuccess <> True Then
Log("Could not hash delete body.")
Return
End If
Dim signedHeaders As ChilkatStringBuilder
signedHeaders.Initialize
signedHeaders.Append("content-md5;host;x-amz-content-sha256;x-amz-date")
Dim canonical As ChilkatStringBuilder
canonical.Initialize
canonical.Append("POST" & Chr(10) & "/" & Chr(10) & "delete=" & Chr(10) & "content-md5:")
canonical.Append(contentMd5)
canonical.Append(Chr(10) & "host:")
canonical.Append(host.GetAsString)
canonical.Append(Chr(10) & "x-amz-content-sha256:")
canonical.Append(payloadHash)
canonical.Append(Chr(10) & "x-amz-date:")
canonical.Append(amzDate)
canonical.Append(Chr(10))
If credentials.HasMember("session_token") = True Then
textCompare.Clear
textCompare.SetString(credentials.StringOf("session_token"))
Dim sameText5 As Boolean = textCompare.ContentsEqual("", True)
If sameText5 <> True Then
signedHeaders.Append(";x-amz-security-token")
canonical.Append("x-amz-security-token:")
canonical.Append(credentials.StringOf("session_token"))
canonical.Append(Chr(10))
success = rest.AddHeader("x-amz-security-token", credentials.StringOf("session_token"))
If success <> True Then
Log("Could not prepare the request.")
Return
End If
End If
End If
canonical.Append(Chr(10))
canonical.Append(signedHeaders.GetAsString)
canonical.Append(Chr(10))
canonical.Append(payloadHash)
Dim canonicalHash As String = crypt.HashStringENC(canonical.GetAsString)
If crypt.LastMethodSuccess <> True Then
Log("Could not hash canonical request.")
Return
End If
Dim scope As ChilkatStringBuilder
scope.Initialize
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
Dim stringToSign As ChilkatStringBuilder
stringToSign.Initialize
stringToSign.Append("AWS4-HMAC-SHA256" & Chr(10))
stringToSign.Append(amzDate)
stringToSign.Append(Chr(10))
stringToSign.Append(scope.GetAsString)
stringToSign.Append(Chr(10))
stringToSign.Append(canonicalHash)
Dim initialKey As ChilkatStringBuilder
initialKey.Initialize
initialKey.Append("AWS4")
initialKey.Append(credentials.StringOf("secret_key"))
crypt.MacAlgorithm = "hmac"
success = crypt.SetMacKeyString(initialKey.GetAsString)
If success <> True Then
Log("Could not set signing key.")
Return
End If
Dim derivedKey As String = crypt.MacStringENC(dateStamp)
If crypt.LastMethodSuccess <> True Then
Log("Could not derive date signing key.")
Return
End If
success = crypt.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set derived signing key.")
Return
End If
derivedKey = crypt.MacStringENC(region)
If crypt.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = crypt.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set derived signing key.")
Return
End If
derivedKey = crypt.MacStringENC("s3")
If crypt.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = crypt.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set derived signing key.")
Return
End If
derivedKey = crypt.MacStringENC("aws4_request")
If crypt.LastMethodSuccess <> True Then
Log("Could not derive signing key.")
Return
End If
success = crypt.SetMacKeyEncoded(derivedKey, "hex")
If success <> True Then
Log("Could not set final signing key.")
Return
End If
Dim signature As String = crypt.MacStringENC(stringToSign.GetAsString)
If crypt.LastMethodSuccess <> True Then
Log("Could not sign delete request.")
Return
End If
Dim authorization As ChilkatStringBuilder
authorization.Initialize
authorization.Append("AWS4-HMAC-SHA256 Credential=")
authorization.Append(credentials.StringOf("access_key"))
authorization.Append("/")
authorization.Append(scope.GetAsString)
authorization.Append(", SignedHeaders=")
authorization.Append(signedHeaders.GetAsString)
authorization.Append(", Signature=")
authorization.Append(signature)
success = rest.AddHeader("Authorization", authorization.GetAsString)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddHeader("Content-MD5", contentMd5)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddHeader("x-amz-content-sha256", payloadHash)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddHeader("x-amz-date", amzDate)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
success = rest.AddQueryParam("delete", "")
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Dim responseBody As String = rest.FullRequestString("POST", "/", requestBody)
If rest.LastMethodSuccess <> True Then
Log("Request did not complete; inspect diagnostics privately.")
Return
End If
If rest.ResponseStatusCode <> 200 Then
Log("S3 HTTP status: " & rest.ResponseStatusCode)
success = xml.LoadXml(responseBody)
textCompare.Clear
textCompare.SetString(xml.Tag)
Dim sameText6 As Boolean = textCompare.ContentsEqual("Error", True)
If (success = True) And (sameText6 = True) Then
Log("S3 error code: " & xml.GetChildContent("Code"))
End If
' Keep signed headers, credentials, URLs, and full diagnostics private.
' A timeout may leave a write's outcome uncertain. Check before retrying.
Return
End If
success = xml.LoadXml(responseBody)
If success <> True Then
Log("Expected well-formed XML.")
Return
End If
textCompare.Clear
textCompare.SetString(xml.Tag)
Dim sameText7 As Boolean = textCompare.ContentsEqual("DeleteResult", True)
If sameText7 <> True Then
Log("Unexpected S3 response element; this is not a successful result.")
Return
End If
Dim deleted As Int = xml.NumChildrenHavingTag("Deleted")
Dim failed As Int = xml.NumChildrenHavingTag("Error")
If deleted + failed <> count Then
Log("Incomplete result: reconcile every requested object before retrying.")
Return
End If
Dim received As ChilkatHashtable
received.Initialize
Dim resultType As Int = 0
Do While (resultType < 2)
Dim itemTag As String = "Deleted"
Dim resultCount As Int = deleted
If resultType = 1 Then
itemTag = "Error"
resultCount = failed
End If
Dim j As Int = 0
Do While (j < resultCount)
xml.I = j
Dim itemPath As ChilkatStringBuilder
itemPath.Initialize
success = itemPath.Append(itemTag)
If success <> True Then
Log("Could not build text.")
Return
End If
success = itemPath.Append("[i]")
If success <> True Then
Log("Could not build text.")
Return
End If
Dim item As ChilkatXml = xml.FindChild(itemPath.GetAsString)
If xml.LastMethodSuccess <> True Then
Log("Missing deletion result entry.")
Return
End If
Dim resultKey As String = item.GetChildContent("Key")
Dim resultVersion As String = ""
If item.HasChildWithTag("VersionId") = True Then
resultVersion = item.GetChildContent("VersionId")
End If
success = identity.UpdateString("key", resultKey)
If success <> True Then
Log("Could not build saved state.")
Return
End If
success = identity.UpdateString("version", resultVersion)
If success <> True Then
Log("Could not build saved state.")
Return
End If
Dim responseIdentity As String = identity.Emit
If (requested.Contains(responseIdentity) <> True) Or (received.Contains(responseIdentity) = True) Then
Log("Unexpected or duplicated deletion result; reconcile manually.")
Return
End If
success = received.AddInt(responseIdentity, 1)
If success <> True Then
Log("Could not prepare the request.")
Return
End If
Log(itemTag & ": " & resultKey)
If resultType = 1 Then
Log("Error code: " & item.GetChildContent("Code"))
End If
j = j + 1
Loop
resultType = resultType + 1
Loop
If failed > 0 Then
Log("Batch has per-object failures. Do not retry successful entries.")
Return
End If
Log("All requested deletions acknowledged.")