List buckets

更新时间:
复制 MD 格式

Buckets are listed in alphabetical order. Managing many buckets manually is inefficient and error-prone. Use the ListBuckets operation to programmatically retrieve a list of all or some buckets under your account. This enables automated tasks such as asset inventory, bulk operations, and permission audits.

How it works

Request parameters and pagination control the behavior of the ListBuckets operation.

Request parameters

Use the following request parameters to filter and control the results.

Parameter

Description

prefix

Filter by prefix: Restricts the response to buckets whose names begin with the specified prefix.

marker

Pagination token: Specifies the starting position for the list. The response includes buckets that alphabetically follow the marker.

max-keys

Number of items per page: Specifies the maximum number of buckets to return in a single response. The value must be an integer from 1 to 1,000. The default value is 100.

Pagination

A basic list operation returns only one page of data by default. If the number of buckets exceeds the per-page limit, which is determined by the max-keys parameter, you must use pagination to retrieve the complete list.

Two key fields in the response enable pagination:

  • isTruncated (Boolean): If this value is true, it indicates that more pages of data are available.

  • nextMarker (string): The pagination token for the next page of results.

The core logic for pagination is as follows: To paginate, check the isTruncated flag. If true, use the nextMarker value from the response as the marker parameter for your next request. Repeat this process until isTruncated returns false.

Some SDKs, such as Python v2, Go v2, PHP v2, and C# v2, provide a Paginator that automatically handles this loop. For other SDKs, you must implement this logic yourself.

List all buckets

This is the most basic list operation.

Console

  1. Log on to the OSS console.

  2. In the navigation pane on the left, click Buckets.

    By default, the Buckets page displays all buckets under your account. To quickly obtain the number of buckets and their properties, click the Export to CSV icon download in the upper-right corner.

ossutil

You can use the ossutil command-line tool to list buckets. For information about how to install ossutil, see Install ossutil.

The following command lists all your buckets.

ossutil api list-buckets

For more information about this command, see list-buckets (get-service).

SDK

The following sections provide sample code for common SDKs. For other SDKs, see SDK overview.

Java

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.Bucket;

import java.util.List;

public class Demo {

    public static void main(String[] args) throws Exception {
        // For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";
        
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // Create an OSS Client instance. 
        // Call the shutdown method to release associated resources when the OSS Client is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // List all buckets in all regions within the current Alibaba Cloud account. 
            List<Bucket> buckets = ossClient.listBuckets();
            for (Bucket bucket : buckets) {
                System.out.println(" - " + bucket.getName());
            }
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Python

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser and describe the purpose of the script: This sample demonstrates how to list all buckets in OSS.
parser = argparse.ArgumentParser(description="list buckets sample")

# Add the --region command-line argument, which specifies the region where the bucket is located. This is a required parameter.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --endpoint command-line argument, which specifies the domain names that other services can use to access OSS. This is an optional parameter.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    # Parse the parameters provided on the command line to obtain the user-input values.
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Create a configuration object using the default configurations of the SDK and set the authentication provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property in the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Initialize the OSS client using the preceding configurations to prepare for interaction with OSS.
    client = oss.Client(cfg)

    # Create a paginator for the ListBuckets operation to handle many buckets.
    paginator = client.list_buckets_paginator()

    # Traverse the paginated results.
    for page in paginator.iter_page(oss.ListBucketsRequest()):
        # For each bucket on each page, print its name, location, and creation date.
        for o in page.buckets:
            print(f'Bucket: {o.name}, Location: {o.location}, Created: {o.creation_date}')

# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script, from which the program flow starts.

Go

package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables
var (
	region string // The region where the bucket is stored
)

// The init function is used to initialize command line parameters
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
}

func main() {
	// Parse command line parameters
	flag.Parse()

	// Check whether the region is empty
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and set the credential provider and region
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client
	client := oss.NewClient(cfg)

	// Create a request to list buckets
	request := &oss.ListBucketsRequest{}

	// Create a paginator
	p := client.NewListBucketsPaginator(request)

	var i int
	log.Println("Buckets:")

	// Traverse each page in the paginator
	for p.HasNext() {
		i++

		// Obtain the data of the next page
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}

		// Print the information of each bucket on the page
		for _, b := range page.Buckets {
			log.Printf("Bucket: %v, StorageClass: %v, Location: %v\n", oss.ToString(b.Name), oss.ToString(b.StorageClass), oss.ToString(b.Location))
		}
	}

}

