Create a container in Azure Cosmos DB for NoSQL using Python

APPLIES TO: NoSQL

Containers in Azure Cosmos DB store sets of items. Before you can create, query, or manage items, you must first create a container.

Name a container

In Azure Cosmos DB, a container is analogous to a table in a relational database. When you create a container, the container name forms a segment of the URI used to access the container resource and any child items.

Once created, the URI for a container is in this format:

https://<cosmos-account-name>.documents.azure.cn/dbs/<database-name>/colls/<container-name>

Create a container

To create a container, call one of the following methods:

Create a container

The following example creates a container with the DatabaseProxy.create_container method. This method throws an exception if the container with the same name already exists.

"""Sample showing how to connect with endpoint and key."""
import os

from azure.cosmos import CosmosClient, PartitionKey
from azure.cosmos.exceptions import (
    CosmosHttpResponseError,
    CosmosResourceExistsError,
)

DATABASE_ID = "cosmicworks-1"
CONTAINER_ID = "products"
ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]

client = CosmosClient(url=ENDPOINT, credential=KEY)


def main():
    """How to CosmosDB and NoSQL samples."""
    try:
        database = client.create_database_if_not_exists(id=DATABASE_ID)

        # <create_container>
        try:
            partition_key_path = PartitionKey(path="/categoryId")
            container = database.create_container(
                id=CONTAINER_ID,
                partition_key=partition_key_path,
                offer_throughput=400,
            )
            print(f"Container created: {container.id}")

        except CosmosResourceExistsError:
            print("Container already exists.")
        # </create_container>

    except CosmosHttpResponseError:
        print("Request to the Azure Cosmos database service failed.")


if __name__ == "__main__":
    main()

Create a container if it doesn't already exist

The following example creates a container with the DatabaseProxy.create_container_if_not_exists method. Compared to the previous create method, this method doesn't throw an exception if the database already exists. This method is useful for avoiding errors if you run the same code multiple times.

"""Sample showing how to connect with endpoint and key."""
import os

from azure.cosmos import CosmosClient, PartitionKey
from azure.cosmos.exceptions import CosmosHttpResponseError

DATABASE_ID = "cosmicworks-3"
CONTAINER_ID = "products"
ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]

client = CosmosClient(url=ENDPOINT, credential=KEY)


def main():
    """How to CosmosDB and NoSQL samples."""
    try:
        database = client.create_database_if_not_exists(id=DATABASE_ID)

        # <create_container>
        try:
            partition_key_path = PartitionKey(path="/categoryId")
            container = database.create_container_if_not_exists(
                id=CONTAINER_ID,
                partition_key=partition_key_path,
                offer_throughput=400,
            )
            print(f"Container created or returned: {container.id}")

        except CosmosHttpResponseError:
            print("Request to the Azure Cosmos database service failed.")
        # </create_container>

        try:
            # <parse_response>
            partition_key_path = PartitionKey(path="/categoryId")
            container = database.create_container_if_not_exists(
                id=CONTAINER_ID,
                partition_key=partition_key_path,
                offer_throughput=400,
            )
            for doc in container.read_all_items(max_item_count=10):
                print(f'Doc id: {doc["id"]}')
            # </parse_response>

        except CosmosHttpResponseError:
            print("Request to the Azure Cosmos database service failed.")

    except CosmosHttpResponseError:
        print("Request to the Azure Cosmos database service failed.")


if __name__ == "__main__":
    main()

Create a container asynchronously

You can also create a database asynchronously using similar object and methods in the azure.cosmos.aio namespace. For example, use the DatabaseProxy.create_database method or the CosmoClient.create_database_if_not_exists method.

Working asynchronously is useful when you want to perform multiple operations in parallel. For more information, see Using the asynchronous client.

Parsing the response

In the examples above, the response from the requests is a ContainerProxy, which is an interface to interact with a DB Container. From the proxy, you can access methods to perform operations on the container.

The following example shows the create_container_if_not_exists method returning a container object.

"""Sample showing how to connect with endpoint and key."""
import os

from azure.cosmos import CosmosClient, PartitionKey
from azure.cosmos.exceptions import CosmosHttpResponseError

DATABASE_ID = "cosmicworks-3"
CONTAINER_ID = "products"
ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]

client = CosmosClient(url=ENDPOINT, credential=KEY)


def main():
    """How to CosmosDB and NoSQL samples."""
    try:
        database = client.create_database_if_not_exists(id=DATABASE_ID)

        # <create_container>
        try:
            partition_key_path = PartitionKey(path="/categoryId")
            container = database.create_container_if_not_exists(
                id=CONTAINER_ID,
                partition_key=partition_key_path,
                offer_throughput=400,
            )
            print(f"Container created or returned: {container.id}")

        except CosmosHttpResponseError:
            print("Request to the Azure Cosmos database service failed.")
        # </create_container>

        try:
            # <parse_response>
            partition_key_path = PartitionKey(path="/categoryId")
            container = database.create_container_if_not_exists(
                id=CONTAINER_ID,
                partition_key=partition_key_path,
                offer_throughput=400,
            )
            for doc in container.read_all_items(max_item_count=10):
                print(f'Doc id: {doc["id"]}')
            # </parse_response>

        except CosmosHttpResponseError:
            print("Request to the Azure Cosmos database service failed.")

    except CosmosHttpResponseError:
        print("Request to the Azure Cosmos database service failed.")


if __name__ == "__main__":
    main()

Next steps

Now that you've create a container, use the next guide to create items.