Connecting and Querying with the Cosmos DB Python SDK
This lesson explains keyless connections with data plane roles, item operations, queries and paging, and optimistic concurrency.
Learning outcomes
After completing this lesson, you will be able to:
- Explain how Cosmos DB data plane roles are assigned.
- Distinguish point reads from queries.
- Describe parameterized, single-partition and cross-partition queries.
- Explain optimistic concurrency with ETags.
Authentication and data plane roles
Cosmos DB accepts two kinds of credential on its data plane. Account keys grant full access to all data and are shared secrets. Microsoft Entra ID with Cosmos DB's own role-based access control is the secure choice: the application authenticates with DefaultAzureCredential, and a data plane role assignment decides what it may do. Local (key) authentication can then be disabled on the account.
Data plane roles are separate from ordinary Azure roles. The built-in Cosmos DB Built-in Data Reader allows reads and queries, and Cosmos DB Built-in Data Contributor allows reads and writes of items. They are assigned with az cosmosdb sql role assignment create, scoped to the account, a database or a container. Data plane roles do not include management operations such as creating databases and containers, which are done through Azure Resource Manager with the Azure CLI, Bicep or the portal.
PRINCIPAL=$(az ad signed-in-user show --query id -o tsv)
az cosmosdb sql role assignment create --resource-group RG --account-name ACCOUNT \
--role-definition-name "Cosmos DB Built-in Data Contributor" \
--principal-id $PRINCIPAL --scope "/"Data plane access
Clients and item operations
The SDK's entry point is CosmosClient. A client is expensive to create because it discovers the account's regions and partitions, and it is thread-safe, so an application creates one client at start-up and reuses it for every request. From the client, get_database_client and get_container_client return lightweight proxies.
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential
client = CosmosClient("https://ACCOUNT.documents.azure.com:443/", credential=DefaultAzureCredential())
container = client.get_database_client("retail").get_container_client("orders")
container.upsert_item({"id": "o-1001", "customerId": "c-42", "status": "new", "total": 129.5})
order = container.read_item(item="o-1001", partition_key="c-42")
container.patch_item(item="o-1001", partition_key="c-42",
patch_operations=[{"op": "replace", "path": "/status", "value": "shipped"}])
container.delete_item(item="o-1001", partition_key="c-42")create_item fails if the item exists, upsert_item creates or replaces, replace_item requires the item to exist, and patch_item changes individual properties without sending the whole document, which saves bandwidth and avoids overwriting concurrent changes to other properties. Errors are raised as CosmosHttpResponseError, with subclasses such as CosmosResourceNotFoundError for HTTP 404. An asynchronous client in azure.cosmos.aio suits asynchronous web frameworks.
The following diagram compares a slow, expensive Cosmos DB profile lookup with the corrected one.

Item operations
Running queries
query_items runs a query in the NoSQL query language. Values are passed as parameters, which avoids injection and lets the service cache query plans. Supplying partition_key makes the query a single-partition query; without it, a query that spans partitions must set enable_cross_partition_query=True.
query = ("SELECT c.id, c.total, c.status FROM c "
"WHERE c.customerId = @cid AND c.total > @min ORDER BY c._ts DESC")
items = container.query_items(
query=query,
parameters=[{"name": "@cid", "value": "c-42"}, {"name": "@min", "value": 50}],
partition_key="c-42",
max_item_count=20)
for page in items.by_page():
for order in page:
print(order["id"], order["total"])
break # only the first page in this example
print(container.client_connection.last_response_headers["x-ms-request-charge"])Results arrive in pages; max_item_count sets the page size, and by_page() returns an iterator of pages whose continuation token lets an API return the next page in a later request. Projecting only the needed properties (SELECT c.id, c.total rather than SELECT *) lowers RU charges for large items. A point read with read_item is always cheaper than a query for the same item.
An expensive query
Optimistic concurrency
Two processes that read an item, change it and write it back can overwrite each other's changes. Cosmos DB prevents this with optimistic concurrency: every item has an _etag that changes on every write, and a write can be made conditional on the ETag still matching. If another process wrote first, the condition fails with HTTP 412 Precondition Failed, and the application reads the item again and retries its change.
from azure.core import MatchConditions
from azure.cosmos.exceptions import CosmosHttpResponseError
order = container.read_item(item="o-1002", partition_key="c-42")
order["status"] = "cancelled"
try:
container.replace_item(item=order, body=order,
etag=order["_etag"], match_condition=MatchConditions.IfNotModified)
except CosmosHttpResponseError as err:
if err.status_code == 412:
print("Changed by someone else; read again and retry")For changes that must update several items atomically, a transactional batch runs up to 100 operations on items in the same logical partition as one all-or-nothing unit.
Concurrent updates
A slow and expensive lookup
An API loads a customer's profile with SELECT * FROM c WHERE c.id = @id and enable_cross_partition_query=True. The container's partition key is /customerId, and the profile's id equals the customer ID. Each call costs about 30 RUs and latency is high under load. The API creates a new CosmosClient for every request.
Two changes fix both problems. Because the id and partition key are known, the API should use a point read, read_item(item=cid, partition_key=cid), which costs about 1 RU for a small item instead of a cross-partition query. And the API should create one CosmosClient at start-up and reuse it, because creating a client per request repeats metadata discovery and connection set-up.
Adding an index on id would not help, since id is already indexed and the cost comes from fanning out. Raising the container's throughput would hide the throttling but not reduce the per-call cost. Switching to Strong consistency would increase read cost.
An application authenticates to Cosmos DB with a data plane role and fails when it calls create_container_if_not_exists. Why?
Show answer
Data plane roles do not include management operations such as creating databases and containers. Containers are created through Azure Resource Manager, for example with the Azure CLI or Bicep.
Exam Tips
Remember for the exam
- Use DefaultAzureCredential with Cosmos DB data plane roles assigned through az cosmosdb sql role assignment.
- Data plane roles cannot create databases or containers; use Azure Resource Manager for that.
- Create one CosmosClient and reuse it; prefer point reads to queries.
- ETag with IfNotModified gives optimistic concurrency; a conflict returns 412.