PHP

<?php

require_once __DIR__ . '/../vendor/autoload.php'; // Import the autoloader file to load dependency libraries.

use AlibabaCloud\Oss\V2 as Oss;

// Define the command line argument descriptions.
$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True], // The region must be specified. Example: oss-cn-hangzhou.
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False], // The endpoint parameter is optional. The endpoint that other services can use to access OSS.
];
$longopts = \array_map(function ($key) {
    return "$key:"; 
}, array_keys($optsdesc));

// Parse the command line arguments.
$options = getopt("", $longopts); 

// Check whether all required parameters have been configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // A message is displayed, indicating that a required parameter is missing.
        exit(1); 
    }
}

// Retrieve the values of the command line arguments.
$region = $options["region"]; // The region where the bucket is located.

// Load credentials (AccessKeyId and AccessKeySecret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider(); // Load credentials from environment variables.

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault(); // Load the default configurations of the SDK.
$cfg->setCredentialsProvider($credentialsProvider); // Set the credential provider.
$cfg->setRegion($region); // Set the region.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]); // Set the endpoint if one is provided.
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg); 

// Create a paginator for the ListBuckets operation.
$paginator = new Oss\Paginator\ListBucketsPaginator($client); // Create a paginator to list buckets.
$iter = $paginator->iterPage(new Oss\Models\ListBucketsRequest()); // Retrieve the pagination iterator.


// Traverse the paginated results.

foreach ($iter as $page) { // Traverse the list of buckets on each page.
    foreach ($page->buckets ?? [] as $bucket) { // Traverse each bucket on the current page.
        print ("Bucket: $bucket->name, $bucket->location\n"); // Print the bucket name and its region.
    }
}

C#

using OSS = AlibabaCloud.OSS.V2; // Create an alias for the Alibaba Cloud OSS SDK to simplify subsequent use.

var region = "cn-hangzhou"; // Required. Specify the region where the bucket is located. In this example, the China (Hangzhou) region is used. Set the region to cn-hangzhou.
var endpoint = null as string;  // Optional. Specify the domain name used to access the OSS service. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.

// Load the default configurations of the OSS SDK. The configurations automatically read credential information (such as AccessKey) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set the use of environment variables to obtain credentials for identity verification (format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET).
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket in the configuration.
cfg.Region = region;
// If an endpoint is specified, it overwrites the default endpoint.
if(endpoint != null)
{
    cfg.Endpoint = endpoint;
}

// Create an OSS client instance using the configuration information.
using var client = new OSS.Client(cfg);

// Create a paginator for the ListBuckets operation to process paged results.
// ListBucketsRequest is a request model defined by the SDK. In this example, the default constructor is used to obtain all buckets. 
var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest());

Console.WriteLine("Buckets:");
await foreach (var page in paginator.IterPageAsync())
{
// Traverse each bucket in the current page.
    foreach (var bucket in page.Buckets ?? [])
    {
    // Print bucket information: name, storage class, and location.
    Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}");
    }
}

Node.js

const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running this code, ensure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of your bucket.
  bucket: 'yourBucketName',
});

async function listBuckets() {
  try {
    // List all buckets in all regions within the current Alibaba Cloud account. 
    const result = await client.listBuckets();
    console.log(result);
  } catch (err) {
    console.log(err);
  }
}

listBuckets();

Harmony

import Client, { RequestError } from '@aliyun/oss';

