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

S3: Retrieve Paginated ListObjectsV2 XML

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.

Prints each validated XML page separately, rather than pretending multiple pages form one XML document. Keys in the XML remain URL-encoded. Use the parsed listing example to decode them.

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

    print(xml.GetXml())
    truncated = xml.GetChildContent("IsTruncated")
    stringCompare.SetString(truncated)
    stringMatch7 = stringCompare.ContentsEqual("true",True)
    stringCompare.SetString(truncated)
    stringMatch8 = stringCompare.ContentsEqual("false",True)
    if ((stringMatch7 != True) and (stringMatch8 != True)):
        print("Missing or invalid IsTruncated; listing is incomplete.")
        sys.exit()

    more = False
    stringCompare.SetString(truncated)
    stringMatch9 = stringCompare.ContentsEqual("true",True)
    if (stringMatch9 == True):
        token = xml.GetChildContent("NextContinuationToken")
        stringCompare.SetString(token)
        stringMatch10 = stringCompare.ContentsEqual("",True)
        if ((xml.LastMethodSuccess != True) or (stringMatch10 == 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.")