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

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  var success = false;

  // StringBuilder compares text by value in every generated language.
  final textCompare = CkStringBuilder();
  // 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.
  final credentials = CkJsonObject();
  credentials.strict = true;
  try {
    credentials.loadFile('qa_data/aws/s3.json');
  } on ChilkatException {
    print('Could not load private AWS credentials.');
    return;
  }

  textCompare.clear();
  textCompare.setString(credentials.stringOf('access_key'));
  final sameText1 = textCompare.contentsEqual('', true);
  if ((credentials.jsonTypeOf('access_key') != 1) || (sameText1)) {
    print('Missing or invalid access_key.');
    return;
  }

  textCompare.clear();
  textCompare.setString(credentials.stringOf('secret_key'));
  final sameText2 = textCompare.contentsEqual('', true);
  if ((credentials.jsonTypeOf('secret_key') != 1) || (sameText2)) {
    print('Missing or invalid secret_key.');
    return;
  }

  // General purpose bucket in the commercial AWS partition.
  final region = 'us-west-2';
  final bucketName = 'amzn-s3-demo-bucket';
  final endpoint = CkStringBuilder();
  try {
    endpoint.append(bucketName);
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    endpoint.append('.');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    endpoint.append('s3.');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    endpoint.append(region);
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    endpoint.append('.amazonaws.com');
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  final aws = CkAuthAws();
  aws.accessKey = credentials.stringOf('access_key');
  aws.secretKey = credentials.stringOf('secret_key');
  aws.region = region;
  aws.serviceName = 's3';
  aws.signatureVersion = 4;
  final rest = CkRest();
  rest.connectTimeoutMs = 20000;
  rest.idleTimeoutMs = 60000;
  try {
    rest.setAuthAws(aws);
  } on ChilkatException {
    print('Could not configure AWS signing.');
    return;
  }

  // Temporary credentials require this token in every signed query.
  // Keep request URLs private. Do not clear this parameter between requests.
  if (credentials.hasMember('session_token')) {
    if (credentials.jsonTypeOf('session_token') != 1) {
      print('session_token must be a string.');
      return;
    }

    textCompare.clear();
    textCompare.setString(credentials.stringOf('session_token'));
    final sameText3 = textCompare.contentsEqual('', true);
    if (!sameText3) {
      try {
        rest.addQueryParam('X-Amz-Security-Token', credentials.stringOf('session_token'));
      } on ChilkatException {
        print('Could not prepare the request.');
        return;
      }
    }
  }

  // Connect to the SAME hostname used for TLS verification and request signing.
  final connection = CkSocket();
  connection.requireSslCertVerify = true;
  connection.maxReadIdleMs = 60000;
  connection.maxSendIdleMs = 60000;
  try {
    connection.connect(endpoint.getAsString(), 443, true, 20000);
  } on ChilkatException {
    print('TLS connection failed; inspect diagnostics privately.');
    return;
  }

  try {
    rest.useConnection(connection, true);
  } on ChilkatException {
    print('Could not attach the TLS connection.');
    return;
  }

  final xml = CkXml();
  xml.strict = true;
  // Supply an unencoded object key, not a URL. Preserve slashes in the key.
  final objectKey = 'documents/example.txt';
  final objectPath = CkStringBuilder();
  try {
    objectPath.append(objectKey);
  } on ChilkatException {
    print('Could not build text.');
    return;
  }

  try {
    objectPath.encode('url_rfc3986', 'utf-8');
  } on ChilkatException {
    print('Could not encode the object key.');
    return;
  }

  final restoredSlashes = objectPath.replace('%2F', '/');
  try {
    objectPath.prepend('/');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  final operation = 'merge';
  final tagKey = 'Environment';
  final tagValue = 'test';
  textCompare.clear();
  textCompare.setString(operation);
  final sameText4 = textCompare.contentsEqual('read', true);
  textCompare.clear();
  textCompare.setString(operation);
  final sameText5 = textCompare.contentsEqual('merge', true);
  textCompare.clear();
  textCompare.setString(operation);
  final sameText6 = textCompare.contentsEqual('remove-one', true);
  textCompare.clear();
  textCompare.setString(operation);
  final sameText7 = textCompare.contentsEqual('delete-all', true);
  if ((!sameText4) && ((!sameText5) && ((!sameText6) && (!sameText7)))) {
    print('Choose read, merge, remove-one, or delete-all.');
    return;
  }

  try {
    rest.addQueryParam('tagging', '');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  String responseBody;
  try {
    responseBody = rest.fullRequestNoBody('GET', objectPath.getAsString());
  } on ChilkatException {
    print('Request did not complete; inspect diagnostics privately.');
    return;
  }

  if (rest.responseStatusCode != 200) {
    print('S3 HTTP status: ${rest.responseStatusCode}');
    success = true;
    try {
      xml.loadXml(responseBody);
    } on ChilkatException {
      success = false;
    }
    textCompare.clear();
    textCompare.setString(xml.tag);
    final sameText8 = textCompare.contentsEqual('Error', true);
    if ((success) && (sameText8)) {
      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.
    return;
  }

  try {
    xml.loadXml(responseBody);
  } on ChilkatException {
    print('Expected well-formed XML.');
    return;
  }

  textCompare.clear();
  textCompare.setString(xml.tag);
  final sameText9 = textCompare.contentsEqual('Tagging', true);
  if (!sameText9) {
    print('Unexpected S3 response element; this is not a successful result.');
    return;
  }

  if (!xml.hasChildWithTag('TagSet')) {
    print('Missing TagSet.');
    return;
  }

  // Pin the version that was read when S3 returns its version ID.
  var versionId = '';
  try {
    versionId = rest.responseHdrByName('x-amz-version-id');
  } on ChilkatException {
    versionId = '';
  }

  textCompare.clear();
  textCompare.setString(versionId);
  final sameText10 = textCompare.contentsEqual('', true);
  if (!sameText10) {
    try {
      rest.addQueryParam('versionId', versionId);
    } on ChilkatException {
      print('Could not prepare the request.');
      return;
    }
  }

  textCompare.clear();
  textCompare.setString(operation);
  final sameText11 = textCompare.contentsEqual('read', true);
  if (sameText11) {
    print(xml.getXml());
    return;
  }

  textCompare.clear();
  textCompare.setString(operation);
  final sameText12 = textCompare.contentsEqual('delete-all', true);
  if (sameText12) {
    try {
      responseBody = rest.fullRequestNoBody('DELETE', objectPath.getAsString());
    } on ChilkatException {
      print('Request did not complete; inspect diagnostics privately.');
      return;
    }

    if (rest.responseStatusCode != 204) {
      print('S3 HTTP status: ${rest.responseStatusCode}');
      success = true;
      try {
        xml.loadXml(responseBody);
      } on ChilkatException {
        success = false;
      }
      textCompare.clear();
      textCompare.setString(xml.tag);
      final sameText13 = textCompare.contentsEqual('Error', true);
      if ((success) && (sameText13)) {
        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.
      return;
    }

    print('All object tags removed.');
    return;
  }

  final replacement = CkXml();
  replacement.tag = 'Tagging';
  try {
    replacement.addAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  replacement.newChild2('TagSet', '');
  final seenKeys = CkHashtable();
  var i = 0;
  var retained = 0;
  while (i < xml.numChildrenAt('TagSet')) {
    xml.i = i;
    textCompare.clear();
    textCompare.setString(xml.getChildContent('TagSet|Tag[i]|Key'));
    final sameText14 = textCompare.contentsEqual('', true);
    if ((!xml.hasChildWithTag('TagSet|Tag[i]|Key')) || (sameText14)) {
      print('Missing response field: TagSet|Tag[i]|Key');
      return;
    }

    if (!xml.hasChildWithTag('TagSet|Tag[i]|Value')) {
      print('Missing tag value.');
      return;
    }

    final existingKey = xml.getChildContent('TagSet|Tag[i]|Key');
    if (seenKeys.contains(existingKey)) {
      print('Duplicate key in returned tag set.');
      return;
    }

    try {
      seenKeys.addInt(existingKey, 1);
    } on ChilkatException {
      print('Could not prepare the request.');
      return;
    }

    textCompare.clear();
    textCompare.setString(existingKey);
    final sameText15 = textCompare.contentsEqual(tagKey, true);
    if (!sameText15) {
      replacement.i = retained;
      replacement.updateChildContent('TagSet|Tag[i]|Key', existingKey);
      replacement.updateChildContent('TagSet|Tag[i]|Value', xml.getChildContent('TagSet|Tag[i]|Value'));
      retained++;
    }

    i++;
  }

  textCompare.clear();
  textCompare.setString(operation);
  final sameText16 = textCompare.contentsEqual('merge', true);
  if (sameText16) {
    replacement.i = retained;
    replacement.updateChildContent('TagSet|Tag[i]|Key', tagKey);
    replacement.updateChildContent('TagSet|Tag[i]|Value', tagValue);
    retained++;
  }

  if (retained > 10) {
    print('The resulting tag set exceeds 10 tags; no change was sent.');
    return;
  }

  final requestBody = replacement.getXml();
  final digest = CkCrypt2();
  digest.charset = 'utf-8';
  digest.hashAlgorithm = 'sha256';
  digest.encodingMode = 'base64';
  final String checksumBase64;
  try {
    checksumBase64 = digest.hashStringENC(requestBody);
  } on ChilkatException {
    print('Could not calculate the content checksum.');
    return;
  }

  try {
    rest.addHeader('x-amz-checksum-sha256', checksumBase64);
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    rest.addHeader('Content-Type', 'application/xml');
  } on ChilkatException {
    print('Could not prepare the request.');
    return;
  }

  try {
    responseBody = rest.fullRequestString('PUT', objectPath.getAsString(), requestBody);
  } on ChilkatException {
    print('Request did not complete; inspect diagnostics privately.');
    return;
  }

  if (rest.responseStatusCode != 200) {
    print('S3 HTTP status: ${rest.responseStatusCode}');
    success = true;
    try {
      xml.loadXml(responseBody);
    } on ChilkatException {
      success = false;
    }
    textCompare.clear();
    textCompare.setString(xml.tag);
    final sameText17 = textCompare.contentsEqual('Error', true);
    if ((success) && (sameText17)) {
      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.
    return;
  }

  print('Updated tag set saved; unrelated tags were preserved from the read.');
}