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

S3: List Objects Under a Prefix

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 S3_ListBucketObjects with list-type=2 to request ListObjectsV2. Follows opaque NextContinuationToken values while IsTruncated is true, including empty pages; detects missing/repeated tokens and stops at 10,000 pages with incomplete-results status. Requires s3:ListBucket.

Requests encoding-type=url so keys containing XML-incompatible characters can be represented. Decode returned keys exactly once before reusing them. Query values are encoded separately. Sizes remain decimal strings to preserve large values; LastModified is an ISO 8601 UTC timestamp, not RFC 822. Owner.DisplayName is not used. Listing pages are not a single snapshot if objects change during enumeration.

A prefix is a key-name filter, not a filesystem folder. The trailing slash matters: images/ excludes keys such as images-old/file.jpg. Without a delimiter, all matching descendant keys are included.

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"
bucketPath = Chilkat::CkStringBuilder.new()
encoded = Chilkat::CkStringBuilder.new()
xml = Chilkat::CkXml.new()
seenTokens = Chilkat::CkHashtable.new()
token = ""
more = true
page = 0
prefix = "images/"
while (more == true)
    if (page == 10000)
        print "Page limit reached; listing is incomplete." + "\n";
        exit
    end

    page = page + 1
    bucketPath.SetString(bucketName)
    bucketPath.Append("?list-type=2&max-keys=1000&encoding-type=url")
    encoded.SetString(prefix)
    bucketPath.Append("&prefix=")
    bucketPath.Append(encoded.getEncoded("url","utf-8"))
    stringCompare.SetString(token)
    stringMatch4 = stringCompare.ContentsEqual("",true)
    if (stringMatch4 != true)
        encoded.SetString(token)
        bucketPath.Append("&continuation-token=")
        bucketPath.Append(encoded.getEncoded("url","utf-8"))
    end

    xmlStr = http.s3_ListBucketObjects(bucketPath.getAsString())
    if (http.get_LastMethodSuccess() != true)
        print "Request failed (transport or S3 error). HTTP status: " + http.get_LastStatus().to_s() + "\n";
        #  Inspect LastErrorText privately. Do not log credentials or signed URLs.
        exit
    end

    if (http.get_LastStatus() != 200)
        print "Unexpected HTTP status: " + http.get_LastStatus().to_s() + "\n";
        exit
    end

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

    stringCompare.SetString(xml.tag())
    stringMatch5 = stringCompare.ContentsEqual("ListBucketResult",true)
    if (stringMatch5 != true)
        print "Unexpected XML response root." + "\n";
        exit
    end

    stringCompare.SetString(xml.getChildContent("EncodingType"))
    stringMatch6 = stringCompare.ContentsEqual("url",true)
    if (stringMatch6 != true)
        print "Expected URL-encoded listing keys." + "\n";
        exit
    end

    i = 0
    count = xml.NumChildrenHavingTag("Contents")
    while (i < count)
        xml.put_I(i)
        #  Decode keys exactly once. Sizes remain decimal strings (not int).
        itemKey = http.urlDecode(xml.getChildContent("Contents[i]|Key"))
        stringCompare.SetString(itemKey)
        stringMatch7 = stringCompare.ContentsEqual("",true)
        if ((http.get_LastMethodSuccess() != true) or (stringMatch7 == true))
            print "Invalid object key." + "\n";
            exit
        end

        size = xml.getChildContent("Contents[i]|Size")
        stringCompare.SetString(size)
        stringMatch8 = stringCompare.ContentsEqual("",true)
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch8 == true))
            print "Incomplete object entry." + "\n";
            exit
        end

        modified = xml.getChildContent("Contents[i]|LastModified")
        stringCompare.SetString(modified)
        stringMatch9 = stringCompare.ContentsEqual("",true)
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch9 == true))
            print "Incomplete object entry." + "\n";
            exit
        end

        print "Key: " + itemKey + "\n";
        print "Bytes: " + size + "\n";
        #  S3 returns ISO 8601, not RFC 822. Keep the original UTC timestamp.
        print "Last modified (UTC): " + modified + "\n";
        i = i + 1
    end
    truncated = xml.getChildContent("IsTruncated")
    stringCompare.SetString(truncated)
    stringMatch10 = stringCompare.ContentsEqual("true",true)
    stringCompare.SetString(truncated)
    stringMatch11 = stringCompare.ContentsEqual("false",true)
    if ((stringMatch10 != true) and (stringMatch11 != true))
        print "Missing or invalid IsTruncated; listing is incomplete." + "\n";
        exit
    end

    more = false
    stringCompare.SetString(truncated)
    stringMatch12 = stringCompare.ContentsEqual("true",true)
    if (stringMatch12 == true)
        token = xml.getChildContent("NextContinuationToken")
        stringCompare.SetString(token)
        stringMatch13 = stringCompare.ContentsEqual("",true)
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch13 == true))
            print "Missing continuation token; listing is incomplete." + "\n";
            exit
        end

        if (seenTokens.Contains(token) == true)
            print "Repeated continuation token; listing is incomplete." + "\n";
            exit
        end

        success = seenTokens.AddStr(token,"seen")
        if (success != true)
            print "Could not track pagination." + "\n";
            exit
        end

        more = true
    end

end
print "Object listing complete." + "\n";