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

AutoIt
Local $bSuccess = False

;  StringBuilder compares text by value in every generated language.
$oTextCompare = ObjCreate("Chilkat.StringBuilder")
;  Assumes Chilkat is unlocked. See Global Unlock Sample.
$bSuccess = False
;  Private configuration, not a file in public web content or source control.
;  Load current IAM credentials authorized for the S3 operation.
$oCredentials = ObjCreate("Chilkat.JsonObject")
$oCredentials.Strict = True
$bSuccess = $oCredentials.LoadFile("qa_data/aws/s3.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load private AWS credentials." & @CRLF)
    Exit
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($oCredentials.StringOf("access_key"))
Local $bSameText1 = $oTextCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("access_key") <> 1) Or ($bSameText1 = True)) Then
    ConsoleWrite("Missing or invalid access_key." & @CRLF)
    Exit
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($oCredentials.StringOf("secret_key"))
Local $bSameText2 = $oTextCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("secret_key") <> 1) Or ($bSameText2 = True)) Then
    ConsoleWrite("Missing or invalid secret_key." & @CRLF)
    Exit
EndIf

;  General purpose bucket in the commercial AWS partition.
Local $sRegion = "us-west-2"
Local $sBucketName = "amzn-s3-demo-bucket"
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$bSuccess = $oEndpoint.Append($sBucketName)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not build text." & @CRLF)
    Exit
EndIf

$bSuccess = $oEndpoint.Append(".")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not build text." & @CRLF)
    Exit
EndIf

$bSuccess = $oEndpoint.Append("s3.")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not build text." & @CRLF)
    Exit
EndIf

$bSuccess = $oEndpoint.Append($sRegion)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not build text." & @CRLF)
    Exit
EndIf

$bSuccess = $oEndpoint.Append(".amazonaws.com")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not build text." & @CRLF)
    Exit
EndIf

$oRest = ObjCreate("Chilkat.Rest")
$oRest.ConnectTimeoutMs = 20000
$oRest.IdleTimeoutMs = 60000
;  Connect to the SAME hostname used for TLS verification and request signing.
$oConnection = ObjCreate("Chilkat.Socket")
$oConnection.RequireSslCertVerify = True
$oConnection.MaxReadIdleMs = 60000
$oConnection.MaxSendIdleMs = 60000
$bSuccess = $oConnection.Connect($oEndpoint.GetAsString(),443,True,20000)
If ($bSuccess <> True) Then
    ConsoleWrite("TLS connection failed; inspect diagnostics privately." & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.UseConnection($oConnection,True)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not attach the TLS connection." & @CRLF)
    Exit
EndIf

$oXml = ObjCreate("Chilkat.Xml")
$oXml.Strict = True
$oRest.Host = $oEndpoint.GetAsString()
If ($oCredentials.HasMember("session_token") = True) Then
    If ($oCredentials.JsonTypeOf("session_token") <> 1) Then
        ConsoleWrite("session_token must be a string." & @CRLF)
        Exit
    EndIf

EndIf

;  One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
$oBatch = ObjCreate("Chilkat.JsonObject")
$oBatch.Strict = True
$bSuccess = $oBatch.LoadFile("qa_data/aws/delete-objects.json")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not load the intended deletion batch." & @CRLF)
    Exit
EndIf

Local $iCount = $oBatch.SizeOfArray("objects")
If (($iCount < 1) Or ($iCount > 1000)) Then
    ConsoleWrite("Supply 1 to 1000 objects in the batch." & @CRLF)
    Exit
EndIf

$oXml.Tag = "Delete"
$bSuccess = $oXml.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$oXml.UpdateChildContent "Quiet","false"
$oRequested = ObjCreate("Chilkat.Hashtable")
$oIdentity = ObjCreate("Chilkat.JsonObject")
Local $i = 0
While ($i < $iCount)
    $oBatch.I = $i
    $oXml.I = $i
    $oTextCompare.Clear 
    $oTextCompare.SetString($oBatch.StringOf("objects[i].key"))
Local $bSameText3 = $oTextCompare.ContentsEqual("",True)
    If (($oBatch.JsonTypeOf("objects[i].key") <> 1) Or ($bSameText3 = True)) Then
        ConsoleWrite("Each object needs a nonempty key." & @CRLF)
        Exit
    EndIf

Local $sKey = $oBatch.StringOf("objects[i].key")
Local $sVersion = ""
    If ($oBatch.HasMember("objects[i].version_id") = True) Then
        $oTextCompare.Clear 
        $oTextCompare.SetString($oBatch.StringOf("objects[i].version_id"))
Local $bSameText4 = $oTextCompare.ContentsEqual("",True)
        If (($oBatch.JsonTypeOf("objects[i].version_id") <> 1) Or ($bSameText4 = True)) Then
            ConsoleWrite("version_id must be a nonempty string when present." & @CRLF)
            Exit
        EndIf

        $sVersion = $oBatch.StringOf("objects[i].version_id")
        $oXml.UpdateChildContent "Object[i]|VersionId",$sVersion
    EndIf

    $oXml.UpdateChildContent "Object[i]|Key",$sKey
    $bSuccess = $oIdentity.UpdateString("key",$sKey)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not build saved state." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oIdentity.UpdateString("version",$sVersion)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not build saved state." & @CRLF)
        Exit
    EndIf

