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

Amazon S3: Delete Multiple Objects and Check Each Result

See more S3 - REST Examples

Deletes the explicitly supplied objects. Load qa_data/aws/delete-objects.json with {"objects":[{"key":"documents/old.txt"},{"key":"documents/older.txt","version_id":"VERSION_ID"}]}. Supply 1–1000 unique entries per request. The example does not enumerate a prefix or automatically retry. Requires s3:DeleteObject and, for explicit versions, s3:DeleteObjectVersion.

Without versionId, an unversioned object is permanently removed; a versioned bucket normally creates a delete marker. Explicit data-version deletion is permanent. Retention, legal holds and MFA Delete can restrict deletion. Absent keys can still be acknowledged as deleted. HTTP 200 may contain per-object errors; each returned key/version is matched against the intended batch. Reconcile uncertain or missing results before any retry.

General purpose DeleteObjects uses Content-MD5. The tested AuthAws path omits that header, so this example explicitly constructs Signature Version 4 for the fixed POST /?delete= request and sends it through Rest. This is deliberately not a general URL signer. Do not change the body, hostname, query, or signed headers after signing, or attach AuthAws as a second signer.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS DeleteObjects reference

Chilkat Python Downloads

Python
import sys
import chilkat2

success = False

# StringBuilder compares text by value in every generated language.
textCompare = chilkat2.StringBuilder()
# Assumes Chilkat is unlocked. See Global Unlock Sample.
success = False
# Private configuration, not a file in public web content or source control.
# Load current IAM credentials authorized for the S3 operation.
credentials = chilkat2.JsonObject()
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/s3.json")
if (success != True):
    print("Could not load private AWS credentials.")
    sys.exit()

textCompare.Clear()
textCompare.SetString(credentials.StringOf("access_key"))
sameText1 = textCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("access_key") != 1) or (sameText1 == True)):
    print("Missing or invalid access_key.")
    sys.exit()

textCompare.Clear()
textCompare.SetString(credentials.StringOf("secret_key"))
sameText2 = textCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("secret_key") != 1) or (sameText2 == True)):
    print("Missing or invalid secret_key.")
    sys.exit()

# General purpose bucket in the commercial AWS partition.
region = "us-west-2"
bucketName = "amzn-s3-demo-bucket"
endpoint = chilkat2.StringBuilder()
success = endpoint.Append(bucketName)
if (success != True):
    print("Could not build text.")
    sys.exit()

success = endpoint.Append(".")
if (success != True):
    print("Could not build text.")
    sys.exit()

success = endpoint.Append("s3.")
if (success != True):
    print("Could not build text.")
    sys.exit()

success = endpoint.Append(region)
if (success != True):
    print("Could not build text.")
    sys.exit()

success = endpoint.Append(".amazonaws.com")
if (success != True):
    print("Could not build text.")
    sys.exit()

rest = chilkat2.Rest()
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
# Connect to the SAME hostname used for TLS verification and request signing.
connection = chilkat2.Socket()
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
if (success != True):
    print("TLS connection failed; inspect diagnostics privately.")
    sys.exit()

success = rest.UseConnection(connection,True)
if (success != True):
    print("Could not attach the TLS connection.")
    sys.exit()

xml = chilkat2.Xml()
xml.Strict = True
rest.Host = endpoint.GetAsString()
if (credentials.HasMember("session_token") == True):
    if (credentials.JsonTypeOf("session_token") != 1):
        print("session_token must be a string.")
        sys.exit()

# One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
batch = chilkat2.JsonObject()
batch.Strict = True
success = batch.LoadFile("qa_data/aws/delete-objects.json")
if (success != True):
    print("Could not load the intended deletion batch.")
    sys.exit()

count = batch.SizeOfArray("objects")
if ((count < 1) or (count > 1000)):
    print("Supply 1 to 1000 objects in the batch.")
    sys.exit()

xml.Tag = "Delete"
success = xml.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/")
if (success != True):
    print("Could not prepare the request.")
    sys.exit()