// Create an OSS client instance.
const client = new Client({
  // Replace with the Access Key ID of the Security Token Service (STS) temporary access credential.
  accessKeyId: 'yourAccessKeyId',
  // Replace with the Access Key Secret of the STS temporary access credential.
  accessKeySecret: 'yourAccessKeySecret',
  // Replace with the Security Token of the STS temporary access credential.
  securityToken: 'yourSecurityToken',
});

// List all buckets.
const listBuckets = async () => {
  try {
    // Call the listBuckets method to list all buckets.
    const res = await client.listBuckets({});

    // Print the result.
    console.log(JSON.stringify(res));
  } catch (err) {
    // Catch and handle request errors.
    if (err instanceof RequestError) {
      console.log('Error code: ', err.code); // Error code
      console.log('Error message: ', err.message); // Error description
      console.log('Request ID: ', err.requestId); // Unique identifier of the request
      console.log('HTTP status code: ', err.status); // HTTP response status code
      console.log('Error category: ', err.ec); // Error category
    } else {
      console.log('Unknown error: ', err); // Error that is not of the RequestError type
    }
  }
};

// Call the function to list all buckets.
listBuckets();

Swift

import AlibabaCloudOSS
import Foundation

@main
struct Main {
    static func main() async {
        do {
            // Specify the region where the bucket is located. For example, set the region to cn-hangzhou for China (Hangzhou).
            let region = "cn-hangzhou"
            // Optional. Specify the domain name to access OSS. For example, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com for China (Hangzhou).
            let endpoint: String? = nil

            // Load credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET in advance.
            let credentialsProvider = EnvironmentCredentialsProvider()

            // Configure the OSS client parameters.
            let config = Configuration.default()
                .withRegion(region) // Set the region.
                .withCredentialsProvider(credentialsProvider) // Set the credentials.
                
            // Set the endpoint.
            if let endpoint = endpoint {
                config.withEndpoint(endpoint)
            }

            // Create an OSS client instance.
            let client = Client(config)

            // Create a paginator to traverse buckets.
            let paginator = client.listBucketsPaginator(ListBucketsRequest())

            // Traverse all buckets and print their information.
            for try await page in paginator {
                for bucket in page.buckets ?? [] {
                    print("Bucket name: \(bucket.name ?? ""), Storage class: \(bucket.storageClass ?? ""), Region: \(bucket.location ?? "")")
                }
            }

        } catch {
            // Catch and handle exceptions.
            print("error:\n\(error)")
        }
    }
}

Ruby

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # The China (Hangzhou) endpoint is used as an example. Replace it with the actual endpoint.
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before running this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# List all buckets across all regions in your account.
buckets = client.list_buckets
buckets.each { |b| puts b.name }

Android

For the complete sample code, see List buckets (Android SDK).

