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

Amazon S3: Read, Merge, and Remove Object Tags

See more S3 - REST Examples

Select read, merge, remove-one, or delete-all. Merge adds or replaces one named tag while preserving other tags from GetObjectTagging. Remove-one rebuilds the set without that key; delete-all uses DeleteObjectTagging. An empty tag value is valid. The replacement has at most 10 tags and includes a SHA-256 request checksum.

Tagging is read/modify/write, not an atomic conditional update. Coordinate concurrent tag writers; an ETag condition on the object is not a tag-set compare-and-swap. The returned version ID is reused when available to target that data version. For unversioned objects or the mutable null version, coordinate object writers as well as tag writers. Requires the corresponding Get/Put/DeleteObjectTagging permissions and their version-specific variants when versionId is used. Tags are distinct from user metadata.

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 GetObjectTagging 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

$oAws = ObjCreate("Chilkat.AuthAws")
$oAws.AccessKey = $oCredentials.StringOf("access_key")
$oAws.SecretKey = $oCredentials.StringOf("secret_key")
$oAws.Region = $sRegion
$oAws.ServiceName = "s3"
$oAws.SignatureVersion = 4
$oRest = ObjCreate("Chilkat.Rest")
$oRest.ConnectTimeoutMs = 20000
$oRest.IdleTimeoutMs = 60000
$bSuccess = $oRest.SetAuthAws($oAws)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not configure AWS signing." & @CRLF)
    Exit
EndIf

;  Temporary credentials require this token in every signed query.
;  Keep request URLs private. Do not clear this parameter between requests.
If ($oCredentials.HasMember("session_token") = True) Then
    If ($oCredentials.JsonTypeOf("session_token") <> 1) Then
        ConsoleWrite("session_token must be a string." & @CRLF)
        Exit
    EndIf

    $oTextCompare.Clear 
    $oTextCompare.SetString($oCredentials.StringOf("session_token"))
Local $bSameText3 = $oTextCompare.ContentsEqual("",True)
    If ($bSameText3 <> True) Then
        $bSuccess = $oRest.AddQueryParam("X-Amz-Security-Token",$oCredentials.StringOf("session_token"))
        If ($bSuccess <> True) Then
            ConsoleWrite("Could not prepare the request." & @CRLF)
            Exit
        EndIf

    EndIf

EndIf

;  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
;  Supply an unencoded object key, not a URL. Preserve slashes in the key.
Local $sObjectKey = "documents/example.txt"
$oObjectPath = ObjCreate("Chilkat.StringBuilder")
$bSuccess = $oObjectPath.Append($sObjectKey)
If ($bSuccess <> True) Then
    ConsoleWrite("Could not build text." & @CRLF)
    Exit
EndIf

$bSuccess = $oObjectPath.Encode("url_rfc3986","utf-8")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not encode the object key." & @CRLF)
    Exit
EndIf

Local $iRestoredSlashes = $oObjectPath.Replace("%2F","/")
$bSuccess = $oObjectPath.Prepend("/")
If ($bSuccess <> True) Then
    ConsoleWrite("Could not prepare the request." & @CRLF)
    Exit
EndIf

Local $sOperation = "merge"
Local $sTagKey = "Environment"
Local $sTagValue = "test"
$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText4 = $oTextCompare.ContentsEqual("read",True)
$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText5 = $oTextCompare.ContentsEqual("merge",True)
$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText6 = $oTextCompare.ContentsEqual("remove-one",True)
$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText7 = $oTextCompare.ContentsEqual("delete-all",True)
If (($bSameText4 <> True) And ($bSameText5 <> True) And ($bSameText6 <> True) And ($bSameText7 <> True)) Then
    ConsoleWrite("Choose read, merge, remove-one, or delete-all." & @CRLF)
    Exit
EndIf

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

