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