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

Amazon S3: List Objects with ListObjectsV2

See more S3 - REST Examples

List current keys under a prefix using ListObjectsV2. Follow NextContinuationToken even when a page is empty. Requires s3:ListBucket. encoding-type=url makes XML-safe keys; decode once before using a returned key. Sizes and ETags remain strings. A listing is not an atomic snapshot across pages.

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 ListObjectsV2 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;
  success = true;
  try {
    credentials.loadFile('qa_data/aws/s3.json');
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    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();
  success = true;
  try {
    endpoint.append(bucketName);
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not build text.');
    return;
  }

  success = true;
  try {
    endpoint.append('.');
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not build text.');
    return;
  }

  success = true;
  try {
    endpoint.append('s3.');
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not build text.');
    return;
  }

  success = true;
  try {
    endpoint.append(region);
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not build text.');
    return;
  }

  success = true;
  try {
    endpoint.append('.amazonaws.com');
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    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;
  success = true;
  try {
    rest.setAuthAws(aws);
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    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) {
      success = true;
      try {
        rest.addQueryParam('X-Amz-Security-Token', credentials.stringOf('session_token'));
      } on ChilkatException {
        success = false;
      }
      if (!success) {
        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;
  success = true;
  try {
    connection.connect(endpoint.getAsString(), 443, true, 20000);
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('TLS connection failed; inspect diagnostics privately.');
    return;
  }

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

  final xml = CkXml();
  xml.strict = true;
  success = true;
  try {
    rest.addQueryParam('list-type', '2');
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not prepare the request.');
    return;
  }

  success = true;
  try {
    rest.addQueryParam('max-keys', '1000');
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not prepare the request.');
    return;
  }

  success = true;
  try {
    rest.addQueryParam('encoding-type', 'url');
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not prepare the request.');
    return;
  }

  // Optional prefix filter; a slash is part of an object key, not a real folder.
  success = true;
  try {
    rest.addQueryParam('prefix', 'documents/');
  } on ChilkatException {
    success = false;
  }
  if (!success) {
    print('Could not prepare the request.');
    return;
  }

  final seenTokens = CkHashtable();
  var nextToken = '';
  var more = true;
  var page = 0;
  while (more) {
    if (page == 1000) {
      print('Page limit reached; enumeration is incomplete.');
      return;
    }

    final String responseBody;
    try {
      responseBody = rest.fullRequestNoBody('GET', '/');
    } 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 sameText4 = textCompare.contentsEqual('Error', true);
      if ((success) && (sameText4)) {
        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;
    }

    success = true;
    try {
      xml.loadXml(responseBody);
    } on ChilkatException {
      success = false;
    }
    if (!success) {
      print('Expected well-formed XML.');
      return;
    }

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

    var i = 0;
    while (i < xml.numChildrenHavingTag('Contents')) {
      xml.i = i;
      textCompare.clear();
      textCompare.setString(xml.getChildContent('Contents[i]|Key'));
      final sameText6 = textCompare.contentsEqual('', true);
      if ((!xml.hasChildWithTag('Contents[i]|Key')) || (sameText6)) {
        print('Missing response field: Contents[i]|Key');
        return;
      }

      print('Encoded key: ${xml.getChildContent('Contents[i]|Key')}');
      textCompare.clear();
      textCompare.setString(xml.getChildContent('Contents[i]|Size'));
      final sameText7 = textCompare.contentsEqual('', true);
      if ((!xml.hasChildWithTag('Contents[i]|Size')) || (sameText7)) {
        print('Missing response field: Contents[i]|Size');
        return;
      }

      print('Size: ${xml.getChildContent('Contents[i]|Size')}');
      textCompare.clear();
      textCompare.setString(xml.getChildContent('Contents[i]|ETag'));
      final sameText8 = textCompare.contentsEqual('', true);
      if ((!xml.hasChildWithTag('Contents[i]|ETag')) || (sameText8)) {
        print('Missing response field: Contents[i]|ETag');
        return;
      }

      print('ETag: ${xml.getChildContent('Contents[i]|ETag')}');
      // Decode percent escapes without interpreting a literal plus as a space.
      final decodedKey = CkStringBuilder();
      success = true;
      try {
        decodedKey.append(xml.getChildContent('Contents[i]|Key'));
      } on ChilkatException {
        success = false;
      }
      if (!success) {
        print('Could not prepare the request.');
        return;
      }

      final escapedPluses = decodedKey.replace('+', '%2B');
      success = true;
      try {
        decodedKey.decode('url', 'utf-8');
      } on ChilkatException {
        success = false;
      }
      if (!success) {
        print('Could not decode object key.');
        return;
      }

      print('Key: ${decodedKey.getAsString()}');
      i++;
    }

    page++;
    more = false;
    nextToken = '';
    textCompare.clear();
    textCompare.setString(xml.getChildContent('IsTruncated'));
    final sameText9 = textCompare.contentsEqual('', true);
    if ((!xml.hasChildWithTag('IsTruncated')) || (sameText9)) {
      print('Missing response field: IsTruncated');
      return;
    }

    textCompare.clear();
    textCompare.setString(xml.getChildContent('IsTruncated'));
    final sameText10 = textCompare.contentsEqual('true', true);
    textCompare.clear();
    textCompare.setString(xml.getChildContent('IsTruncated'));
    final sameText11 = textCompare.contentsEqual('false', true);
    if ((!sameText10) && (!sameText11)) {
      print('Invalid IsTruncated value.');
      return;
    }

    textCompare.clear();
    textCompare.setString(xml.getChildContent('IsTruncated'));
    final sameText12 = textCompare.contentsEqual('true', true);
    if (sameText12) {
      textCompare.clear();
      textCompare.setString(xml.getChildContent('NextContinuationToken'));
      final sameText13 = textCompare.contentsEqual('', true);
      if ((!xml.hasChildWithTag('NextContinuationToken')) || (sameText13)) {
        print('Missing response field: NextContinuationToken');
        return;
      }

      nextToken = xml.getChildContent('NextContinuationToken');
    }

    textCompare.clear();
    textCompare.setString(nextToken);
    final sameText14 = textCompare.contentsEqual('', true);
    if (!sameText14) {
      if (seenTokens.contains(nextToken)) {
        print('Repeated pagination token; enumeration is incomplete.');
        return;
      }

      success = true;
      try {
        seenTokens.addInt(nextToken, 1);
      } on ChilkatException {
        success = false;
      }
      if (!success) {
        print('Could not track pagination.');
        return;
      }

      if (page > 1) {
        success = true;
        try {
          rest.removeQueryParam('continuation-token');
        } on ChilkatException {
          success = false;
        }
        if (!success) {
          print('Could not prepare the request.');
          return;
        }
      }

      success = true;
      try {
        rest.addQueryParam('continuation-token', nextToken);
      } on ChilkatException {
        success = false;
      }
      if (!success) {
        print('Could not prepare the request.');
        return;
      }

      more = true;
    }
  }

  print('Enumeration complete.');
}