How to Use Azure CosmosDB Management API SDK for Python

Azure provides an excellent portal for managing various cloud resources. If you are working with CosmosDB database accounts, you will be familiar with the powerful interface available in Azure portal. Sometimes you may need to access some of the CosmosDB management features programatically. If you plan to build something on the command line, you can use either Azure CLI interface or the Azure PowerShell interface to access CosmosDB management features.

However, sometimes you may want direct programmatic access from your preferred programming language. Good news is that Azure API SDKs are available for common languages such as Python, .NET, Java and JavaScript. In the following section I will show you how to use powerful Azure management APIs using the Azure SDK for Python. For this example I will be specifically using the CosmosDB management API to list CosmosDB accounts and print connection strings (access keys) for one of the database accounts.

How to List CosmosDB Accounts in an Azure Subscription Using Azure Management API for Python

The following code snippet assumes that you already have Azure CLI setup so that the user credentials is available through the AzureCliCredential class. See this page for other methods of providing user credentials/service principal for API access. If you get the error "SubscriptionNotFound", check the subscription id used in the code and that you have logged into the subscription using Azure CLI.

# This program will list all the CosmosDB database accounts under a subscription.
# Uses Azure Management API for Python
# Also assumes Azure CLI is installed and configured with user authorization. Hence this code doesn't expose Azure user id and password.

from azure.mgmt.cosmosdb import CosmosDBManagementClient
from azure.identity import AzureCliCredential
import re

# Replace the following variable with your subscription id
subscription_id = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX'

# Connect to CosmosDB management API
cosmosdb_mgmt_client = CosmosDBManagementClient(AzureCliCredential(),subscription_id)

# Query the list of CosmosDB accounts under the subscription specified above
cosmosdb_accounts = cosmosdb_mgmt_client.database_accounts.list()

# For each account, let us print account name, id, access endpoint. Please note that the object has lot more attributes available.
for db_account in cosmosdb_accounts:
    print(f"Name={db_account.name},Id={db_account.id},Endpoint={db_account.document_endpoint}")

# There are additional APIs that can be used to get more specific details of CosmosDB cosmosdb_accounts

How to List Connection Strings for a CosmosDB Account Using Azure CosmosDB SDK for Python

The following code snippet assumes that you already have Azure CLI setup so that the user credentials is available through the AzureCliCredential class. If you get the error "SubscriptionNotFound", check the subscription id used in the code and that you have logged into the subscription using Azure CLI.

# This program will list all the CosmosDB database accounts under a subscription.
# Uses Azure Management API for Python
# Also assumes Azure CLI is installed and configured with user authorization. Hence this code doesn't expose Azure user id and password.

from azure.mgmt.cosmosdb import CosmosDBManagementClient
from azure.identity import AzureCliCredential
import re

# Replace the following variable with your subscription id
subscription_id = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX'

# Connect to CosmosDB management API
cosmosdb_mgmt_client = CosmosDBManagementClient(AzureCliCredential(),subscription_id)


# The following code snippet shows how to print connection strings with access keys of an account

# Let us get the first account from the accounts list
first_account = next(cosmosdb_mgmt_client.database_accounts.list())
account_id = first_account.id
account_name = first_account.name

# Extract resource group name for the CosmosDB account since the next API needs resource group
resource_group = re.search('resourceGroups/(.*)/providers', account_id).group(1)


# Call API to list connection strings. Note that the API returns an object
cs_list_obj = cosmosdb_mgmt_client.database_accounts.list_connection_strings(
       f"{resource_group}",
       f"{account_name}"
   )

# This lists all 4 keys of CosmosDB accounts
# This includes primary read-write, secondary read-write, primary read only and secondary read only
for connection_string_obj in cs_list_obj.connection_strings:
    print(connection_string_obj.connection_string)

The CosmosDBManagementClient used above is quite powerful and can also be used for getting detailed metrics for CosmosDB accounts, databases or collections. This is useful if you plan to use your own solution for monitoring and alerting instead of the Azure's core services for the same. For one of my solutions I use this API to fetch Max RUs Per Second, Mongo Query Request Charge and Throttled Requests for a CosmosDB account provisioned for MongoDB API.

Additional References