Todos os produtos
Search
Central de documentação

Object Storage Service:Listar buckets

Última atualização: Jul 03, 2026

Os buckets são listados em ordem alfabética. Gerenciar muitos buckets manualmente é ineficiente e propenso a erros. Use a operação ListBuckets para recuperar programaticamente uma lista de todos ou de alguns buckets da sua conta. Isso permite automatizar tarefas como inventário de ativos, operações em massa e auditorias de permissões.

Como funciona

Os parâmetros de solicitação e a paginação controlam o comportamento da operação ListBuckets.

Parâmetros de solicitação

Use os seguintes parâmetros de solicitação para filtrar e controlar os resultados.

Parâmetro

Descrição

prefix

Filtrar por prefixo: Restringe a resposta aos buckets cujos nomes começam com o prefixo especificado.

marker

Token de paginação: Especifica a posição inicial da lista. A resposta inclui os buckets que seguem o marker em ordem alfabética.

max-keys

Número de itens por página: Defina a quantidade máxima de buckets retornados em uma única resposta. O valor deve ser um número inteiro entre 1 e 1.000. O valor padrão é 100.

Paginação

Uma operação de listagem básica retorna apenas uma página de dados por padrão. Se o número de buckets exceder o limite por página, determinado pelo parâmetro max-keys, use a paginação para recuperar a lista completa.

Dois campos principais na resposta ativam a paginação:

  • isTruncated (Boolean): Quando este valor é true, indica que há mais páginas de dados disponíveis.

  • nextMarker (string): Token de paginação para a próxima página de resultados.

A lógica central da paginação funciona da seguinte forma: Para paginar, verifique a flag isTruncated. Se for true, use o valor de nextMarker da resposta como parâmetro marker na próxima solicitação. Repita esse processo até que isTruncated retorne false.

Alguns SDKs, como Python v2, Go v2, PHP v2 e C# v2, fornecem um Paginator que gerencia automaticamente esse loop. Para outros SDKs, implemente essa lógica manualmente.

Listar todos os buckets

Esta é a operação de listagem mais básica.

Console

  1. Faça logon no console do OSS.

  2. No painel de navegação à esquerda, clique em Buckets.

    Por padrão, a página Buckets exibe todos os buckets da sua conta. Para obter rapidamente o número de buckets e suas propriedades, clique em Export to CSV download no canto superior direito.

ossutil

Use a ferramenta de linha de comando ossutil para listar buckets. Para obter informações sobre como instalar o ossutil, consulte Instalar ossutil.

O comando a seguir lista todos os seus buckets.

ossutil api list-buckets

Para obter mais informações sobre este comando, consulte list-buckets (get-service).

SDK

As seções a seguir apresentam exemplos de código para SDKs comuns. Para outros SDKs, consulte Visão geral do SDK.

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; // Alias the OSS SDK namespace for brevity.

var region = "cn-hangzhou"; // Required. The region where your buckets are located.
var endpoint = null as string;  // Optional. Override the default endpoint (e.g., https://oss-cn-hangzhou.aliyuncs.com).

// Load default SDK configuration, then set credentials from environment variables.
var cfg = OSS.Configuration.LoadDefault();
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
cfg.Region = region;
if (endpoint != null)
{
    cfg.Endpoint = endpoint;
}

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

// Create a paginator to iterate through all buckets across pages.
var paginator = client.ListBucketsPaginator(new OSS.Models.ListBucketsRequest());

Console.WriteLine("Buckets:");
await foreach (var page in paginator.IterPageAsync())
{
    foreach (var bucket in page.Buckets ?? [])
    {
        // Output: bucket 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Android).

// 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

Após fazer logon no ossbrowser 2.0, clique em All no painel de navegação à esquerda para exibir todos os buckets da sua conta. Para obter mais informações sobre como instalar e fazer logon no ossbrowser 2.0, consulte Instalar ossbrowser 2.0 e Fazer logon no ossbrowser 2.0.

API

As operações anteriores usam chamadas de API. Caso sua aplicação tenha requisitos específicos de personalização, envie diretamente solicitações REST API. Para isso, escreva manualmente o código para calcular a assinatura. Para obter mais informações, consulte ListBuckets (GetService).

Listar buckets com um prefixo especificado

Defina o parâmetro prefix para filtrar no lado do servidor. Essa ação retorna apenas os buckets cujos nomes correspondem ao prefixo especificado.

ossutil

Liste todos os buckets de sua propriedade que possuem o prefixo example.

ossutil api list-buckets --prefix example

Para obter mais informações, consulte list-buckets (get-service).

SDK

Java

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Java 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Python 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Go 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Node.js).

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

Harmony

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Harmony).

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

Ruby

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Ruby).

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

Listar buckets após uma posição especificada

Configure o parâmetro marker para definir onde iniciar a lista. Este é o passo fundamental para implementar a paginação manual.

ossutil

Liste todos os buckets de sua propriedade que vêm depois de examplebucket.

ossutil api list-buckets --marker examplebucket

Para obter mais informações, consulte list-buckets (get-service).

SDK

Java

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Java 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Python 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Go 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Harmony).

// 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Node.js).

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

Android

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Android).

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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para iOS).

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];

Listar buckets em um grupo de recursos especificado

Liste os buckets pertencentes a um grupo de recursos específico.

ossutil

Liste todos os buckets de sua propriedade que estão no grupo de recursos com o ID rg-123.

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

Para obter mais informações, consulte list-buckets (get-service).

SDK

Java

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Java 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Python 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Go 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para PHP V2).

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

Controlar o número de itens por solicitação

Defina o parâmetro max-keys para limitar a quantidade de buckets retornados por solicitação e definir o tamanho da página.

ossutil

Limite o retorno desta chamada a no máximo 100 buckets.

ossutil api list-buckets --max-keys 100

Para obter mais informações, consulte list-buckets (get-service).

SDK

Java

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Java 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Python 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Go 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Node.js).

// 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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para Android).

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

Para obter o código de exemplo completo, consulte Listar buckets (SDK para iOS).

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];

Limitações

Não é possível usar um endpoint de Transfer Acceleration para listar buckets. O serviço Transfer Acceleration resolve apenas nomes de domínio de terceiro nível que incluem o nome do bucket (por exemplo, https://BucketName.oss-accelerate.aliyuncs.com), enquanto a operação de listagem de buckets usa um endpoint raiz que não contém o nome do bucket (por exemplo, https://oss-cn-hangzhou.aliyuncs.com).