Sample code for 30+ languages & platforms
B4X 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 B4X Downloads

B4X
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 response As ChilkatHttpResponse
response.Initialize
Dim signer As ChilkatCrypt2
signer.Initialize("signer")
signer.Charset = "utf-8"
signer.HashAlgorithm = "sha256"
signer.EncodingMode = "hexlower"
signer.MacAlgorithm = "hmac"
Dim now As ChilkatDateTime
now.Initialize
Dim timestamp As ChilkatStringBuilder
timestamp.Initialize
Dim canonical As ChilkatStringBuilder
canonical.Initialize
Dim canonicalHeaders As ChilkatStringBuilder
canonicalHeaders.Initialize
Dim signedHeaders As ChilkatStringBuilder
signedHeaders.Initialize
Dim scope As ChilkatStringBuilder
scope.Initialize
Dim stringToSign As ChilkatStringBuilder
stringToSign.Initialize
Dim signingKey As ChilkatStringBuilder
signingKey.Initialize
Dim authorization As ChilkatStringBuilder
authorization.Initialize
Dim url As ChilkatStringBuilder
url.Initialize
Dim query As ChilkatStringBuilder
query.Initialize
Dim number As ChilkatStringBuilder
number.Initialize
Dim host As ChilkatStringBuilder
host.Initialize
Dim uri As ChilkatStringBuilder
uri.Initialize
Dim xml As ChilkatXml
xml.Initialize
Dim amzDate As String
Dim dateStamp As String
Dim payloadHash As String
Dim canonicalHash As String
Dim derivedKey As String
Dim signature As String
Dim replaceCount As Int
host.Append(bucketName)
host.Append(".")
host.Append(endpoint.GetAsString)
uri.Append("/")
Dim seen As ChilkatHashtable
seen.Initialize
Dim more As Boolean = True
Dim page As Int = 0
Dim marker As String = ""
Dim truncated As String
Dim item As String
Dim keyMarker As String = ""
Dim versionMarker As String = ""
Dim prefix As String = "examples/"
Dim cursor As ChilkatJsonObject
cursor.Initialize
Do While (more = True)
    If page = 10000 Then
        Log("Page bound reached; results are incomplete.")
        Return
    End If

    page = page + 1
    query.Clear
    If query.Length > 0 Then
        query.Append("&")
    End If

    query.Append("encoding-type=")
    query.Append(http.UrlEncode("url"))
    stringCompare.SetString(keyMarker)
    Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("", True)
    If stringMatch4 <> True Then
        If query.Length > 0 Then
            query.Append("&")
        End If

        query.Append("key-marker=")
        query.Append(http.UrlEncode(keyMarker))
    End If

    If query.Length > 0 Then
        query.Append("&")
    End If

    query.Append("max-keys=")
    query.Append(http.UrlEncode("1000"))
    If query.Length > 0 Then
        query.Append("&")
    End If

    query.Append("prefix=")
    query.Append(http.UrlEncode(prefix))
    stringCompare.SetString(versionMarker)
    Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("", True)
    If stringMatch5 <> True Then
        If query.Length > 0 Then
            query.Append("&")
        End If

        query.Append("version-id-marker=")
        query.Append(http.UrlEncode(versionMarker))
    End If

    If query.Length > 0 Then
        query.Append("&")
    End If

    query.Append("versions=")
    query.Append(http.UrlEncode(""))
    http.ClearHeaders
    success = now.SetFromCurrentSystemTime
    If success <> True Then
        Log("Could not read system time.")
        Return
    End If

    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.LastMethodSuccess <> True Then
        Log("Could not hash payload.")
        Return
    End If

    canonicalHeaders.Clear
    signedHeaders.Clear
    If signedHeaders.Length > 0 Then
        signedHeaders.Append(";")
    End If

    signedHeaders.Append("host")
    canonicalHeaders.Append("host:")
    canonicalHeaders.Append(host.GetAsString)
    canonicalHeaders.Append(Chr(10))
    http.SetRequestHeader("host", host.GetAsString)
    If signedHeaders.Length > 0 Then
        signedHeaders.Append(";")
    End If

    signedHeaders.Append("x-amz-content-sha256")
    canonicalHeaders.Append("x-amz-content-sha256:")
    canonicalHeaders.Append(payloadHash)
    canonicalHeaders.Append(Chr(10))
    http.SetRequestHeader("x-amz-content-sha256", payloadHash)
    If signedHeaders.Length > 0 Then
        signedHeaders.Append(";")
    End If

    signedHeaders.Append("x-amz-date")
    canonicalHeaders.Append("x-amz-date:")
    canonicalHeaders.Append(amzDate)
    canonicalHeaders.Append(Chr(10))
    http.SetRequestHeader("x-amz-date", amzDate)
    If credentials.HasMember("session_token") = True Then
        If signedHeaders.Length > 0 Then
            signedHeaders.Append(";")
        End If

        signedHeaders.Append("x-amz-security-token")
        canonicalHeaders.Append("x-amz-security-token:")
        canonicalHeaders.Append(credentials.StringOf("session_token"))
        canonicalHeaders.Append(Chr(10))
        http.SetRequestHeader("x-amz-security-token", credentials.StringOf("session_token"))
    End If

    canonical.Clear
    canonical.Append("GET" & Chr(10))
    canonical.Append(uri.GetAsString)
    canonical.Append(Chr(10))
    canonical.Append(query.GetAsString)
    canonical.Append(Chr(10))
    canonical.Append(canonicalHeaders.GetAsString)
    canonical.Append(Chr(10))
    canonical.Append(signedHeaders.GetAsString)
    canonical.Append(Chr(10))
    canonical.Append(payloadHash)
    canonicalHash = signer.HashStringENC(canonical.GetAsString)
    If signer.LastMethodSuccess <> True Then
        Log("Could not hash canonical request.")
        Return
    End If

    scope.Clear
    scope.Append(dateStamp)
    scope.Append("/")
    scope.Append(region)
    scope.Append("/s3/aws4_request")
    stringToSign.Clear
    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)
    signingKey.SetString("AWS4")
    signingKey.Append(credentials.StringOf("secret_key"))
    success = signer.SetMacKeyString(signingKey.GetAsString)
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    derivedKey = signer.MacStringENC(dateStamp)
    If signer.LastMethodSuccess <> True Then
        Log("Could not derive signing key.")
        Return
    End If

    success = signer.SetMacKeyEncoded(derivedKey, "hex")
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    derivedKey = signer.MacStringENC(region)
    If signer.LastMethodSuccess <> True Then
        Log("Could not derive signing key.")
        Return
    End If

    success = signer.SetMacKeyEncoded(derivedKey, "hex")
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    derivedKey = signer.MacStringENC("s3")
    If signer.LastMethodSuccess <> True Then
        Log("Could not derive signing key.")
        Return
    End If

    success = signer.SetMacKeyEncoded(derivedKey, "hex")
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    derivedKey = signer.MacStringENC("aws4_request")
    If signer.LastMethodSuccess <> True Then
        Log("Could not derive signing key.")
        Return
    End If

    success = signer.SetMacKeyEncoded(derivedKey, "hex")
    If success <> True Then
        Log("Could not set signing key.")
        Return
    End If

    signature = signer.MacStringENC(stringToSign.GetAsString)
    If signer.LastMethodSuccess <> True Then
        Log("Could not sign request.")
        Return
    End If

    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.Length > 0 Then
        url.Append("?")
        url.Append(query.GetAsString)
    End If

    success = http.HttpNoBody("GET", url.GetAsString, response)
    If (success <> True) Or (response.StatusCode <> 200) Then
        Log("Request failed or returned unexpected HTTP status: " & response.StatusCode)
        '  Preserve progress. Inspect full diagnostics privately; do not log secrets.
        Return
    End If

    success = xml.LoadXml(response.BodyStr)
    If success <> True Then
        Log("Invalid XML response.")
        Return
    End If

    stringCompare.SetString(xml.Tag)
    Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("ListVersionsResult", True)
    If stringMatch6 <> True Then
        Log("Unexpected XML result, possibly an embedded S3 error. Inspect privately.")
        Return
    End If

    stringCompare.SetString(xml.GetChildContent("EncodingType"))
    Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("url", True)
    If stringMatch7 <> True Then
        Log("Expected URL encoding.")
        Return
    End If

    Dim i As Int = 0
    Do While (i < xml.NumChildrenHavingTag("Version"))
        xml.I = i
        item = xml.GetChildContent("Version[i]|Key")
        stringCompare.SetString(item)
        Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("", True)
        If (xml.LastMethodSuccess <> True) Or (stringMatch8 = True) Then
            Log("Missing required Version[i]|Key.")
            Return
        End If

        Log("Version key: " & http.UrlDecode(item))
        item = xml.GetChildContent("Version[i]|VersionId")
        stringCompare.SetString(item)
        Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("", True)
        If (xml.LastMethodSuccess <> True) Or (stringMatch9 = True) Then
            Log("Missing required Version[i]|VersionId.")
            Return
        End If

        Log("Version ID: " & item)
        Log("Latest: " & xml.GetChildContent("Version[i]|IsLatest"))
        i = i + 1
    Loop
    Dim j As Int = 0
    Do While (j < xml.NumChildrenHavingTag("DeleteMarker"))
        xml.I = j
        item = xml.GetChildContent("DeleteMarker[i]|Key")
        stringCompare.SetString(item)
        Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("", True)
        If (xml.LastMethodSuccess <> True) Or (stringMatch10 = True) Then
            Log("Missing required DeleteMarker[i]|Key.")
            Return
        End If

        Log("DeleteMarker key: " & http.UrlDecode(item))
        item = xml.GetChildContent("DeleteMarker[i]|VersionId")
        stringCompare.SetString(item)
        Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("", True)
        If (xml.LastMethodSuccess <> True) Or (stringMatch11 = True) Then
            Log("Missing required DeleteMarker[i]|VersionId.")
            Return
        End If

        Log("Version ID: " & item)
        Log("Latest: " & xml.GetChildContent("DeleteMarker[i]|IsLatest"))
        j = j + 1
    Loop
    truncated = xml.GetChildContent("IsTruncated")
    stringCompare.SetString(truncated)
    Dim stringMatch12 As Boolean = stringCompare.ContentsEqual("", True)
    If (xml.LastMethodSuccess <> True) Or (stringMatch12 = True) Then
        Log("Missing required IsTruncated.")
        Return
    End If

    stringCompare.SetString(truncated)
    Dim stringMatch13 As Boolean = stringCompare.ContentsEqual("true", True)
    stringCompare.SetString(truncated)
    Dim stringMatch14 As Boolean = stringCompare.ContentsEqual("false", True)
    If (stringMatch13 <> True) And (stringMatch14 <> True) Then
        Log("Invalid IsTruncated.")
        Return
    End If

    more = False
    stringCompare.SetString(truncated)
    Dim stringMatch15 As Boolean = stringCompare.ContentsEqual("true", True)
    If stringMatch15 = True Then
        keyMarker = xml.GetChildContent("NextKeyMarker")
        stringCompare.SetString(keyMarker)
        Dim stringMatch16 As Boolean = stringCompare.ContentsEqual("", True)
        If (xml.LastMethodSuccess <> True) Or (stringMatch16 = True) Then
            Log("Missing required NextKeyMarker.")
            Return
        End If

        keyMarker = http.UrlDecode(keyMarker)
        versionMarker = ""
        If xml.HasChildWithTag("NextVersionIdMarker") = True Then
            versionMarker = xml.GetChildContent("NextVersionIdMarker")
        End If

        success = cursor.UpdateString("key", keyMarker)
        If success <> True Then
            Log("Could not save key.")
            Return
        End If

        success = cursor.UpdateString("version", versionMarker)
        If success <> True Then
            Log("Could not save version.")
            Return
        End If

        marker = cursor.Emit
        If seen.Contains(marker) = True Then
            Log("Repeated version cursor; listing is incomplete.")
            Return
        End If

        success = seen.AddStr(marker, "seen")
        If success <> True Then
            Log("Could not track version cursor.")
            Return
        End If

        more = True
    End If

Loop
Log("Version and delete-marker listing complete.")