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 Lua Downloads
local chilkat = require("chilkat")
local stringCompare = chilkat.StringBuilder.new()
-- 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.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/s3.json")
if not success then
print("Could not load private S3 credentials.")
return
end
stringCompare:set_string(credentials:string_of("access_key"))
local stringMatch1 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (stringMatch1) then
print("Missing or invalid access_key.")
return
end
stringCompare:set_string(credentials:string_of("secret_key"))
local stringMatch2 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (stringMatch2) then
print("Missing or invalid secret_key.")
return
end
local http = chilkat.Http.new()
http.aws_access_key = credentials:string_of("access_key")
http.aws_secret_key = credentials:string_of("secret_key")
if credentials:has_member("session_token") then
stringCompare:set_string(credentials:string_of("session_token"))
local stringMatch3 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("session_token") ~= 1) or (stringMatch3) then
print("session_token must be a nonempty string when supplied.")
return
end
http.aws_session_token = credentials:string_of("session_token")
end
-- Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
-- Set the actual bucket region, not the caller's location.
local region = "us-west-2"
http.aws_region = region
local endpoint = chilkat.StringBuilder.new()
endpoint:append("s3.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
http.aws_endpoint = endpoint:get_as_string()
http.require_ssl_cert_verify = true
http.follow_redirects = false
-- A region redirect is not success. Correct the endpoint and signing region.
local bucketName = "your-bucket-name"
local deleteRequest = chilkat.Xml.new()
deleteRequest.tag = "Delete"
deleteRequest:add_attribute("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")
deleteRequest:update_child_content("Quiet", "true")
-- XML APIs escape key text. Do NOT URL-encode keys in this XML body.
deleteRequest:update_child_content("Object[0]|Key", "images/seahorse.jpg")
deleteRequest:update_child_content("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:num_children_having_tag("Object") < 1) or (deleteRequest:num_children_having_tag("Object") > 1000) then
print("Use a batch of 1 to 1,000 object identifiers.")
return
end
local requestBody = deleteRequest:get_xml()
-- Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
-- Do not change signed headers, body, endpoint, or query after signing.
local host = chilkat.StringBuilder.new()
host:append(bucketName)
host:append(".")
host:append(endpoint:get_as_string())
local now = chilkat.DateTime.new()
success = now:set_from_current_system_time()
if not success then
print("Could not read system time.")
return
end
local timestamp = chilkat.StringBuilder.new()
timestamp:append(now:get_as_timestamp(false))
local removedDashes = timestamp:replace("-", "")
local removedColons = timestamp:replace(":", "")
local amzDate = timestamp:get_as_string()
local dateStamp = timestamp:get_range(0, 8, false)
local crypt = chilkat.Crypt2.new()
crypt.charset = "utf-8"
crypt.hash_algorithm = "md5"
crypt.encoding_mode = "base64"
local contentMd5 = crypt:hash_string_enc(requestBody)
if not crypt.last_method_success then
print("Could not hash delete body.")
return
end
crypt.hash_algorithm = "sha256"
crypt.encoding_mode = "hexlower"
local payloadHash = crypt:hash_string_enc(requestBody)
if not crypt.last_method_success then
print("Could not hash delete body.")
return
end
local signedHeaders = chilkat.StringBuilder.new()
signedHeaders:append("content-md5;host;x-amz-content-sha256;x-amz-date")
local canonical = chilkat.StringBuilder.new()
canonical:append("POST\n/\ndelete=\ncontent-md5:")
canonical:append(contentMd5)
canonical:append("\nhost:")
canonical:append(host:get_as_string())
canonical:append("\nx-amz-content-sha256:")
canonical:append(payloadHash)
canonical:append("\nx-amz-date:")
canonical:append(amzDate)
canonical:append("\n")
if credentials:has_member("session_token") then
signedHeaders:append(";x-amz-security-token")
canonical:append("x-amz-security-token:")
canonical:append(credentials:string_of("session_token"))
canonical:append("\n")
http:set_request_header("x-amz-security-token", credentials:string_of("session_token"))
end
canonical:append("\n")
canonical:append(signedHeaders:get_as_string())
canonical:append("\n")
canonical:append(payloadHash)
local canonicalHash = crypt:hash_string_enc(canonical:get_as_string())
if not crypt.last_method_success then
print("Could not hash canonical request.")
return
end
local scope = chilkat.StringBuilder.new()
scope:append(dateStamp)
scope:append("/")
scope:append(region)
scope:append("/s3/aws4_request")
local stringToSign = chilkat.StringBuilder.new()
stringToSign:append("AWS4-HMAC-SHA256\n")
stringToSign:append(amzDate)
stringToSign:append("\n")
stringToSign:append(scope:get_as_string())
stringToSign:append("\n")
stringToSign:append(canonicalHash)
local initialKey = chilkat.StringBuilder.new()
initialKey:append("AWS4")
initialKey:append(credentials:string_of("secret_key"))
crypt.mac_algorithm = "hmac"
success = crypt:set_mac_key_string(initialKey:get_as_string())
if not success then
print("Could not set signing key.")
return
end
local derivedKey = crypt:mac_string_enc(dateStamp)
if not crypt.last_method_success then
print("Could not derive date signing key.")
return
end
success = crypt:set_mac_key_encoded(derivedKey, "hex")
if not success then
print("Could not set derived signing key.")
return
end
derivedKey = crypt:mac_string_enc(region)
if not crypt.last_method_success then
print("Could not derive signing key.")
return
end
success = crypt:set_mac_key_encoded(derivedKey, "hex")
if not success then
print("Could not set derived signing key.")
return
end
derivedKey = crypt:mac_string_enc("s3")
if not crypt.last_method_success then
print("Could not derive signing key.")
return
end
success = crypt:set_mac_key_encoded(derivedKey, "hex")
if not success then
print("Could not set derived signing key.")
return
end
derivedKey = crypt:mac_string_enc("aws4_request")
if not crypt.last_method_success then
print("Could not derive signing key.")
return
end
success = crypt:set_mac_key_encoded(derivedKey, "hex")
if not success then
print("Could not set final signing key.")
return
end
local signature = crypt:mac_string_enc(stringToSign:get_as_string())
if not crypt.last_method_success then
print("Could not sign delete request.")
return
end
local authorization = chilkat.StringBuilder.new()
authorization:append("AWS4-HMAC-SHA256 Credential=")
authorization:append(credentials:string_of("access_key"))
authorization:append("/")
authorization:append(scope:get_as_string())
authorization:append(", SignedHeaders=")
authorization:append(signedHeaders:get_as_string())
authorization:append(", Signature=")
authorization:append(signature)
http:set_request_header("Authorization", authorization:get_as_string())
http:set_request_header("Content-MD5", contentMd5)
http:set_request_header("x-amz-content-sha256", payloadHash)
http:set_request_header("x-amz-date", amzDate)
local requestUrl = chilkat.StringBuilder.new()
requestUrl:append("https://")
requestUrl:append(host:get_as_string())
requestUrl:append("/?delete=")
local response = chilkat.HttpResponse.new()
success = http:http_str("POST", requestUrl:get_as_string(), requestBody, "utf-8", "application/xml", response)
if not success then
print("Request failed (transport or S3 error). HTTP status: " .. http.last_status)
-- Inspect LastErrorText privately. Do not log credentials or signed URLs.
return
end
if response.status_code ~= 200 then
print("Unexpected HTTP status: " .. response.status_code)
return
end
-- HTTP 200 can contain per-object errors. Inspect the actual XML body.
local xml = chilkat.Xml.new()
success = xml:load_xml(response.body_str)
if not success then
print("Invalid XML response.")
return
end
stringCompare:set_string(xml.tag)
local stringMatch4 = stringCompare:contents_equal("DeleteResult", true)
if not stringMatch4 then
print("Unexpected XML response root.")
return
end
local failures = xml:num_children_having_tag("Error")
local i = 0
while i < failures do
xml.i = i
print("Failed key: " .. xml:get_child_content("Error[i]|Key"))
print("Error code: " .. xml:get_child_content("Error[i]|Code"))
i = i + 1
end
if failures ~= 0 then
print("One or more objects were not deleted. Retry only appropriate failed identifiers.")
return
end
-- Quiet=true means success entries need not be returned.
print("Delete batch succeeded with no reported object errors.")