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

Amazon S3: List Object Versions and Delete Markers

See more S3 - REST Examples

List versions and delete markers under a prefix. Version IDs, including the literal null version ID, remain strings. IsLatest indicates the current entry, which can be a delete marker. This listing does not modify data. Requires s3:ListBucketVersions.

Follow both pagination markers, including after an empty page. With encoding-type=url, decode keys and NextKeyMarker once, but never decode the opaque version/upload ID. Repeated marker pairs and the 1000-page bound report incomplete enumeration. Pages are not an atomic snapshot, and no deprecated DisplayName field is required.

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 ListObjectVersions 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 aws = chilkat.AuthAws.new()
aws.access_key = credentials:string_of("access_key")
aws.secret_key = credentials:string_of("secret_key")
aws.region = region
aws.service_name = "s3"
aws.signature_version = 4
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
success = rest:set_auth_aws(aws)
if not success then
    print("Could not configure AWS signing.")
    return
end

-- Temporary credentials require this token in every signed query.
-- Keep request URLs private. Do not clear this parameter between requests.
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

    textCompare:clear()
    textCompare:set_string(credentials:string_of("session_token"))
    local sameText3 = textCompare:contents_equal("", true)
    if not sameText3 then
        success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
        if not success then
            print("Could not prepare the request.")
            return
        end
    end
end

-- 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
success = rest:add_query_param("versions", "")
if not success then
    print("Could not prepare the request.")
    return
end

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

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

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