// List all buckets in all regions of your account.
ListBucketsRequest request = new ListBucketsRequest();
ossClient.asyncListBuckets(request, new OSSCompletedCallback<ListBucketsRequest, ListBucketsResult>() {
    @Override
    public void onSuccess(ListBucketsRequest request, ListBucketsResult result) {
        List<OSSBucketSummary> buckets = result.getBuckets();
        for (int i = 0; i < buckets.size(); i++) {
            Log.i("info", "name: " + buckets.get(i).name + " "
                    + "location: " + buckets.get(i).location);
        }
    }

    @Override
    public void onFailure(ListBucketsRequest request, ClientException clientException, ServiceException serviceException) {
        // The request failed.
        if (clientException != null) {
            // A client exception occurred, such as a network exception.
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // A server exception occurred.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});

C++

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize the OSS account information. */
    
    /* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* List all buckets under the current account. */
    ListBucketsRequest request;
    auto outcome = client.ListBuckets(request);

    if (outcome.isSuccess()) {
        /* Print bucket information. */
        std::cout <<" success, and bucket count is" << outcome.result().Buckets().size() << std::endl;
        std::cout << "Bucket name is" << std::endl;
        for (auto result : outcome.result().Buckets())
        {
            std::cout << result.Name() << std::endl;
        }
    }
    else {
        /* Handle the exception. */
        std::cout << "ListBuckets fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

iOS

OSSGetServiceRequest * getService = [OSSGetServiceRequest new];
// List all buckets in all regions within the current account.    
OSSTask * getServiceTask = [client getService:getService];
[getServiceTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        OSSGetServiceResult * result = task.result;
        NSLog(@"buckets: %@", result.buckets);
        NSLog(@"owner: %@, %@", result.ownerId, result.ownerDispName);
        [result.buckets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary * bucketInfo = obj;
            NSLog(@"BucketName: %@", [bucketInfo objectForKey:@"Name"]);
            NSLog(@"CreationDate: %@", [bucketInfo objectForKey:@"CreationDate"]);
            NSLog(@"Location: %@", [bucketInfo objectForKey:@"Location"]);
        }];
    } else {
        NSLog(@"get service failed, error: %@", task.error);
    }
    return nil;
}];
// Implement synchronous blocking to wait for the task to complete.
// [getServiceTask waitUntilFinished];

C

#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the endpoint of the region where the bucket is located. For example, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com for the China (Hangzhou) region. */
const char *endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, set the region to cn-hangzhou for the China (Hangzhou) region. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize the aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Configure the following two parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use a CNAME to access OSS. A value of 0 indicates that a CNAME is not used. */
    options->config->is_cname = 0;
    /* Set network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method at the program entry to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* The memory pool used for memory management. It is equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Create a memory pool. The second parameter is NULL, which indicates that the new memory pool does not inherit from another memory pool. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate memory to options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    oss_list_buckets_params_t *params = NULL;
    oss_list_bucket_content_t *content = NULL;
    int size = 0;
    params = oss_create_list_buckets_params(pool);
    /* List buckets. */
    resp_status = oss_list_bucket(oss_client_options, params, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("list buckets succeeded\n");
    } else {
        printf("list buckets failed\n");
    }
    /* Print the buckets. */
    aos_list_for_each_entry(oss_list_bucket_content_t, content, &params->bucket_list, node) {
        printf("BucketName: %s\n", content->name.data);
        ++size;
    }
    /* Release the memory pool. This releases the memory allocated to resources during the request. */
    aos_pool_destroy(pool);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

ossbrowser

After you log on to ossbrowser 2.0, click All in the navigation pane on the left to display all buckets under your account. For more information about how to install and log on to ossbrowser 2.0, see Install ossbrowser 2.0 and Log on to ossbrowser 2.0.

API

The preceding operations use API calls. If your application has specific customization requirements, you can directly send REST API requests. To do this, you must manually write code to calculate the signature. For more information, see ListBuckets (GetService).

List buckets with a specified prefix

Set the prefix parameter to perform server-side filtering. This returns only buckets whose names match the specified prefix.

ossutil

List all buckets that you own and that have the prefix example.

ossutil api list-buckets --prefix example

For more information, see list-buckets (get-service).

SDK

Java

For the complete sample code, see List buckets (Java SDK V1).

// 1. Create a request object.
ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
// 2. Set the prefix parameter.
listBucketsRequest.setPrefix("example");
// 3. Execute the request.
BucketList bucketList = ossClient.listBuckets(listBucketsRequest);

Python

For the complete sample code, see List buckets (Python SDK V2).

# Pass a request object with the prefix parameter to the iter_page method of the Paginator.
for page in paginator.iter_page(oss.ListBucketsRequest(
    prefix='example'
)):
    # ... process the loop ...

Go

For the complete sample code, see List buckets (Go SDK V2).

// 1. Create a request object and set the Prefix field.
request := &oss.ListBucketsRequest{
    Prefix: oss.Ptr("example"), 
}
// 2. Use the request object to create a Paginator.
p := client.NewListBucketsPaginator(request)

Node.js

For the complete sample code, see List buckets (Node.js SDK).

// Specify the prefix in the parameter object of the listBuckets method.
const result = await client.listBuckets({
  prefix: 'example' 
});

Harmony

For the complete sample code, see List buckets (Harmony SDK).

// Key code: Pass an object that contains the prefix when you call listBuckets.
const res = await client.listBuckets({
  prefix: 'bucketNamePrefix'
});

Ruby

For the complete sample code, see List buckets (Ruby SDK).

# Key code: Call list_buckets with :prefix as a parameter.
buckets = client.list_buckets(:prefix => 'example')

List buckets after a specified position

Set the marker parameter to specify where to start the list. This is the core step for implementing manual pagination.

ossutil

List all buckets that you own and that come after examplebucket.

ossutil api list-buckets --marker examplebucket

For more information, see list-buckets (get-service).

SDK

Java

For the complete sample code, see List buckets (Java SDK V1).

// 1. Set marker to "examplebucket" to list buckets that come after "examplebucket".
String nextMarker = "examplebucket"; 
BucketList bucketListing;
do {
    // 2. Initiate a request with the current marker.
    bucketListing = ossClient.listBuckets(new ListBucketsRequest()
            .withMarker(nextMarker)
            .withMaxKeys(200));
    // 3. Update the marker to obtain the next page.
    nextMarker = bucketListing.getNextMarker(); 
} while (bucketListing.isTruncated());

Python

For the complete sample code, see List buckets (Python SDK V2).

# Set marker to "example-bucket" to list buckets that come after "example-bucket".
for page in paginator.iter_page(oss.ListBucketsRequest(
    marker="example-bucket"
)):
    # ... iterate through the page ...

Go

For the complete sample code, see List buckets (Go SDK V2).

// Set marker to "example-bucket" to list buckets that come after "example-bucket".
request := &oss.ListBucketsRequest{
    Marker: oss.Ptr("example-bucket"), 
}
// Use the request to create a Paginator.
p := client.NewListBucketsPaginator(request)

Harmony

For the complete sample code, see List buckets (Harmony SDK).

// Set the initial value of marker to "examplebucket" to specify the starting point for the listing.
let marker: string | undefined = "examplebucket"; 
let isTruncated = true;
while (isTruncated) {
  // Use the current marker in the request.
  const res = await client.listBuckets({
    marker 
  });
  // ...
  // Update the marker for the next loop.
  marker = res.data.nextMarker; 
  isTruncated = res.data.isTruncated;
}

Node.js

For the complete sample code, see List buckets (Node.js SDK).

// Set marker to 'examplebucket' to list buckets that come after 'examplebucket'.
const result = await client.listBuckets({
  marker: 'examplebucket' 
});

Android

For the complete sample code, see List buckets (Android SDK).

ListBucketsRequest request = new ListBucketsRequest();
// Set marker to "examplebucket" to list buckets that come after "examplebucket".
request.setMarker("examplebucket");
ossClient.asyncListBuckets(request, ...);
#### **iOS (Objective-C)**
objectivec OSSGetServiceRequest * getService = [OSSGetServiceRequest new]; // Set marker to "examplebucket" to list buckets that come after "examplebucket". getService.marker = @"examplebucket"; OSSTask * getServiceTask = [client getService:getService];

iOS

For the complete sample code, see List buckets (iOS SDK).

OSSGetServiceRequest * getService = [OSSGetServiceRequest new];
// Set marker to "examplebucket" to list buckets that come after "examplebucket".
getService.marker = @"examplebucket";
// Use this request object to initiate an asynchronous task.
OSSTask * getServiceTask = [client getService:getService];

List buckets in a specified resource group

List buckets in a specified resource group.

ossutil

List all buckets that you own and that are in the resource group with the ID rg-123.

ossutil api list-buckets --resource-group-id rg-123

For more information, see list-buckets (get-service).

SDK

Java

For the complete sample code, see List buckets (Java SDK V1).

ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
// Key code: Set the ID of the resource group by which to filter.
listBucketsRequest.setResourceGroupId("rg-aek27tc****");
// Pass the configured request object to the listBuckets method.
BucketList bucketList = ossClient.listBuckets(listBucketsRequest);

Python

For the complete sample code, see List buckets (Python SDK V2).

# Key code: Construct a request in the iter_page method and specify resource_group_id.
for page in paginator.iter_page(oss.ListBucketsRequest(
    resource_group_id="rg-aek27tc********"
)):
    # ... iterate through the page ...

Go

For the complete sample code, see List buckets (Go SDK V2).

// Key code: Create a request and set the ResourceGroupId field.
request := &oss.ListBucketsRequest{
    ResourceGroupId: oss.Ptr("rg-aek27tc********"), 
}
// Use this request to create a Paginator.
p := client.NewListBucketsPaginator(request)

PHP

For the complete sample code, see List buckets (PHP SDK V2).

// Key code: Construct a request in the iterPage method and specify resourceGroupId.
$iter = $paginator->iterPage(new Oss\Models\ListBucketsRequest(
    resourceGroupId: "rg-aekzfalvmw2sxby"
));

Control the number of items per request

Set the max-keys parameter to limit the number of buckets returned per request, which defines the page size.

ossutil

Limit the number of buckets returned in this call to a maximum of 100.

ossutil api list-buckets --max-keys 100

For more information, see list-buckets (get-service).

SDK

Java

For the complete sample code, see List buckets (Java SDK V1).

ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
// Key code: Set the maxKeys parameter to 500 to limit the number of buckets returned in this call to a maximum of 500.
listBucketsRequest.setMaxKeys(500);
// Pass the configured request object to the method.
BucketList bucketList = ossClient.listBuckets(listBucketsRequest);

Python

For the complete sample code, see List buckets (Python SDK V2).

# Key code: Pass the max_keys parameter with a value of 10 when you create a ListBucketsRequest.
# This causes the Paginator to retrieve a maximum of 10 buckets per request.
for page in paginator.iter_page(oss.ListBucketsRequest(
    max_keys=10
)):
    # ... iterate through the page ...

Go

For the complete sample code, see List buckets (Go SDK V2).

// Key code: Set the MaxKeys field to 5 when you create a ListBucketsRequest.
// The Paginator uses this setting to retrieve a maximum of 5 buckets per request.
request := &oss.ListBucketsRequest{
    MaxKeys: 5,
}
p := client.NewListBucketsPaginator(request)

Node.js

For the complete sample code, see List buckets (Node.js SDK).

// Key code: Pass an object that contains the 'max-keys' property when you call listBuckets.
// 'max-keys' is set to 500 to limit the number of buckets returned in this call to a maximum of 500.
const result = await client.listBuckets({
  'max-keys': 500
});

Android

For the complete sample code, see List buckets (Android SDK).

ListBucketsRequest request = new ListBucketsRequest();
// Key code: Set the maxKeys parameter to 500 to limit the number of buckets returned in this asynchronous request to a maximum of 500.
request.setMaxKeys(500);
ossClient.asyncListBuckets(request, ...);

iOS

For the complete sample code, see List buckets (iOS SDK).

OSSGetServiceRequest * getService = [OSSGetServiceRequest new];
// Key code: Set the maxKeys property of the getService request object to 500.
getService.maxKeys = 500;
OSSTask * getServiceTask = [client getService:getService];

Limitations

You cannot use a Transfer Acceleration endpoint to list buckets. The Transfer Acceleration service resolves only third-level domain names that include a bucket name (for example, https://BucketName.oss-accelerate.aliyuncs.com), while the list buckets operation uses a root endpoint that does not contain a bucket name (for example, https://oss-cn-hangzhou.aliyuncs.com).