Local $sRequestIdentity = $oIdentity.Emit()
    If ($oRequested.Contains($sRequestIdentity) = True) Then
        ConsoleWrite("Duplicate key/version in deletion batch." & @CRLF)
        Exit
    EndIf

    $bSuccess = $oRequested.AddInt($sRequestIdentity,1)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not prepare the request." & @CRLF)
        Exit
    EndIf

    $i = $i + 1
Wend
Local $sRequestBody = $oXml.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.
$oHost = ObjCreate("Chilkat.StringBuilder")
$oHost.Append($oEndpoint.GetAsString())
$oNow = ObjCreate("Chilkat.CkDateTime")
$bSuccess = $oNow.SetFromCurrentSystemTime()
If ($bSuccess <> True) Then
    ConsoleWrite("Could not read system time." & @CRLF)
    Exit
EndIf

$oTimestamp = ObjCreate("Chilkat.StringBuilder")
$oTimestamp.Append($oNow.GetAsTimestamp(False))
Local $iRemovedDashes = $oTimestamp.Replace("-","")
Local $iRemovedColons = $oTimestamp.Replace(":","")
Local $sAmzDate = $oTimestamp.GetAsString()
Local $sDateStamp = $oTimestamp.GetRange(0,8,False)
$oCrypt = ObjCreate("Chilkat.Crypt2")
$oCrypt.Charset = "utf-8"
$oCrypt.HashAlgorithm = "md5"
$oCrypt.EncodingMode = "base64"
Local $sContentMd5 = $oCrypt.HashStringENC($sRequestBody)
If ($oCrypt.LastMethodSuccess <> True) Then
    ConsoleWrite("Could not hash delete body." & @CRLF)
    Exit
EndIf

$oCrypt.HashAlgorithm = "sha256"
$oCrypt.EncodingMode = "hexlower"
Local $sPayloadHash = $oCrypt.HashStringENC($sRequestBody)
If ($oCrypt.LastMethodSuccess <> True) Then
    ConsoleWrite("Could not hash delete body." & @CRLF)
    Exit
EndIf

$oSignedHeaders = ObjCreate("Chilkat.StringBuilder")
$oSignedHeaders.Append("content-md5;host;x-amz-content-sha256;x-amz-date")
$oCanonical = ObjCreate("Chilkat.StringBuilder")
$oCanonical.Append("POST" & @LF & "/" & @LF & "delete=" & @LF & "content-md5:")
$oCanonical.Append($sContentMd5)
$oCanonical.Append(@LF & "host:")
$oCanonical.Append($oHost.GetAsString())
$oCanonical.Append(@LF & "x-amz-content-sha256:")
$oCanonical.Append($sPayloadHash)
$oCanonical.Append(@LF & "x-amz-date:")
$oCanonical.Append($sAmzDate)
$oCanonical.Append(@LF)
If ($oCredentials.HasMember("session_token") = True) Then
    $oTextCompare.Clear 
    $oTextCompare.SetString($oCredentials.StringOf("session_token"))
Local $bSameText5 = $oTextCompare.ContentsEqual("",True)
    If ($bSameText5 <> True) Then
        $oSignedHeaders.Append(";x-amz-security-token")
        $oCanonical.Append("x-amz-security-token:")
        $oCanonical.Append($oCredentials.StringOf("session_token"))
        $oCanonical.Append(@LF)
        $bSuccess = $oRest.AddHeader("x-amz-security-token",$oCredentials.StringOf("session_token"))
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not prepare the request." & @CRLF)
            Exit
        EndIf

    EndIf

