Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.6.0+

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.

AWS DeleteObjects reference

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- StringBuilder compares text by value in every generated language.
local textCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local success = false
-- Private configuration, not a file in public web content or source control.
-- Load current IAM credentials authorized for the S3 operation.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
success = credentials:load_file("qa_data/aws/s3.json")
if not success then
    print("Could not load private AWS credentials.")
    return
end

textCompare:clear()
textCompare:set_string(credentials:string_of("access_key"))
local sameText1 = textCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (sameText1) then
    print("Missing or invalid access_key.")
    return
end

textCompare:clear()
textCompare:set_string(credentials:string_of("secret_key"))
local sameText2 = textCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (sameText2) then
    print("Missing or invalid secret_key.")
    return
end

-- General purpose bucket in the commercial AWS partition.
local region = "us-west-2"
local bucketName = "amzn-s3-demo-bucket"
local endpoint = chilkat.StringBuilder.new()
success = endpoint:append(bucketName)
if not success then
    print("Could not build text.")
    return
end

success = endpoint:append(".")
if not success then
    print("Could not build text.")
    return
end

success = endpoint:append("s3.")
if not success then
    print("Could not build text.")
    return
end

success = endpoint:append(region)
if not success then
    print("Could not build text.")
    return
end

success = endpoint:append(".amazonaws.com")
if not success then
    print("Could not build text.")
    return
end

local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
-- Connect to the SAME hostname used for TLS verification and request signing.
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
    print("TLS connection failed; inspect diagnostics privately.")
    return
end

success = rest:use_connection(connection, true)
if not success then
    print("Could not attach the TLS connection.")
    return
end

local xml = chilkat.Xml.new()
xml.strict = true
rest.host = endpoint:get_as_string()
if credentials:has_member("session_token") then
    if credentials:json_type_of("session_token") ~= 1 then
        print("session_token must be a string.")
        return
    end
end

-- One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
local batch = chilkat.JsonObject.new()
batch.strict = true
success = batch:load_file("qa_data/aws/delete-objects.json")
if not success then
    print("Could not load the intended deletion batch.")
    return
end

local count = batch:size_of_array("objects")
if (count < 1) or (count > 1000) then
    print("Supply 1 to 1000 objects in the batch.")
    return
end

xml.tag = "Delete"
success = xml:add_attribute("xmlns", "http://s3.amazonaws.com/doc/2006-03-01/")
if not success then
    print("Could not prepare the request.")
    return
end

xml:update_child_content("Quiet", "false")
local requested = chilkat.Hashtable.new()
local identity = chilkat.JsonObject.new()
local i = 0
while i < count do
    batch.i = i
    xml.i = i
    textCompare:clear()
    textCompare:set_string(batch:string_of("objects[i].key"))
    local sameText3 = textCompare:contents_equal("", true)
    if (batch:json_type_of("objects[i].key") ~= 1) or (sameText3) then
        print("Each object needs a nonempty key.")
        return
    end

    local key = batch:string_of("objects[i].key")
    local version = ""
    if batch:has_member("objects[i].version_id") then
        textCompare:clear()
        textCompare:set_string(batch:string_of("objects[i].version_id"))
        local sameText4 = textCompare:contents_equal("", true)
        if (batch:json_type_of("objects[i].version_id") ~= 1) or (sameText4) then
            print("version_id must be a nonempty string when present.")
            return
        end

        version = batch:string_of("objects[i].version_id")
        xml:update_child_content("Object[i]|VersionId", version)
    end

    xml:update_child_content("Object[i]|Key", key)
    success = identity:update_string("key", key)
    if not success then
        print("Could not build saved state.")
        return
    end

    success = identity:update_string("version", version)
    if not success then
        print("Could not build saved state.")
        return
    end

    local requestIdentity = identity:emit()
    if requested:contains(requestIdentity) then
        print("Duplicate key/version in deletion batch.")
        return
    end

    success = requested:add_int(requestIdentity, 1)
    if not success then
        print("Could not prepare the request.")
        return
    end

    i = i + 1
