Get started with Azure Cosmos DB for NoSQL using Python

This article explains how to connect to Azure Cosmos DB for NoSQL using the Python SDK. After connecting, perform operations on databases, containers, and items.

Package (PyPi) | API reference | Library source code | Give feedback

Prerequisites

Set up your project

Create an environment for the Python code.

Use a virtual environment to install Python packages in isolation without affecting your system.

Install the Azure Cosmos DB for NoSQL Python SDK in your virtual environment.

pip install azure-cosmos

Create the Python application

In your environment, create a new app.py file and add this code:

"""Sample showing how to connect with endpoint and key."""
# <imports>
import json
import os
import sys
import uuid

from azure.core.exceptions import AzureError
from azure.cosmos import CosmosClient, PartitionKey

# </imports>

DATABASE_ID = "cosmicworks"
CONTAINER_ID = "products"
# <client>
ENDPOINT = os.environ["COSMOS_ENDPOINT"]
KEY = os.environ["COSMOS_KEY"]

client = CosmosClient(url=ENDPOINT, credential=KEY)
# </client>


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

        # Create a container.
        partition_key_path = PartitionKey(path="/categoryId")
        container = database.create_container_if_not_exists(
            id=CONTAINER_ID,
            partition_key=partition_key_path,
            offer_throughput=400,
        )

        # Create a new item.
        new_guid = str(uuid.uuid4())
        new_item = {
            "id": new_guid,
            "categoryId": "61dba35b-4f02-45c5-b648-c6badc0cbd79",
            "categoryName": "gear-surf-surfboards",
            "name": "Yamba Surfboard",
            "quantity": 12,
            "sale": False,
        }
        container.create_item(new_item)

        # Query items.
        sql_stmt = "SELECT * FROM products p WHERE p.categoryId = @categoryId"
        category_id = "61dba35b-4f02-45c5-b648-c6badc0cbd79"
        params = [dict(name="@categoryId", value=category_id)]

        items = container.query_items(
            query=sql_stmt,
            parameters=params,
            enable_cross_partition_query=False,
        )

        for item in items:
            print(json.dumps(item, indent=True))

    except AzureError as err:
        sys.exit("Error:" + str(err))


if __name__ == "__main__":
    main()

The preceding code imports modules used in the rest of the article.

Connect to Azure Cosmos DB for NoSQL

To connect to the Azure Cosmos DB API for NoSQL, create an instance of the CosmosClient class. This class is the starting point to perform all operations against databases.

To connect to your API for NoSQL account using Microsoft Entra, use a security principal. The exact type of principal depends on where you host your application code. The following table is a quick reference guide.

Where the application runs Security principal
Local machine (developing and testing) User identity or service principal
Azure Managed identity
Servers or clients outside of Azure Service principal

Import Azure.Identity

The azure-identity package provides core authentication functionality shared across all Azure SDK libraries.

Import the azure-identity package into your environment.

pip install azure-identity

Create CosmosClient with default credential implementation

If you're testing on a local machine or running your application on Azure services with managed identity support, obtain an OAuth token by creating a DefaultAzureCredential instance.

In your app.py file:

  • Get the endpoint for your account and set it as the environment variable COSMOS_ENDPOINT.

  • Import the DefaultAzureCredential and create an instance of it.

  • Create a new instance of the CosmosClient class with the ENDPOINT and credential as parameters.

"""Sample showing how to connect with AAD."""
import json
import os
import sys
import uuid

from azure.core.exceptions import AzureError
from azure.cosmos import CosmosClient

# <credential>
from azure.identity import DefaultAzureCredential

ENDPOINT = os.environ["COSMOS_ENDPOINT"]

credential = DefaultAzureCredential()

client = CosmosClient(ENDPOINT, credential)
# </credential>

DATABASE_ID = "cosmicworks"
CONTAINER_ID = "products"


def main():
    """How to CosmosDB and NoSQL samples."""
    try:
        # Get database.
        database = client.get_database_client(DATABASE_ID)

        # Get container.
        container = database.get_container_client(CONTAINER_ID)
        print("Container info: " + str(container.read()))

        # Create a new item.
        new_guid = str(uuid.uuid4())
        new_item = {
            "id": new_guid,
            "categoryId": "61dba35b-4f02-45c5-b648-c6badc0cbd79",
            "categoryName": "gear-surf-surfboards",
            "name": "Yamba Surfboard",
            "quantity": 12,
            "sale": False,
        }
        container.create_item(new_item)

        # Query items.
        sql_stmt = "SELECT * FROM products p WHERE p.categoryId = @categoryId"
        category_id = "61dba35b-4f02-45c5-b648-c6badc0cbd79"
        params = [dict(name="@categoryId", value=category_id)]

        items = container.query_items(
            query=sql_stmt,
            parameters=params,
            enable_cross_partition_query=False,
        )

        for item in items:
            print(json.dumps(item, indent=True))

    except AzureError as err:
        sys.exit("Error:" + str(err))


if __name__ == "__main__":
    main()

Important

For details on adding the correct role to enable DefaultAzureCredential, see Configure role-based access control with Microsoft Entra ID for your Azure Cosmos DB account. In particular, see the section on creating roles and assigning them to a principal ID.

Build your application

As you build your application, your code primarily interacts with four types of resources:

  • The API for NoSQL account, which is the unique top-level namespace for your Azure Cosmos DB data.

  • Databases, which organize the containers in your account.

  • Containers, which contain a set of individual items in your database.

  • Items, which represent a JSON document in your container.

This diagram shows the relationship between these resources.

Diagram of the Azure Cosmos DB hierarchy including accounts, databases, containers, and items.

Hierarchical diagram showing an Azure Cosmos DB account at the top. The account has two child database nodes. One of the database nodes includes two child container nodes. The other database node includes a single child container node. That single container node has three child item nodes.

One or more associated Python classes represents type of resource. This list shows the most common classes for synchronous programming. (There are similar classes for asynchronous programming under the azure.cosmos.aio namespace.)

Class Description
CosmosClient This class provides a client-side logical representation for the Azure Cosmos DB service. The client object configures and executes requests against the service.
DatabaseProxy An interface to a database that could, or couldn't, exist in the service yet. This class shouldn't be instantiated directly. Instead, use the CosmosClient get_database_client method.
ContainerProxy An interface to interact with a specific Cosmos DB container. This class shouldn't be instantiated directly. Instead, use the DatabaseProxy get_container_client method to get an existing container, or the create_container method to create a new container.

These guides show how to use each of these classes to build your application.

Guide Description
Create a database Create a database.
Create container Create a container.

See also

Next steps