EndIf

$oCanonical.Append(@LF)
$oCanonical.Append($oSignedHeaders.GetAsString())
$oCanonical.Append(@LF)
$oCanonical.Append($sPayloadHash)
Local $sCanonicalHash = $oCrypt.HashStringENC($oCanonical.GetAsString())
If ($oCrypt.LastMethodSuccess <> True) Then
    ConsoleWrite("Could not hash canonical request." & @CRLF)
    Exit
EndIf

$oScope = ObjCreate("Chilkat.StringBuilder")
$oScope.Append($sDateStamp)
$oScope.Append("/")
$oScope.Append($sRegion)
$oScope.Append("/s3/aws4_request")
$oStringToSign = ObjCreate("Chilkat.StringBuilder")
$oStringToSign.Append("AWS4-HMAC-SHA256" & @LF)
$oStringToSign.Append($sAmzDate)
$oStringToSign.Append(@LF)
$oStringToSign.Append($oScope.GetAsString())
$oStringToSign.Append(@LF)
$oStringToSign.Append($sCanonicalHash)
$oInitialKey = ObjCreate("Chilkat.StringBuilder")
$oInitialKey.Append("AWS4")
$oInitialKey.Append($oCredentials.StringOf("secret_key"))
$oCrypt.MacAlgorithm = "hmac"
$bSuccess = $oCrypt.SetMacKeyString($oInitialKey.GetAsString())
If ($bSuccess <> True) Then
    ConsoleWrite("Could not set signing key." & @CRLF)
    Exit
EndIf

Local $sDerivedKey = $oCrypt.MacStringENC($sDateStamp)
If ($oCrypt.LastMethodSuccess <> True) Then
    ConsoleWrite("Could not derive date signing key." & @CRLF)
    Exit
EndIf

$bSuccess = $oCrypt.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not set derived signing key." & @CRLF)
    Exit
EndIf

$sDerivedKey = $oCrypt.MacStringENC($sRegion)
If ($oCrypt.LastMethodSuccess <> True) Then
    ConsoleWrite("Could not derive signing key." & @CRLF)
    Exit
EndIf

$bSuccess = $oCrypt.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not set derived signing key." & @CRLF)
    Exit
EndIf

$sDerivedKey = $oCrypt.MacStringENC("s3")
If ($oCrypt.LastMethodSuccess <> True) Then
    ConsoleWrite("Could not derive signing key." & @CRLF)
    Exit
EndIf

$bSuccess = $oCrypt.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not set derived signing key." & @CRLF)
    Exit
EndIf

$sDerivedKey = $oCrypt.MacStringENC("aws4_request")
If ($oCrypt.LastMethodSuccess <> True) Then
    ConsoleWrite("Could not derive signing key." & @CRLF)
    Exit
EndIf

$bSuccess = $oCrypt.SetMacKeyEncoded($sDerivedKey,"hex")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not set final signing key." & @CRLF)
    Exit
EndIf

Local $signature = $oCrypt.MacStringENC($oStringToSign.GetAsString())
If ($oCrypt.LastMethodSuccess <> True) Then
    ConsoleWrite("Could not sign delete request." & @CRLF)
    Exit
EndIf

$oAuthorization = ObjCreate("Chilkat.StringBuilder")
$oAuthorization.Append("AWS4-HMAC-SHA256 Credential=")
$oAuthorization.Append($oCredentials.StringOf("access_key"))
$oAuthorization.Append("/")
$oAuthorization.Append($oScope.GetAsString())
$oAuthorization.Append(", SignedHeaders=")
$oAuthorization.Append($oSignedHeaders.GetAsString())
$oAuthorization.Append(", Signature=")
$oAuthorization.Append($signature)
$bSuccess = $oRest.AddHeader("Authorization",$oAuthorization.GetAsString())
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.AddHeader("Content-MD5",$sContentMd5)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.AddHeader("x-amz-content-sha256",$sPayloadHash)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.AddHeader("x-amz-date",$sAmzDate)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

$bSuccess = $oRest.AddQueryParam("delete","")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

