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

S3 Http: List Object Versions and Delete Markers

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.

Uses explicit signed Http requests to preserve query parameters, conditional headers, and full responses. The included SigV4 block signs the exact path, sorted encoded query and headers used by this example; it is not a general-purpose HTTP signing library. Keep the clock accurate and do not change signed data after signing. Code requires Chilkat 11.6.0 or later; locally tested with 11.8.0.

Lists both Version and DeleteMarker entries, with prefix filtering, URL-decoded keys, and pagination using the pair NextKeyMarker/NextVersionIdMarker. A missing optional version marker is omitted; opaque version IDs, including literal null, are not decoded as object keys. Tracks complete cursor pairs and bounds pagination.

Requires s3:ListBucketVersions. Listing is read-only and not a single snapshot. Objects and delete markers are distinct; deleting a current marker may expose an older version.

AWS reference

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.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.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/s3.json")
if (success != true)
    print "Could not load private S3 credentials." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == true))
    print "Missing or invalid access_key." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == true))
    print "Missing or invalid secret_key." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_AwsAccessKey(credentials.stringOf("access_key"))
http.put_AwsSecretKey(credentials.stringOf("secret_key"))
if (credentials.HasMember("session_token") == true)
    stringCompare.SetString(credentials.stringOf("session_token"))
    stringMatch3 = stringCompare.ContentsEqual("",true)
    if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == true))
        print "session_token must be a nonempty string when supplied." + "\n";
        exit
    end

    http.put_AwsSessionToken(credentials.stringOf("session_token"))
end

