List blob containers with Python

When you list the containers in an Azure Storage account from your code, you can specify several options to manage how results are returned from Azure Storage. This article shows how to list containers using the Azure Storage client library for Python.

To learn about listing blob containers using asynchronous APIs, see List containers asynchronously.

Prerequisites

  • This article assumes you already have a project set up to work with the Azure Blob Storage client library for Python. To learn about setting up your project, including package installation, adding import statements, and creating an authorized client object, see Get started with Azure Blob Storage and Python.
  • The authorization mechanism must have permissions to list blob containers. To learn more, see the authorization guidance for the following REST API operation:

About container listing options

When listing containers from your code, you can specify options to manage how results are returned from Azure Storage. You can specify the number of results to return in each set of results, and then retrieve the subsequent sets. You can also filter the results by a prefix, and return container metadata with the results. These options are described in the following sections.

To list containers in a storage account, call the following method:

This method returns an iterable of type ContainerProperties. Containers are ordered lexicographically by name.

Manage how many results are returned

By default, a listing operation returns up to 5000 results at a time. To return a smaller set of results, provide a nonzero value for the results_per_page keyword argument.

Filter results with a prefix

To filter the list of containers, specify a string or character for the name_starts_with keyword argument. The prefix string can include one or more characters. Azure Storage then returns only the containers whose names start with that prefix.

Include container metadata

To include container metadata with the results, set the include_metadata keyword argument to True. Azure Storage includes metadata with each container returned, so you don't need to fetch the container metadata separately.

Include deleted containers

To include soft-deleted containers with the results, set the include_deleted keyword argument to True.

Code examples

The following example lists all containers and metadata. You can include container metadata by setting include_metadata to True:

def list_containers(self, blob_service_client: BlobServiceClient):
    containers = blob_service_client.list_containers(include_metadata=True)
    for container in containers:
        print(container['name'], container['metadata'])

The following example lists only containers that begin with a prefix specified in the name_starts_with parameter:

def list_containers_prefix(self, blob_service_client: BlobServiceClient):
    containers = blob_service_client.list_containers(name_starts_with='test-')
    for container in containers:
        print(container['name'])

You can also specify a limit for the number of results per page. This example passes in results_per_page and paginates the results:

def list_containers_pages(self, blob_service_client: BlobServiceClient):
    i=0
    all_pages = blob_service_client.list_containers(results_per_page=5).by_page()
    for container_page in all_pages:
        i += 1
        print(f"Page {i}")
        for container in container_page:
            print(container['name'])

List containers asynchronously

The Azure Blob Storage client library for Python supports listing containers asynchronously. To learn more about project setup requirements, see Asynchronous programming.

Follow these steps to list containers using asynchronous APIs:

  1. Add the following import statements:

    import asyncio
    
    from azure.identity.aio import DefaultAzureCredential
    from azure.storage.blob.aio import BlobServiceClient
    
  2. Add code to run the program using asyncio.run. This function runs the passed coroutine, main() in our example, and manages the asyncio event loop. Coroutines are declared with the async/await syntax. In this example, the main() coroutine first creates the top level BlobServiceClient using async with, then calls the method that lists the containers. Note that only the top level client needs to use async with, as other clients created from it share the same connection pool.

    async def main():
        sample = ContainerSamples()
    
        # TODO: Replace <storage-account-name> with your actual storage account name
        account_url = "https://<storage-account-name>.blob.core.windows.net"
        credential = DefaultAzureCredential()
    
        async with BlobServiceClient(account_url, credential=credential) as blob_service_client:
            await sample.list_containers(blob_service_client)
    
    if __name__ == '__main__':
        asyncio.run(main())
    
  3. Add code to list the containers. The code is the same as the synchronous example, except that the method is declared with the async keyword and async for is used when calling the list_containers method.

    async def list_containers(self, blob_service_client: BlobServiceClient):
        async for container in blob_service_client.list_containers(include_metadata=True):
            print(container['name'], container['metadata'])
    

With this basic setup in place, you can implement other examples in this article as coroutines using async/await syntax.

Resources

To learn more about listing containers using the Azure Blob Storage client library for Python, see the following resources.

REST API operations

The Azure SDK for Python contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar Python paradigms. The client library methods for listing containers use the following REST API operation:

Code samples

Client library resources

See also