Get started with Azure Cosmos DB for NoSQL using Python

APPLIES TO: NoSQL

This article shows you how to connect to Azure Cosmos DB for NoSQL using the Python SDK. Once connected, you can perform operations on databases, containers, and items.

Package (PyPi) | Samples | API reference | Library source code | Give Feedback

Prerequisites

Set up your project

Create an environment that you can run Python code in.

With a virtual environment, you can install Python packages in an isolated environment without affecting the rest of your system.

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

pip install azure-cosmos

Create the Python application

In your environment, create a new app.py file and add the following code to it:

"""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 that you'll use in the rest of the article.

Connect to Azure Cosmos DB for NoSQL

To connect to the API for NoSQL of Azure Cosmos DB, 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 will depend on where you host your application code. The table below serves as 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 contains core authentication functionality that is shared among 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 your application will run on Azure services with direct support for managed identities, obtain an OAuth token by creating a DefaultAzureCredential instance.

In your app.py:

  • Get the endpoint to connect to your account and set that 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 how to add the correct role to enable DefaultAzureCredential to work, 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 will primarily interact 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.

The following 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.

Each type of resource is represented by one or more associated Python classes. Here's a list of 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 is used to configure and execute requests against the service.
DatabaseProxy An interface to a database that may, or may not, exist in the service yet. This class shouldn't be instantiated directly. Instead you should 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.

The following guides show you how to use each of these classes to build your application.

Guide Description
Create a database Create databases
Create container Create containers
Item examples Point read a specific item

See also

Next steps