end

local requestBody = xml:get_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.
local host = chilkat.StringBuilder.new()
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
    textCompare:clear()
    textCompare:set_string(credentials:string_of("session_token"))
    local sameText5 = textCompare:contents_equal("", true)
    if not sameText5 then
        signedHeaders:append(";x-amz-security-token")
        canonical:append("x-amz-security-token:")
        canonical:append(credentials:string_of("session_token"))
        canonical:append("\n")
        success = rest:add_header("x-amz-security-token", credentials:string_of("session_token"))
        if not success then
            print("Could not prepare the request.")
            return
        end
    end
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)
success = rest:add_header("Authorization", authorization:get_as_string())
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("Content-MD5", contentMd5)
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("x-amz-content-sha256", payloadHash)
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_header("x-amz-date", amzDate)
if not success then
    print("Could not prepare the request.")
    return
end

success = rest:add_query_param("delete", "")
if not success then
    print("Could not prepare the request.")
    return
end

local responseBody = rest:full_request_string("POST", "/", requestBody)
if not rest.last_method_success then
    print("Request did not complete; inspect diagnostics privately.")
    return
end

if rest.response_status_code ~= 200 then
    print("S3 HTTP status: " .. rest.response_status_code)
    success = xml:load_xml(responseBody)
    textCompare:clear()
    textCompare:set_string(xml.tag)
    local sameText6 = textCompare:contents_equal("Error", true)
    if (success) and (sameText6) then
        print("S3 error code: " .. xml:get_child_content("Code"))
    end

    -- Keep signed headers, credentials, URLs, and full diagnostics private.
    -- A timeout may leave a write's outcome uncertain. Check before retrying.
    return
end

success = xml:load_xml(responseBody)
if not success then
    print("Expected well-formed XML.")
    return
end

textCompare:clear()
textCompare:set_string(xml.tag)
local sameText7 = textCompare:contents_equal("DeleteResult", true)
if not sameText7 then
    print("Unexpected S3 response element; this is not a successful result.")
    return
end

local deleted = xml:num_children_having_tag("Deleted")
local failed = xml:num_children_having_tag("Error")
if deleted + failed ~= count then
    print("Incomplete result: reconcile every requested object before retrying.")
    return
end

local received = chilkat.Hashtable.new()
local resultType = 0
while resultType < 2 do
    local itemTag = "Deleted"
    local resultCount = deleted
    if resultType == 1 then
        itemTag = "Error"
        resultCount = failed
    end

    local j = 0
    while j < resultCount do
        xml.i = j
        local itemPath = chilkat.StringBuilder.new()
        success = itemPath:append(itemTag)
        if not success then
            print("Could not build text.")
            return
        end

        success = itemPath:append("[i]")
        if not success then
            print("Could not build text.")
            return
        end

        local item = xml:find_child(itemPath:get_as_string())
        if not xml.last_method_success then
            print("Missing deletion result entry.")
            return
        end

        local resultKey = item:get_child_content("Key")
        local resultVersion = ""
        if item:has_child_with_tag("VersionId") then
            resultVersion = item:get_child_content("VersionId")
        end

        success = identity:update_string("key", resultKey)
        if not success then
            print("Could not build saved state.")
            return
        end

        success = identity:update_string("version", resultVersion)
        if not success then
            print("Could not build saved state.")
            return
        end

        local responseIdentity = identity:emit()
        if (not requested:contains(responseIdentity)) or (received:contains(responseIdentity)) then
            print("Unexpected or duplicated deletion result; reconcile manually.")
            return
        end

        success = received:add_int(responseIdentity, 1)
        if not success then
            print("Could not prepare the request.")
            return
        end

        print(itemTag .. ": " .. resultKey)
        if resultType == 1 then
            print("Error code: " .. item:get_child_content("Code"))
        end

        j = j + 1
    end

    resultType = resultType + 1
end

if failed > 0 then
    print("Batch has per-object failures. Do not retry successful entries.")
    return
end

print("All requested deletions acknowledged.")