All Products
Search
Document Center

Object Storage Service:List buckets

Last Updated:Mar 20, 2026

List all or a filtered subset of your buckets to support automated workflows such as asset inventories, bulk operations, and permission audits. Buckets are returned in alphabetical order.

How it works

The list buckets operation accepts request parameters to filter and paginate results.

Request parameters

ParameterDescriptionDefault
prefixReturn only buckets whose names begin with this string
markerReturn buckets that come after this value alphabetically. Use this to paginate manually or start from a specific position.
max-keysMaximum number of buckets per response. Valid values: 1–1000.100
resource-group-idReturn only buckets that belong to the specified resource group.

Pagination

Important

Always use pagination when listing buckets at scale. A single unpaginated request returns at most 1,000 buckets (the max-keys maximum). For accounts with more buckets than the max-keys limit, the response includes two fields:

  • isTruncated (Boolean): true means more pages are available.

  • nextMarker (string): pass this as marker in your next request to retrieve the next page.

Repeat until isTruncated is false.

Note

Python v2, Go v2, PHP v2, and C# v2 SDKs include a built-in paginator that handles this loop automatically. For other SDKs, implement the loop manually.

List all buckets

Console

  1. Log on to the OSS console.

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

The Buckets page lists all buckets under your account. To export the list as a CSV file, click the export to CSV icon download in the upper-right corner.

ossbrowser

After logging on to ossbrowser 2.0, click All on the left to display all buckets in your account. For installation and login instructions, see Install ossbrowser 2.0 and Log on to ossbrowser 2.0.

image

ossutil

ossutil api list-buckets

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

SDK

The following examples list all buckets. Each example uses a paginator (where available) or a simple API call.

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 {
        // Endpoint for the China (Hangzhou) region
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String region = "cn-hangzhou";

        // Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        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 across all regions in 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("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("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

Python

import argparse
import alibabacloud_oss_v2 as oss

parser = argparse.ArgumentParser(description="list buckets sample")
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')

def main():
    args = parser.parse_args()

    # Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = args.region

    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    client = oss.Client(cfg)

    # The paginator handles the pagination loop automatically
    paginator = client.list_buckets_paginator()

    for page in paginator.iter_page(oss.ListBucketsRequest()):
        for o in page.buckets:
            print(f'Bucket: {o.name}, Location: {o.location}, Created: {o.creation_date}, Resource Group ID: {o.resource_group_id}')

if __name__ == "__main__":
    main()

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"
)

var region string

func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
}

func main() {
	flag.Parse()

	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	// The paginator handles the pagination loop automatically
	p := client.NewListBucketsPaginator(&oss.ListBucketsRequest{})

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

	for p.HasNext() {
		i++
		page, err := p.NextPage(context.TODO())
		if err != nil {
			log.Fatalf("failed to get page %v, %v", i, err)
		}
		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))
		}
	}
}

C#

using OSS = AlibabaCloud.OSS.V2;

var region = "cn-hangzhou";
var endpoint = null as string;

// Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET
var cfg = OSS.Configuration.LoadDefault();
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
cfg.Region = region;

if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

using var client = new OSS.Client(cfg);

// The paginator handles the pagination loop automatically
var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest());

Console.WriteLine("Buckets:");
await foreach (var page in paginator.IterPageAsync())
{
    foreach (var bucket in page.Buckets ?? [])
    {
        Console.WriteLine($"Bucket:{bucket.Name}, {bucket.StorageClass}, {bucket.Location}");
    }
}

Node.js

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

const client = new OSS({
  region: 'cn-hangzhou',
  // Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  bucket: 'examplebucket',
});

async function listBuckets() {
  try {
    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 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',
});

const listBuckets = async () => {
  try {
    const res = await client.listBuckets({});
    console.log(JSON.stringify(res));
  } catch (err) {
    if (err instanceof RequestError) {
      console.log('Error code: ', err.code);
      console.log('Error message: ', err.message);
      console.log('Request ID: ', err.requestId);
      console.log('HTTP status code: ', err.status);
      console.log('Error category: ', err.ec);
    } else {
      console.log('Unknown error: ', err);
    }
  }
};

listBuckets();

Ruby

require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)

buckets = client.list_buckets
buckets.each { |b| puts b.name }

Android

For the complete sample code, see List buckets.

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) {
        if (clientException != null) {
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            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)
{
    std::string Endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    std::string Region = "cn-hangzhou";

    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    // Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    ListBucketsRequest request;
    auto outcome = client.ListBuckets(request);

    if (outcome.isSuccess()) {
        std::cout << "success, bucket count is " << outcome.result().Buckets().size() << std::endl;
        for (auto result : outcome.result().Buckets())
        {
            std::cout << result.Name() << std::endl;
        }
    }
    else {
        std::cout << "ListBuckets fail"
            << ", code:" << outcome.error().Code()
            << ", message:" << outcome.error().Message()
            << ", requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    ShutdownSdk();
    return 0;
}

iOS

OSSGetServiceRequest *getService = [OSSGetServiceRequest new];
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;
}];

C

#include "oss_api.h"
#include "aos_http_io.h"

const char *endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
const char *region = "cn-hangzhou";

void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    aos_str_set(&options->config->endpoint, endpoint);
    // Load credentials from environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET
    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"));
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    options->config->is_cname = 0;
    options->ctl = aos_http_controller_create(options->pool, 0);
}