Local $sResponseBody = $oRest.FullRequestString("POST","/",$sRequestBody)
If ($oRest.LastMethodSuccess <> True) Then
    ConsoleWrite("Request did not complete; inspect diagnostics privately." & @CRLF)
    Exit
EndIf

If ($oRest.ResponseStatusCode <> 200) Then
    ConsoleWrite("S3 HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
    $bSuccess = $oXml.LoadXml($sResponseBody)
    $oTextCompare.Clear 
    $oTextCompare.SetString($oXml.Tag)
Local $bSameText6 = $oTextCompare.ContentsEqual("Error",True)
    If (($bSuccess = True) And ($bSameText6 = True)) Then
        ConsoleWrite("S3 error code: " & $oXml.GetChildContent("Code") & @CRLF)
    EndIf

    ;  Keep signed headers, credentials, URLs, and full diagnostics private.
    ;  A timeout may leave a write's outcome uncertain. Check before retrying.
    Exit
EndIf

$bSuccess = $oXml.LoadXml($sResponseBody)
If ($bSuccess <> True) Then
    ConsoleWrite("Expected well-formed XML." & @CRLF)
    Exit
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($oXml.Tag)
Local $bSameText7 = $oTextCompare.ContentsEqual("DeleteResult",True)
If ($bSameText7 <> True) Then
    ConsoleWrite("Unexpected S3 response element; this is not a successful result." & @CRLF)
    Exit
EndIf

Local $iDeleted = $oXml.NumChildrenHavingTag("Deleted")
Local $iFailed = $oXml.NumChildrenHavingTag("Error")
If ($iDeleted + $iFailed <> $iCount) Then
    ConsoleWrite("Incomplete result: reconcile every requested object before retrying." & @CRLF)
    Exit
EndIf

$oReceived = ObjCreate("Chilkat.Hashtable")
Local $iResultType = 0
While ($iResultType < 2)
Local $sItemTag = "Deleted"
Local $iResultCount = $iDeleted
    If ($iResultType = 1) Then
        $sItemTag = "Error"
        $iResultCount = $iFailed
    EndIf

Local $iJ = 0
    While ($iJ < $iResultCount)
        $oXml.I = $iJ
        $oItemPath = ObjCreate("Chilkat.StringBuilder")
        $bSuccess = $oItemPath.Append($sItemTag)
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not build text." & @CRLF)
            Exit
        EndIf

        $bSuccess = $oItemPath.Append("[i]")
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not build text." & @CRLF)
            Exit
        EndIf

Local $oItem = $oXml.FindChild($oItemPath.GetAsString())
        If ($oXml.LastMethodSuccess <> True) Then
            ConsoleWrite("Missing deletion result entry." & @CRLF)
            Exit
        EndIf

Local $sResultKey = $oItem.GetChildContent("Key")
Local $sResultVersion = ""
        If ($oItem.HasChildWithTag("VersionId") = True) Then
            $sResultVersion = $oItem.GetChildContent("VersionId")
        EndIf

        $bSuccess = $oIdentity.UpdateString("key",$sResultKey)
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not build saved state." & @CRLF)
            Exit
        EndIf

        $bSuccess = $oIdentity.UpdateString("version",$sResultVersion)
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not build saved state." & @CRLF)
            Exit
        EndIf

Local $sResponseIdentity = $oIdentity.Emit()
        If (($oRequested.Contains($sResponseIdentity) <> True) Or ($oReceived.Contains($sResponseIdentity) = True)) Then
            ConsoleWrite("Unexpected or duplicated deletion result; reconcile manually." & @CRLF)
            Exit
        EndIf

        $bSuccess = $oReceived.AddInt($sResponseIdentity,1)
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not prepare the request." & @CRLF)
            Exit
        EndIf

        ConsoleWrite($sItemTag & ": " & $sResultKey & @CRLF)
        If ($iResultType = 1) Then
            ConsoleWrite("Error code: " & $oItem.GetChildContent("Code") & @CRLF)
        EndIf

        $iJ = $iJ + 1
    Wend
    $iResultType = $iResultType + 1
Wend
If ($iFailed > 0) Then
    ConsoleWrite("Batch has per-object failures. Do not retry successful entries." & @CRLF)
    Exit
EndIf

ConsoleWrite("All requested deletions acknowledged." & @CRLF)