xml.UpdateChildContent("Quiet","false")
requested = chilkat2.Hashtable()
identity = chilkat2.JsonObject()
i = 0
while (i < count) :
    batch.I = i
    xml.I = i
    textCompare.Clear()
    textCompare.SetString(batch.StringOf("objects[i].key"))
    sameText3 = textCompare.ContentsEqual("",True)
    if ((batch.JsonTypeOf("objects[i].key") != 1) or (sameText3 == True)):
        print("Each object needs a nonempty key.")
        sys.exit()

    key = batch.StringOf("objects[i].key")
    version = ""
    if (batch.HasMember("objects[i].version_id") == True):
        textCompare.Clear()
        textCompare.SetString(batch.StringOf("objects[i].version_id"))
        sameText4 = textCompare.ContentsEqual("",True)
        if ((batch.JsonTypeOf("objects[i].version_id") != 1) or (sameText4 == True)):
            print("version_id must be a nonempty string when present.")
            sys.exit()

        version = batch.StringOf("objects[i].version_id")
        xml.UpdateChildContent("Object[i]|VersionId",version)

    xml.UpdateChildContent("Object[i]|Key",key)
    success = identity.UpdateString("key",key)
    if (success != True):
        print("Could not build saved state.")
        sys.exit()

    success = identity.UpdateString("version",version)
    if (success != True):
        print("Could not build saved state.")
        sys.exit()

    requestIdentity = identity.Emit()
    if (requested.Contains(requestIdentity) == True):
        print("Duplicate key/version in deletion batch.")
        sys.exit()

    success = requested.AddInt(requestIdentity,1)
    if (success != True):
        print("Could not prepare the request.")
        sys.exit()

    i = i + 1

requestBody = xml.GetXml()
# Explicit signing is used only for this fixed request so Content-MD5 survives.
# Rest sends it; AuthAws must NOT also be configured on this Rest instance.
# Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
# Do not change signed headers, body, endpoint, or query after signing.
host = chilkat2.StringBuilder()
host.Append(endpoint.GetAsString())
now = chilkat2.CkDateTime()
success = now.SetFromCurrentSystemTime()
if (success != True):
    print("Could not read system time.")
    sys.exit()

timestamp = chilkat2.StringBuilder()
timestamp.Append(now.GetAsTimestamp(False))
removedDashes = timestamp.Replace("-","")
removedColons = timestamp.Replace(":","")
amzDate = timestamp.GetAsString()
dateStamp = timestamp.GetRange(0,8,False)
crypt = chilkat2.Crypt2()
crypt.Charset = "utf-8"
crypt.HashAlgorithm = "md5"
crypt.EncodingMode = "base64"
contentMd5 = crypt.HashStringENC(requestBody)
if (crypt.LastMethodSuccess != True):
    print("Could not hash delete body.")
    sys.exit()

crypt.HashAlgorithm = "sha256"
crypt.EncodingMode = "hexlower"
payloadHash = crypt.HashStringENC(requestBody)
if (crypt.LastMethodSuccess != True):
    print("Could not hash delete body.")
    sys.exit()

signedHeaders = chilkat2.StringBuilder()
signedHeaders.Append("content-md5;host;x-amz-content-sha256;x-amz-date")
canonical = chilkat2.StringBuilder()
canonical.Append("POST\n/\ndelete=\ncontent-md5:")
canonical.Append(contentMd5)
canonical.Append("\nhost:")
canonical.Append(host.GetAsString())
canonical.Append("\nx-amz-content-sha256:")
canonical.Append(payloadHash)
canonical.Append("\nx-amz-date:")
canonical.Append(amzDate)
canonical.Append("\n")
if (credentials.HasMember("session_token") == True):
    textCompare.Clear()
    textCompare.SetString(credentials.StringOf("session_token"))
    sameText5 = textCompare.ContentsEqual("",True)
    if (sameText5 != True):
        signedHeaders.Append(";x-amz-security-token")
        canonical.Append("x-amz-security-token:")
        canonical.Append(credentials.StringOf("session_token"))
        canonical.Append("\n")
        success = rest.AddHeader("x-amz-security-token",credentials.StringOf("session_token"))
        if (success != True):
            print("Could not prepare the request.")
            sys.exit()

canonical.Append("\n")
canonical.Append(signedHeaders.GetAsString())
canonical.Append("\n")
canonical.Append(payloadHash)
canonicalHash = crypt.HashStringENC(canonical.GetAsString())
if (crypt.LastMethodSuccess != True):
    print("Could not hash canonical request.")
    sys.exit()

scope = chilkat2.StringBuilder()
scope.Append(dateStamp)
scope.Append("/")
scope.Append(region)
scope.Append("/s3/aws4_request")
stringToSign = chilkat2.StringBuilder()
stringToSign.Append("AWS4-HMAC-SHA256\n")
stringToSign.Append(amzDate)
stringToSign.Append("\n")
stringToSign.Append(scope.GetAsString())
stringToSign.Append("\n")
stringToSign.Append(canonicalHash)
initialKey = chilkat2.StringBuilder()
initialKey.Append("AWS4")
initialKey.Append(credentials.StringOf("secret_key"))
crypt.MacAlgorithm = "hmac"
success = crypt.SetMacKeyString(initialKey.GetAsString())
if (success != True):
    print("Could not set signing key.")
    sys.exit()

derivedKey = crypt.MacStringENC(dateStamp)
if (crypt.LastMethodSuccess != True):
    print("Could not derive date signing key.")
    sys.exit()

success = crypt.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
    print("Could not set derived signing key.")
    sys.exit()