int main(int argc, char *argv[])
{
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }

    aos_pool_t *pool;
    aos_pool_create(&pool, NULL);

    oss_request_options_t *oss_client_options = oss_request_options_create(pool);
    init_options(oss_client_options);

    aos_table_t *resp_headers = NULL;
    aos_status_t *resp_status = NULL;
    oss_list_buckets_params_t *params = oss_create_list_buckets_params(pool);
    oss_list_bucket_content_t *content = NULL;
    int size = 0;

    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");
    }

    aos_list_for_each_entry(oss_list_bucket_content_t, content, &params->bucket_list, node) {
        printf("BucketName: %s\n", content->name.data);
        ++size;
    }

    aos_pool_destroy(pool);
    aos_http_io_deinitialize();
    return 0;
}

API

To send requests directly to the REST API without using an SDK, see ListBuckets (GetService).

List buckets with a specified prefix

Set prefix to return only buckets whose names start with the specified string.

ossutil

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).

ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
listBucketsRequest.setPrefix("example");
BucketList bucketList = ossClient.listBuckets(listBucketsRequest);

Python

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

for page in paginator.iter_page(oss.ListBucketsRequest(
    prefix='example'
)):
    # ... process page ...

Go

For the complete sample code, see List buckets.

request := &oss.ListBucketsRequest{
    Prefix: oss.Ptr("example"),
}
p := client.NewListBucketsPaginator(request)

Node.js

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

const result = await client.listBuckets({
  prefix: 'example'
});

Harmony

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

const res = await client.listBuckets({
  prefix: 'bucketNamePrefix'
});

Ruby

For the complete sample code, see List buckets.

buckets = client.list_buckets(:prefix => 'example')

List buckets after a specified position

Set marker to return only buckets that come after the specified value alphabetically. This is the key parameter for implementing manual pagination.

ossutil

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).

String nextMarker = "examplebucket";
BucketList bucketListing;

do {
    bucketListing = ossClient.listBuckets(new ListBucketsRequest()
            .withMarker(nextMarker)
            .withMaxKeys(200));
    nextMarker = bucketListing.getNextMarker();
} while (bucketListing.isTruncated());

Python

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

for page in paginator.iter_page(oss.ListBucketsRequest(
    marker="example-bucket"
)):
    # ... process page ...

Go

For the complete sample code, see List buckets.

request := &oss.ListBucketsRequest{
    Marker: oss.Ptr("example-bucket"),
}
p := client.NewListBucketsPaginator(request)

Harmony

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

let marker: string | undefined = "examplebucket";
let isTruncated = true;

while (isTruncated) {
  const res = await client.listBuckets({ marker });
  // ... process page ...
  marker = res.data.nextMarker;
  isTruncated = res.data.isTruncated;
}

Node.js

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

const result = await client.listBuckets({
  marker: 'examplebucket'
});

Android

For the complete sample code, see List buckets.

ListBucketsRequest request = new ListBucketsRequest();
request.setMarker("examplebucket");
ossClient.asyncListBuckets(request, ...);

iOS

For the complete sample code, see List buckets.

OSSGetServiceRequest *getService = [OSSGetServiceRequest new];
getService.marker = @"examplebucket";
OSSTask *getServiceTask = [client getService:getService];

List buckets in a specified resource group

Set resource-group-id to return only buckets that belong to the specified resource group.

ossutil

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).

ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
listBucketsRequest.setResourceGroupId("rg-aek27tc****");
BucketList bucketList = ossClient.listBuckets(listBucketsRequest);

Python

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

for page in paginator.iter_page(oss.ListBucketsRequest(
    resource_group_id="rg-aek27tc********"
)):
    # ... process page ...

Go

For the complete sample code, see List buckets.

request := &oss.ListBucketsRequest{
    ResourceGroupId: oss.Ptr("rg-aek27tc********"),
}
p := client.NewListBucketsPaginator(request)

PHP

For the complete sample code, see List buckets.

$iter = $paginator->iterPage(new Oss\Models\ListBucketsRequest(
    resourceGroupId: "rg-aekzfalvmw2sxby"
));

Control the number of results per page

Set max-keys to control how many buckets are returned per request. Valid values: 1–1000. Default: 100.

ossutil

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).

ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
listBucketsRequest.setMaxKeys(500);
BucketList bucketList = ossClient.listBuckets(listBucketsRequest);

Python

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

# The paginator retrieves up to 10 buckets per request
for page in paginator.iter_page(oss.ListBucketsRequest(
    max_keys=10
)):
    # ... process page ...

Go

For the complete sample code, see List buckets.

// The paginator retrieves up to 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).

const result = await client.listBuckets({
  'max-keys': 500
});

Android

For the complete sample code, see List buckets.

ListBucketsRequest request = new ListBucketsRequest();
request.setMaxKeys(500);
ossClient.asyncListBuckets(request, ...);

iOS

For the complete sample code, see List buckets.

OSSGetServiceRequest *getService = [OSSGetServiceRequest new];
getService.maxKeys = 500;
OSSTask *getServiceTask = [client getService:getService];

Limitations

Transfer Acceleration endpoints cannot be used to list buckets. Transfer Acceleration resolves only third-level domain names that include a bucket name (for example, https://BucketName.oss-accelerate.aliyuncs.com), while the list buckets operation requires a root endpoint without a bucket name (for example, https://oss-cn-hangzhou.aliyuncs.com).