A bucket is a container that stores objects in OSS. Every object is contained in a bucket. This topic describes how to list all buckets or buckets whose names contain a specified prefix.

List all buckets

The following code provides an example on how to list all buckets:

# -*- coding: utf-8 -*-
import oss2

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
service = oss2.Service(auth, 'http://oss-cn-hangzhou.aliyuncs.com')

# List all buckets.
for b in oss2.BucketIterator(service):
    print(b.name)

For more information about how to list buckets, see GetBucket (ListObjects).

List buckets whose names contain a specified prefix

The following code provides an example on how to list buckets whose names contain a specified prefix:

# -*- coding: utf-8 -*-
import oss2

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
service = oss2.Service(auth, 'http://oss-cn-hangzhou.aliyuncs.com')

# List buckets whose names contain the test- prefix.
for b in oss2.BucketIterator(service, prefix='test-'):
    print(b.name)

List buckets whose names are alphabetically greater than a specified marker.

The marker parameter specifies the name of the bucket after which the list begins. The following code provides an example on how to list buckets that follow a specified marker:

# -*- coding: utf-8 -*-
import oss2

# Security risks may arise if you use the AccessKey pair of an Alibaba Cloud account to log on to OSS because the account has permissions on all API operations. We recommend that you use your RAM user's credentials to call API operations or perform routine operations and maintenance. To create a RAM user, log on to the RAM console.
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# The endpoint of the China (Hangzhou) region is used in this example. Specify the actual endpoint.
service = oss2.Service(auth, 'http://oss-cn-hangzhou.aliyuncs.com')

# List the buckets whose names are alphabetically greater than test-bucket1. The test-bucket1 bucket is not listed.
for b in oss2.BucketIterator(service, marker='test-bucket1'):
    print(b.name)