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

Python
import sys
import chilkat2

success = False

stringCompare = chilkat2.StringBuilder()
# 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 = chilkat2.JsonObject()
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/s3.json")
if (success != True):
    print("Could not load private S3 credentials.")
    sys.exit()

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.")
    sys.exit()

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.")
    sys.exit()

http = chilkat2.Http()
http.AwsAccessKey = credentials.StringOf("access_key")
http.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.")
        sys.exit()

    http.AwsSessionToken = credentials.StringOf("session_token")

# 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.AwsRegion = region
endpoint = chilkat2.StringBuilder()
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.
bucketName = "your-bucket-name"
bucketPath = chilkat2.StringBuilder()
encoded = chilkat2.StringBuilder()
xml = chilkat2.Xml()
seenTokens = chilkat2.Hashtable()
token = ""
more = True
page = 0
prefix = "images/"
while (more == True) :
    if (page == 10000):
        print("Page limit reached; listing is incomplete.")
        sys.exit()

    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"))

    xmlStr = http.S3_ListBucketObjects(bucketPath.GetAsString())
    if (http.LastMethodSuccess != True):
        print("Request failed (transport or S3 error). HTTP status: " + str(http.LastStatus))
        # Inspect LastErrorText privately. Do not log credentials or signed URLs.
        sys.exit()

    if (http.LastStatus != 200):
        print("Unexpected HTTP status: " + str(http.LastStatus))
        sys.exit()

    success = xml.LoadXml(xmlStr)
    if (success != True):
        print("Invalid XML response.")
        sys.exit()

    stringCompare.SetString(xml.Tag)
    stringMatch5 = stringCompare.ContentsEqual("ListBucketResult",True)
    if (stringMatch5 != True):
        print("Unexpected XML response root.")
        sys.exit()

    stringCompare.SetString(xml.GetChildContent("EncodingType"))
    stringMatch6 = stringCompare.ContentsEqual("url",True)
    if (stringMatch6 != True):
        print("Expected URL-encoded listing keys.")
        sys.exit()

    i = 0
    count = xml.NumChildrenHavingTag("Contents")
    while (i < count) :
        xml.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.LastMethodSuccess != True) or (stringMatch7 == True)):
            print("Invalid object key.")
            sys.exit()

        size = xml.GetChildContent("Contents[i]|Size")
        stringCompare.SetString(size)
        stringMatch8 = stringCompare.ContentsEqual("",True)
        if ((xml.LastMethodSuccess != True) or (stringMatch8 == True)):
            print("Incomplete object entry.")
            sys.exit()

        modified = xml.GetChildContent("Contents[i]|LastModified")
        stringCompare.SetString(modified)
        stringMatch9 = stringCompare.ContentsEqual("",True)
        if ((xml.LastMethodSuccess != True) or (stringMatch9 == True)):
            print("Incomplete object entry.")
            sys.exit()

        print("Key: " + itemKey)
        print("Bytes: " + size)
        # S3 returns ISO 8601, not RFC 822. Keep the original UTC timestamp.
        print("Last modified (UTC): " + modified)
        i = i + 1

    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.")
        sys.exit()

    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.LastMethodSuccess != True) or (stringMatch13 == True)):
            print("Missing continuation token; listing is incomplete.")
            sys.exit()

        if (seenTokens.Contains(token) == True):
            print("Repeated continuation token; listing is incomplete.")
            sys.exit()

        success = seenTokens.AddStr(token,"seen")
        if (success != True):
            print("Could not track pagination.")
            sys.exit()

        more = True

print("Object listing complete.")