Local $sResponseBody = $oRest.FullRequestNoBody("GET",$oObjectPath.GetAsString())
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 $bSameText8 = $oTextCompare.ContentsEqual("Error",True)
    If (($bSuccess = True) And ($bSameText8 = 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 $bSameText9 = $oTextCompare.ContentsEqual("Tagging",True)
If ($bSameText9 <> True) Then
    ConsoleWrite("Unexpected S3 response element; this is not a successful result." & @CRLF)
    Exit
EndIf

If ($oXml.HasChildWithTag("TagSet") <> True) Then
    ConsoleWrite("Missing TagSet." & @CRLF)
    Exit
EndIf

;  Pin the version that was read when S3 returns its version ID.
Local $sVersionId = $oRest.ResponseHdrByName("x-amz-version-id")
If ($oRest.LastMethodSuccess <> True) Then
    $sVersionId = ""
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($sVersionId)
Local $bSameText10 = $oTextCompare.ContentsEqual("",True)
If ($bSameText10 <> True) Then
    $bSuccess = $oRest.AddQueryParam("versionId",$sVersionId)
    If ($bSuccess <> True) Then
        ConsoleWrite("Could not prepare the request." & @CRLF)
        Exit
    EndIf

EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText11 = $oTextCompare.ContentsEqual("read",True)
If ($bSameText11 = True) Then
    ConsoleWrite($oXml.GetXml() & @CRLF)
    Exit
EndIf

$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText12 = $oTextCompare.ContentsEqual("delete-all",True)
If ($bSameText12 = True) Then
    $sResponseBody = $oRest.FullRequestNoBody("DELETE",$oObjectPath.GetAsString())
    If ($oRest.LastMethodSuccess <> True) Then
        ConsoleWrite("Request did not complete; inspect diagnostics privately." & @CRLF)
        Exit
    EndIf

    If ($oRest.ResponseStatusCode <> 204) Then
        ConsoleWrite("S3 HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
        $bSuccess = $oXml.LoadXml($sResponseBody)
        $oTextCompare.Clear 
        $oTextCompare.SetString($oXml.Tag)
Local $bSameText13 = $oTextCompare.ContentsEqual("Error",True)
        If (($bSuccess = True) And ($bSameText13 = 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

    ConsoleWrite("All object tags removed." & @CRLF)
    Exit
EndIf

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

$oReplacement.NewChild2 "TagSet",""
$oSeenKeys = ObjCreate("Chilkat.Hashtable")
Local $i = 0
Local $iRetained = 0
While ($i < $oXml.NumChildrenAt("TagSet"))
    $oXml.I = $i
    $oTextCompare.Clear 
    $oTextCompare.SetString($oXml.GetChildContent("TagSet|Tag[i]|Key"))
Local $bSameText14 = $oTextCompare.ContentsEqual("",True)
    If (($oXml.HasChildWithTag("TagSet|Tag[i]|Key") <> True) Or ($bSameText14 = True)) Then
        ConsoleWrite("Missing response field: TagSet|Tag[i]|Key" & @CRLF)
        Exit
    EndIf

    If ($oXml.HasChildWithTag("TagSet|Tag[i]|Value") <> True) Then
        ConsoleWrite("Missing tag value." & @CRLF)
        Exit
    EndIf

Local $sExistingKey = $oXml.GetChildContent("TagSet|Tag[i]|Key")
    If ($oSeenKeys.Contains($sExistingKey) = True) Then
        ConsoleWrite("Duplicate key in returned tag set." & @CRLF)
        Exit
    EndIf

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

    $oTextCompare.Clear 
    $oTextCompare.SetString($sExistingKey)
Local $bSameText15 = $oTextCompare.ContentsEqual($sTagKey,True)
    If ($bSameText15 <> True) Then
        $oReplacement.I = $iRetained
        $oReplacement.UpdateChildContent "TagSet|Tag[i]|Key",$sExistingKey
        $oReplacement.UpdateChildContent "TagSet|Tag[i]|Value",$oXml.GetChildContent("TagSet|Tag[i]|Value")
        $iRetained = $iRetained + 1
    EndIf

    $i = $i + 1
Wend
$oTextCompare.Clear 
$oTextCompare.SetString($sOperation)
Local $bSameText16 = $oTextCompare.ContentsEqual("merge",True)
If ($bSameText16 = True) Then
    $oReplacement.I = $iRetained
    $oReplacement.UpdateChildContent "TagSet|Tag[i]|Key",$sTagKey
    $oReplacement.UpdateChildContent "TagSet|Tag[i]|Value",$sTagValue
    $iRetained = $iRetained + 1
EndIf

If ($iRetained > 10) Then
    ConsoleWrite("The resulting tag set exceeds 10 tags; no change was sent." & @CRLF)
    Exit
EndIf

Local $sRequestBody = $oReplacement.GetXml()
$oDigest = ObjCreate("Chilkat.Crypt2")
$oDigest.Charset = "utf-8"
$oDigest.HashAlgorithm = "sha256"
$oDigest.EncodingMode = "base64"
Local $sChecksumBase64 = $oDigest.HashStringENC($sRequestBody)
If ($oDigest.LastMethodSuccess <> True) Then
    ConsoleWrite("Could not calculate the content checksum." & @CRLF)
    Exit
EndIf

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

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

$sResponseBody = $oRest.FullRequestString("PUT",$oObjectPath.GetAsString(),$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 $bSameText17 = $oTextCompare.ContentsEqual("Error",True)
    If (($bSuccess = True) And ($bSameText17 = 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

ConsoleWrite("Updated tag set saved; unrelated tags were preserved from the read." & @CRLF)