S3: Delete Multiple Objects and Check Per-Object Errors
See more S3 - HTTP Examples
Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.
Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.
Sends an explicit DeleteObjects request with Http.HttpStr and receives the original HttpResponse. XML APIs safely serialize up to 1,000 object identifiers. The request uses quiet mode; successful entries may be absent. HTTP 200 can still contain per-object errors, so every Error element is inspected before reporting success.
The sample uses Crypt2 to sign this fixed POST /?delete= request with SigV4, including Content-MD5, the SHA-256 payload hash, date, and optional session token. Keep the system clock accurate. Do not alter signed components after signing. This signing block is specific to this operation, not a general URL canonicalizer. See AWS header-signing rules.
Requires s3:DeleteObject, and s3:DeleteObjectVersion for explicit versions. Version-specific deletion is permanent. Without a version ID, a versioning-enabled bucket normally gains delete markers instead. Missing keys count as successful deletes. MFA Delete, retention, and legal holds may affect results. Retry only failed identifiers when appropriate, rather than repeating successful versioned deletes.
Chilkat B4X Downloads
Dim success As Boolean = False
Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
' This example requires the Chilkat API to have been previously unlocked.
' See Global Unlock Sample for sample code.
' Load private credentials; never put access keys or session tokens in source.
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 S3 credentials.")
Return
End If
stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = True) Then
Log("Missing or invalid access_key.")
Return
End If
stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = True) Then
Log("Missing or invalid secret_key.")
Return
End If
Dim http As ChilkatHttp
http.Initialize("http")
http.AwsAccessKey = credentials.StringOf("access_key")
http.AwsSecretKey = credentials.StringOf("secret_key")
If credentials.HasMember("session_token") = True Then
stringCompare.SetString(credentials.StringOf("session_token"))
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = True) Then
Log("session_token must be a nonempty string when supplied.")
Return
End If
http.AwsSessionToken = credentials.StringOf("session_token")
End If
' Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
' Set the actual bucket region, not the caller's location.
Dim region As String = "us-west-2"
http.AwsRegion = region
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("s3.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
http.AwsEndpoint = endpoint.GetAsString
http.RequireSslCertVerify = True
http.FollowRedirects = False
' A region redirect is not success. Correct the endpoint and signing region.
Dim bucketName As String = "your-bucket-name"
Dim deleteRequest As ChilkatXml
deleteRequest.Initialize
deleteRequest.Tag = "Delete"
deleteRequest.AddAttribute("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")
deleteRequest.UpdateChildContent("Quiet", "true")
' XML APIs escape key text. Do NOT URL-encode keys in this XML body.
deleteRequest.UpdateChildContent("Object[0]|Key", "images/seahorse.jpg")
deleteRequest.UpdateChildContent("Object[1]|Key", "images/starfish.jpg")
' For permanent deletion of a specific version, add Object[i]|VersionId
' deliberately. Use separate XML elements, not an embedded string convention.
If (deleteRequest.NumChildrenHavingTag("Object") < 1) Or (deleteRequest.NumChildrenHavingTag("Object") > 1000) Then
Log("Use a batch of 1 to 1,000 object identifiers.")
Return
End If
Dim requestBody As String = deleteRequest.GetXml
' 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(bucketName)
host.Append(".")
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
signedHeaders.Append(";x-amz-security-token")
canonical.Append("x-amz-security-token:")
canonical.Append(credentials.StringOf("session_token"))
canonical.Append(Chr(10))
http.SetRequestHeader("x-amz-security-token", credentials.StringOf("session_token"))
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)
http.SetRequestHeader("Authorization", authorization.GetAsString)
http.SetRequestHeader("Content-MD5", contentMd5)
http.SetRequestHeader("x-amz-content-sha256", payloadHash)
http.SetRequestHeader("x-amz-date", amzDate)
Dim requestUrl As ChilkatStringBuilder
requestUrl.Initialize
requestUrl.Append("https://")
requestUrl.Append(host.GetAsString)
requestUrl.Append("/?delete=")
Dim response As ChilkatHttpResponse
response.Initialize
success = http.HttpStr("POST", requestUrl.GetAsString, requestBody, "utf-8", "application/xml", response)
If success <> True Then
Log("Request failed (transport or S3 error). HTTP status: " & http.LastStatus)
' Inspect LastErrorText privately. Do not log credentials or signed URLs.
Return
End If
If response.StatusCode <> 200 Then
Log("Unexpected HTTP status: " & response.StatusCode)
Return
End If
' HTTP 200 can contain per-object errors. Inspect the actual XML body.
Dim xml As ChilkatXml
xml.Initialize
success = xml.LoadXml(response.BodyStr)
If success <> True Then
Log("Invalid XML response.")
Return
End If
stringCompare.SetString(xml.Tag)
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("DeleteResult", True)
If stringMatch4 <> True Then
Log("Unexpected XML response root.")
Return
End If
Dim failures As Int = xml.NumChildrenHavingTag("Error")
Dim i As Int = 0
Do While (i < failures)
xml.I = i
Log("Failed key: " & xml.GetChildContent("Error[i]|Key"))
Log("Error code: " & xml.GetChildContent("Error[i]|Code"))
i = i + 1
Loop
If failures <> 0 Then
Log("One or more objects were not deleted. Retry only appropriate failed identifiers.")
Return
End If
' Quiet=true means success entries need not be returned.
Log("Delete batch succeeded with no reported object errors.")