local seenPages = chilkat.Hashtable.new()
local markerPair = chilkat.JsonObject.new()
local more = true
local page = 0
while more do
    if page == 1000 then
        print("Page limit reached; enumeration is incomplete.")
        return
    end

    local responseBody = rest:full_request_no_body("GET", "/")
    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 sameText4 = textCompare:contents_equal("Error", true)
        if (success) and (sameText4) 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 sameText5 = textCompare:contents_equal("ListVersionsResult", true)
    if not sameText5 then
        print("Unexpected S3 response element; this is not a successful result.")
        return
    end

    local v = 0
    while v < xml:num_children_having_tag("Version") do
        xml.i = v
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("Version[i]|Key"))
        local sameText6 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("Version[i]|Key")) or (sameText6) then
            print("Missing response field: Version[i]|Key")
            return
        end

        local keyv = chilkat.StringBuilder.new()
        success = keyv:append(xml:get_child_content("Version[i]|Key"))
        if not success then
            print("Could not prepare the request.")
            return
        end

        local keyvPluses = keyv:replace("+", "%2B")
        success = keyv:decode("url", "utf-8")
        if not success then
            print("Could not decode a returned key.")
            return
        end

        print("Version key: " .. keyv:get_as_string())
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("Version[i]|VersionId"))
        local sameText7 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("Version[i]|VersionId")) or (sameText7) then
            print("Missing response field: Version[i]|VersionId")
            return
        end

        print("VersionId: " .. xml:get_child_content("Version[i]|VersionId"))
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("Version[i]|IsLatest"))
        local sameText8 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("Version[i]|IsLatest")) or (sameText8) then
            print("Missing response field: Version[i]|IsLatest")
            return
        end

        print("IsLatest: " .. xml:get_child_content("Version[i]|IsLatest"))
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("Version[i]|LastModified"))
        local sameText9 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("Version[i]|LastModified")) or (sameText9) then
            print("Missing response field: Version[i]|LastModified")
            return
        end

        print("LastModified: " .. xml:get_child_content("Version[i]|LastModified"))
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("Version[i]|Size"))
        local sameText10 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("Version[i]|Size")) or (sameText10) then
            print("Missing response field: Version[i]|Size")
            return
        end

        print("Size: " .. xml:get_child_content("Version[i]|Size"))
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("Version[i]|ETag"))
        local sameText11 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("Version[i]|ETag")) or (sameText11) then
            print("Missing response field: Version[i]|ETag")
            return
        end

        print("ETag: " .. xml:get_child_content("Version[i]|ETag"))
        v = v + 1
    end

    local d = 0
    while d < xml:num_children_having_tag("DeleteMarker") do
        xml.i = d
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("DeleteMarker[i]|Key"))
        local sameText12 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("DeleteMarker[i]|Key")) or (sameText12) then
            print("Missing response field: DeleteMarker[i]|Key")
            return
        end

        local keyd = chilkat.StringBuilder.new()
        success = keyd:append(xml:get_child_content("DeleteMarker[i]|Key"))
        if not success then
            print("Could not prepare the request.")
            return
        end

        local keydPluses = keyd:replace("+", "%2B")
        success = keyd:decode("url", "utf-8")
        if not success then
            print("Could not decode a returned key.")
            return
        end

        print("DeleteMarker key: " .. keyd:get_as_string())
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("DeleteMarker[i]|VersionId"))
        local sameText13 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("DeleteMarker[i]|VersionId")) or (sameText13) then
            print("Missing response field: DeleteMarker[i]|VersionId")
            return
        end

        print("VersionId: " .. xml:get_child_content("DeleteMarker[i]|VersionId"))
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("DeleteMarker[i]|IsLatest"))
        local sameText14 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("DeleteMarker[i]|IsLatest")) or (sameText14) then
            print("Missing response field: DeleteMarker[i]|IsLatest")
            return
        end

        print("IsLatest: " .. xml:get_child_content("DeleteMarker[i]|IsLatest"))
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("DeleteMarker[i]|LastModified"))
        local sameText15 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("DeleteMarker[i]|LastModified")) or (sameText15) then
            print("Missing response field: DeleteMarker[i]|LastModified")
            return
        end

        print("LastModified: " .. xml:get_child_content("DeleteMarker[i]|LastModified"))
        d = d + 1
    end

    textCompare:clear()
    textCompare:set_string(xml:get_child_content("IsTruncated"))
    local sameText16 = textCompare:contents_equal("", true)
    if (not xml:has_child_with_tag("IsTruncated")) or (sameText16) then
        print("Missing response field: IsTruncated")
        return
    end

    textCompare:clear()
    textCompare:set_string(xml:get_child_content("IsTruncated"))
    local sameText17 = textCompare:contents_equal("true", true)
    textCompare:clear()
    textCompare:set_string(xml:get_child_content("IsTruncated"))
    local sameText18 = textCompare:contents_equal("false", true)
    if (not sameText17) and (not sameText18) then
        print("Invalid IsTruncated value.")
        return
    end

    more = false
    textCompare:clear()
    textCompare:set_string(xml:get_child_content("IsTruncated"))
    local sameText19 = textCompare:contents_equal("true", true)
    if sameText19 then
        textCompare:clear()
        textCompare:set_string(xml:get_child_content("NextKeyMarker"))
        local sameText20 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("NextKeyMarker")) or (sameText20) then
            print("Missing response field: NextKeyMarker")
            return
        end

        textCompare:clear()
        textCompare:set_string(xml:get_child_content("NextVersionIdMarker"))
        local sameText21 = textCompare:contents_equal("", true)
        if (not xml:has_child_with_tag("NextVersionIdMarker")) or (sameText21) then
            print("Missing response field: NextVersionIdMarker")
            return
        end

        local nextKey = chilkat.StringBuilder.new()
        success = nextKey:append(xml:get_child_content("NextKeyMarker"))
        if not success then
            print("Could not prepare the request.")
            return
        end

        local nextKeyPluses = nextKey:replace("+", "%2B")
        success = nextKey:decode("url", "utf-8")
        if not success then
            print("Could not decode a returned key.")
            return
        end

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

        success = markerPair:update_string("id", xml:get_child_content("NextVersionIdMarker"))
        if not success then
            print("Could not build saved state.")
            return
        end

        local pair = markerPair:emit()
        if seenPages:contains(pair) then
            print("Repeated marker pair; enumeration is incomplete.")
            return
        end

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

        if page > 0 then
            success = rest:remove_query_param("key-marker")
            if not success then
                print("Could not prepare the request.")
                return
            end

            success = rest:remove_query_param("version-id-marker")
            if not success then
                print("Could not prepare the request.")
                return
            end
        end

        -- AddQueryParam encodes the decoded key and the opaque, unmodified ID once.
        success = rest:add_query_param("key-marker", nextKey:get_as_string())
        if not success then
            print("Could not prepare the request.")
            return
        end

        success = rest:add_query_param("version-id-marker", xml:get_child_content("NextVersionIdMarker"))
        if not success then
            print("Could not prepare the request.")
            return
        end

        more = true
    end

    page = page + 1
end

print("Enumeration complete.")