derivedKey = crypt.MacStringENC(region)
if (crypt.LastMethodSuccess != True):
    print("Could not derive signing key.")
    sys.exit()

success = crypt.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
    print("Could not set derived signing key.")
    sys.exit()

derivedKey = crypt.MacStringENC("s3")
if (crypt.LastMethodSuccess != True):
    print("Could not derive signing key.")
    sys.exit()

success = crypt.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
    print("Could not set derived signing key.")
    sys.exit()

derivedKey = crypt.MacStringENC("aws4_request")
if (crypt.LastMethodSuccess != True):
    print("Could not derive signing key.")
    sys.exit()

success = crypt.SetMacKeyEncoded(derivedKey,"hex")
if (success != True):
    print("Could not set final signing key.")
    sys.exit()

signature = crypt.MacStringENC(stringToSign.GetAsString())
if (crypt.LastMethodSuccess != True):
    print("Could not sign delete request.")
    sys.exit()

authorization = chilkat2.StringBuilder()
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)
success = rest.AddHeader("Authorization",authorization.GetAsString())
if (success != True):
    print("Could not prepare the request.")
    sys.exit()

success = rest.AddHeader("Content-MD5",contentMd5)
if (success != True):
    print("Could not prepare the request.")
    sys.exit()

success = rest.AddHeader("x-amz-content-sha256",payloadHash)
if (success != True):
    print("Could not prepare the request.")
    sys.exit()

success = rest.AddHeader("x-amz-date",amzDate)
if (success != True):
    print("Could not prepare the request.")
    sys.exit()

success = rest.AddQueryParam("delete","")
if (success != True):
    print("Could not prepare the request.")
    sys.exit()

responseBody = rest.FullRequestString("POST","/",requestBody)
if (rest.LastMethodSuccess != True):
    print("Request did not complete; inspect diagnostics privately.")
    sys.exit()

if (rest.ResponseStatusCode != 200):
    print("S3 HTTP status: " + str(rest.ResponseStatusCode))
    success = xml.LoadXml(responseBody)
    textCompare.Clear()
    textCompare.SetString(xml.Tag)
    sameText6 = textCompare.ContentsEqual("Error",True)
    if ((success == True) and (sameText6 == True)):
        print("S3 error code: " + xml.GetChildContent("Code"))

    # Keep signed headers, credentials, URLs, and full diagnostics private.
    # A timeout may leave a write's outcome uncertain. Check before retrying.
    sys.exit()

success = xml.LoadXml(responseBody)
if (success != True):
    print("Expected well-formed XML.")
    sys.exit()

textCompare.Clear()
textCompare.SetString(xml.Tag)
sameText7 = textCompare.ContentsEqual("DeleteResult",True)
if (sameText7 != True):
    print("Unexpected S3 response element; this is not a successful result.")
    sys.exit()

deleted = xml.NumChildrenHavingTag("Deleted")
failed = xml.NumChildrenHavingTag("Error")
if (deleted + failed != count):
    print("Incomplete result: reconcile every requested object before retrying.")
    sys.exit()

received = chilkat2.Hashtable()
resultType = 0
while (resultType < 2) :
    itemTag = "Deleted"
    resultCount = deleted
    if (resultType == 1):
        itemTag = "Error"
        resultCount = failed

    j = 0
    while (j < resultCount) :
        xml.I = j
        itemPath = chilkat2.StringBuilder()
        success = itemPath.Append(itemTag)
        if (success != True):
            print("Could not build text.")
            sys.exit()

        success = itemPath.Append("[i]")
        if (success != True):
            print("Could not build text.")
            sys.exit()

        # item is a CkXml
        item = xml.FindChild(itemPath.GetAsString())
        if (xml.LastMethodSuccess != True):
            print("Missing deletion result entry.")
            sys.exit()

        resultKey = item.GetChildContent("Key")
        resultVersion = ""
        if (item.HasChildWithTag("VersionId") == True):
            resultVersion = item.GetChildContent("VersionId")

        success = identity.UpdateString("key",resultKey)
        if (success != True):
            print("Could not build saved state.")
            sys.exit()

        success = identity.UpdateString("version",resultVersion)
        if (success != True):
            print("Could not build saved state.")
            sys.exit()

        responseIdentity = identity.Emit()
        if ((requested.Contains(responseIdentity) != True) or (received.Contains(responseIdentity) == True)):
            print("Unexpected or duplicated deletion result; reconcile manually.")
            sys.exit()

        success = received.AddInt(responseIdentity,1)
        if (success != True):
            print("Could not prepare the request.")
            sys.exit()

        print(itemTag + ": " + resultKey)
        if (resultType == 1):
            print("Error code: " + item.GetChildContent("Code"))

        j = j + 1

    resultType = resultType + 1

if (failed > 0):
    print("Batch has per-object failures. Do not retry successful entries.")
    sys.exit()

print("All requested deletions acknowledged.")