#  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
#  Set the actual bucket region, not the caller's location.
region = "us-west-2"
http.put_AwsRegion(region)
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("s3.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
http.put_AwsEndpoint(endpoint.getAsString())
http.put_RequireSslCertVerify(true)
http.put_FollowRedirects(false)
#  A region redirect is not success. Correct the endpoint and signing region.
bucketName = "your-bucket-name"
response = Chilkat::CkHttpResponse.new()
signer = Chilkat::CkCrypt2.new()
signer.put_Charset("utf-8")
signer.put_HashAlgorithm("sha256")
signer.put_EncodingMode("hexlower")
signer.put_MacAlgorithm("hmac")
now = Chilkat::CkDateTime.new()
timestamp = Chilkat::CkStringBuilder.new()
canonical = Chilkat::CkStringBuilder.new()
canonicalHeaders = Chilkat::CkStringBuilder.new()
signedHeaders = Chilkat::CkStringBuilder.new()
scope = Chilkat::CkStringBuilder.new()
stringToSign = Chilkat::CkStringBuilder.new()
signingKey = Chilkat::CkStringBuilder.new()
authorization = Chilkat::CkStringBuilder.new()
url = Chilkat::CkStringBuilder.new()
query = Chilkat::CkStringBuilder.new()
number = Chilkat::CkStringBuilder.new()
host = Chilkat::CkStringBuilder.new()
uri = Chilkat::CkStringBuilder.new()
xml = Chilkat::CkXml.new()

host.Append(bucketName)
host.Append(".")
host.Append(endpoint.getAsString())
uri.Append("/")
seen = Chilkat::CkHashtable.new()
more = true
page = 0
marker = ""

keyMarker = ""
versionMarker = ""
prefix = "examples/"
cursor = Chilkat::CkJsonObject.new()
while (more == true)
    if (page == 10000)
        print "Page bound reached; results are incomplete." + "\n";
        exit
    end

    page = page + 1
    query.Clear()
    if (query.get_Length() > 0)
        query.Append("&")
    end

    query.Append("encoding-type=")
    query.Append(http.urlEncode("url"))
    stringCompare.SetString(keyMarker)
    stringMatch4 = stringCompare.ContentsEqual("",true)
    if (stringMatch4 != true)
        if (query.get_Length() > 0)
            query.Append("&")
        end

        query.Append("key-marker=")
        query.Append(http.urlEncode(keyMarker))
    end

    if (query.get_Length() > 0)
        query.Append("&")
    end

    query.Append("max-keys=")
    query.Append(http.urlEncode("1000"))
    if (query.get_Length() > 0)
        query.Append("&")
    end

    query.Append("prefix=")
    query.Append(http.urlEncode(prefix))
    stringCompare.SetString(versionMarker)
    stringMatch5 = stringCompare.ContentsEqual("",true)
    if (stringMatch5 != true)
        if (query.get_Length() > 0)
            query.Append("&")
        end

        query.Append("version-id-marker=")
        query.Append(http.urlEncode(versionMarker))
    end

    if (query.get_Length() > 0)
        query.Append("&")
    end

    query.Append("versions=")
    query.Append(http.urlEncode(""))
    http.ClearHeaders()
    success = now.SetFromCurrentSystemTime()
    if (success != true)
        print "Could not read system time." + "\n";
        exit
    end

    timestamp.SetString(now.getAsTimestamp(false))
    replaceCount = timestamp.Replace("-","")
    replaceCount = timestamp.Replace(":","")
    amzDate = timestamp.getAsString()
    dateStamp = timestamp.getRange(0,8,false)
    payloadHash = signer.hashStringENC("")
    if (signer.get_LastMethodSuccess() != true)
        print "Could not hash payload." + "\n";
        exit
    end

    canonicalHeaders.Clear()
    signedHeaders.Clear()
    if (signedHeaders.get_Length() > 0)
        signedHeaders.Append(";")
    end

    signedHeaders.Append("host")
    canonicalHeaders.Append("host:")
    canonicalHeaders.Append(host.getAsString())
    canonicalHeaders.Append("\n")
    http.SetRequestHeader("host",host.getAsString())
    if (signedHeaders.get_Length() > 0)
        signedHeaders.Append(";")
    end

    signedHeaders.Append("x-amz-content-sha256")
    canonicalHeaders.Append("x-amz-content-sha256:")
    canonicalHeaders.Append(payloadHash)
    canonicalHeaders.Append("\n")
    http.SetRequestHeader("x-amz-content-sha256",payloadHash)
    if (signedHeaders.get_Length() > 0)
        signedHeaders.Append(";")
    end

    signedHeaders.Append("x-amz-date")
    canonicalHeaders.Append("x-amz-date:")
    canonicalHeaders.Append(amzDate)
    canonicalHeaders.Append("\n")
    http.SetRequestHeader("x-amz-date",amzDate)
    if (credentials.HasMember("session_token") == true)
        if (signedHeaders.get_Length() > 0)
            signedHeaders.Append(";")
        end

        signedHeaders.Append("x-amz-security-token")
        canonicalHeaders.Append("x-amz-security-token:")
        canonicalHeaders.Append(credentials.stringOf("session_token"))
        canonicalHeaders.Append("\n")
        http.SetRequestHeader("x-amz-security-token",credentials.stringOf("session_token"))
    end

    canonical.Clear()
    canonical.Append("GET\n")
    canonical.Append(uri.getAsString())
    canonical.Append("\n")
    canonical.Append(query.getAsString())
    canonical.Append("\n")
    canonical.Append(canonicalHeaders.getAsString())
    canonical.Append("\n")
    canonical.Append(signedHeaders.getAsString())
    canonical.Append("\n")
    canonical.Append(payloadHash)
    canonicalHash = signer.hashStringENC(canonical.getAsString())
    if (signer.get_LastMethodSuccess() != true)
        print "Could not hash canonical request." + "\n";
        exit
    end

    scope.Clear()
    scope.Append(dateStamp)
    scope.Append("/")
    scope.Append(region)
    scope.Append("/s3/aws4_request")
    stringToSign.Clear()
    stringToSign.Append("AWS4-HMAC-SHA256\n")
    stringToSign.Append(amzDate)
    stringToSign.Append("\n")
    stringToSign.Append(scope.getAsString())
    stringToSign.Append("\n")
    stringToSign.Append(canonicalHash)
    signingKey.SetString("AWS4")
    signingKey.Append(credentials.stringOf("secret_key"))
    success = signer.SetMacKeyString(signingKey.getAsString())
    if (success != true)
        print "Could not set signing key." + "\n";
        exit
    end

    derivedKey = signer.macStringENC(dateStamp)
    if (signer.get_LastMethodSuccess() != true)
        print "Could not derive signing key." + "\n";
        exit
    end

    success = signer.SetMacKeyEncoded(derivedKey,"hex")
    if (success != true)
        print "Could not set signing key." + "\n";
        exit
    end

    derivedKey = signer.macStringENC(region)
    if (signer.get_LastMethodSuccess() != true)
        print "Could not derive signing key." + "\n";
        exit
    end

    success = signer.SetMacKeyEncoded(derivedKey,"hex")
    if (success != true)
        print "Could not set signing key." + "\n";
        exit
    end

    derivedKey = signer.macStringENC("s3")
    if (signer.get_LastMethodSuccess() != true)
        print "Could not derive signing key." + "\n";
        exit
    end

    success = signer.SetMacKeyEncoded(derivedKey,"hex")
    if (success != true)
        print "Could not set signing key." + "\n";
        exit
    end

    derivedKey = signer.macStringENC("aws4_request")
    if (signer.get_LastMethodSuccess() != true)
        print "Could not derive signing key." + "\n";
        exit
    end

    success = signer.SetMacKeyEncoded(derivedKey,"hex")
    if (success != true)
        print "Could not set signing key." + "\n";
        exit
    end

    signature = signer.macStringENC(stringToSign.getAsString())
    if (signer.get_LastMethodSuccess() != true)
        print "Could not sign request." + "\n";
        exit
    end

    authorization.Clear()
    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())
    url.SetString("https://")
    url.Append(host.getAsString())
    url.Append(uri.getAsString())
    if (query.get_Length() > 0)
        url.Append("?")
        url.Append(query.getAsString())
    end

    success = http.HttpNoBody("GET",url.getAsString(),response)
    if ((success != true) or (response.get_StatusCode() != 200))
        print "Request failed or returned unexpected HTTP status: " + response.get_StatusCode().to_s() + "\n";
        #  Preserve progress. Inspect full diagnostics privately; do not log secrets.
        exit
    end

    success = xml.LoadXml(response.bodyStr())
    if (success != true)
        print "Invalid XML response." + "\n";
        exit
    end

    stringCompare.SetString(xml.tag())
    stringMatch6 = stringCompare.ContentsEqual("ListVersionsResult",true)
    if (stringMatch6 != true)
        print "Unexpected XML result, possibly an embedded S3 error. Inspect privately." + "\n";
        exit
    end

    stringCompare.SetString(xml.getChildContent("EncodingType"))
    stringMatch7 = stringCompare.ContentsEqual("url",true)
    if (stringMatch7 != true)
        print "Expected URL encoding." + "\n";
        exit
    end

    i = 0
    while (i < xml.NumChildrenHavingTag("Version"))
        xml.put_I(i)
        item = xml.getChildContent("Version[i]|Key")
        stringCompare.SetString(item)
        stringMatch8 = stringCompare.ContentsEqual("",true)
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch8 == true))
            print "Missing required Version[i]|Key." + "\n";
            exit
        end

        print "Version key: " + http.urlDecode(item) + "\n";
        item = xml.getChildContent("Version[i]|VersionId")
        stringCompare.SetString(item)
        stringMatch9 = stringCompare.ContentsEqual("",true)
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch9 == true))
            print "Missing required Version[i]|VersionId." + "\n";
            exit
        end

        print "Version ID: " + item + "\n";
        print "Latest: " + xml.getChildContent("Version[i]|IsLatest") + "\n";
        i = i + 1
    end
    j = 0
    while (j < xml.NumChildrenHavingTag("DeleteMarker"))
        xml.put_I(j)
        item = xml.getChildContent("DeleteMarker[i]|Key")
        stringCompare.SetString(item)
        stringMatch10 = stringCompare.ContentsEqual("",true)
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch10 == true))
            print "Missing required DeleteMarker[i]|Key." + "\n";
            exit
        end

        print "DeleteMarker key: " + http.urlDecode(item) + "\n";
        item = xml.getChildContent("DeleteMarker[i]|VersionId")
        stringCompare.SetString(item)
        stringMatch11 = stringCompare.ContentsEqual("",true)
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch11 == true))
            print "Missing required DeleteMarker[i]|VersionId." + "\n";
            exit
        end

        print "Version ID: " + item + "\n";
        print "Latest: " + xml.getChildContent("DeleteMarker[i]|IsLatest") + "\n";
        j = j + 1
    end
    truncated = xml.getChildContent("IsTruncated")
    stringCompare.SetString(truncated)
    stringMatch12 = stringCompare.ContentsEqual("",true)
    if ((xml.get_LastMethodSuccess() != true) or (stringMatch12 == true))
        print "Missing required IsTruncated." + "\n";
        exit
    end

    stringCompare.SetString(truncated)
    stringMatch13 = stringCompare.ContentsEqual("true",true)
    stringCompare.SetString(truncated)
    stringMatch14 = stringCompare.ContentsEqual("false",true)
    if ((stringMatch13 != true) and (stringMatch14 != true))
        print "Invalid IsTruncated." + "\n";
        exit
    end

    more = false
    stringCompare.SetString(truncated)
    stringMatch15 = stringCompare.ContentsEqual("true",true)
    if (stringMatch15 == true)
        keyMarker = xml.getChildContent("NextKeyMarker")
        stringCompare.SetString(keyMarker)
        stringMatch16 = stringCompare.ContentsEqual("",true)
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch16 == true))
            print "Missing required NextKeyMarker." + "\n";
            exit
        end

        keyMarker = http.urlDecode(keyMarker)
        versionMarker = ""
        if (xml.HasChildWithTag("NextVersionIdMarker") == true)
            versionMarker = xml.getChildContent("NextVersionIdMarker")
        end

        success = cursor.UpdateString("key",keyMarker)
        if (success != true)
            print "Could not save key." + "\n";
            exit
        end

        success = cursor.UpdateString("version",versionMarker)
        if (success != true)
            print "Could not save version." + "\n";
            exit
        end

        marker = cursor.emit()
        if (seen.Contains(marker) == true)
            print "Repeated version cursor; listing is incomplete." + "\n";
            exit
        end

        success = seen.AddStr(marker,"seen")
        if (success != true)
            print "Could not track version cursor." + "\n";
            exit
        end

        more = true
    end

end
print "Version and delete-marker listing complete." + "\n";