Install & Compatibility
Where this runs
tested against v4.16.3 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.794s · 46.5MB
glibcpy 3.10–3.95 runs
installs and imports cleanly · install 3.9s · import 0.700s · 47MB
46MB installed
● package 46MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
CosmosClient
✓ from azure.cosmos import CosmosClient
CosmosResourceNotFoundError
✓ from azure.cosmos.exceptions import CosmosResourceNotFoundError
✗ from azure.cosmos import CosmosResourceNotFoundError
Exceptions are located in the `azure.cosmos.exceptions` submodule.
This quickstart demonstrates how to initialize the `CosmosClient`, create a database and container (if they don't exist), create a new item, read an existing item, and query items within a container. Ensure you have `AZURE_COSMOS_ENDPOINT` and `AZURE_COSMOS_KEY` environment variables set to your Cosmos DB account's endpoint and primary key.
import os
from azure.cosmos import CosmosClient
# Retrieve Cosmos DB account details from environment variables
endpoint = os.environ.get('AZURE_COSMOS_ENDPOINT', 'YOUR_COSMOS_ENDPOINT')
key = os.environ.get('AZURE_COSMOS_KEY', 'YOUR_COSMOS_KEY')
# Ensure endpoint and key are not default placeholders
if 'YOUR_COSMOS_ENDPOINT' in endpoint or 'YOUR_COSMOS_KEY' in key:
print("Please set AZURE_COSMOS_ENDPOINT and AZURE_COSMOS_KEY environment variables.")
exit(1)
database_name = 'MyDatabase'
container_name = 'MyContainer'
client = CosmosClient(endpoint, key)
try:
# Create a database
database = client.create_database_if_not_exists(id=database_name)
print(f"Database '{database_name}' created or already exists.")
# Create a container with a partition key
container = database.create_container_if_not_exists(
id=container_name,
partition_key={'path': '/category', 'kind': 'Hash'}
)
print(f"Container '{container_name}' created or already exists.")
# Create an item
new_item = {"id": "item1", "name": "Sample Item", "category": "Electronics", "price": 100}
item = container.create_item(body=new_item)
print(f"Item created with id: {item['id']}")
# Read an item
read_item = container.read_item(item=item['id'], partition_key=item['category'])
print(f"Item read: {read_item['name']}")
# Query items
query = "SELECT * FROM c WHERE c.category = 'Electronics'"
items = list(container.query_items(query=query, enable_cross_partition_query=True))
print(f"Found {len(items)} item(s) in category 'Electronics'.")
finally:
# Clean up (optional): delete database and its contents
# client.delete_database(database.id)
# print(f"Database '{database_name}' deleted.")
pass
Debug
Known issues
deprecatedThe `azure-cosmosdb-nspkg` library (and other `*-nspkg` packages like `azure-nspkg`) is an internal namespace package and should NOT be installed directly by end-users. It served to consolidate sub-packages under a common `azure` namespace in older Python versions. Modern Azure SDKs use PEP 420 for namespace packages, making explicit `nspkg` packages unnecessary. Installing it directly can lead to dependency conflicts.fixAlways install the specific client library (e.g., `azure-cosmos`) directly. Do not explicitly install `azure-cosmosdb-nspkg`.
affects: <=2.0.2 for azure-cosmosdb-nspkg
breakingOlder Cosmos DB SDKs for Python (e.g., `pydocumentdb` and `azure-cosmosdb-table`) are deprecated. The `pydocumentdb` package's support ended on March 31, 2023, and `azure-cosmosdb-table` was replaced by `azure-data-tables`.fixMigrate applications using `pydocumentdb` to `azure-cosmos`. Migrate applications using `azure-cosmosdb-table` to `azure-data-tables` for the Table API.
affects: All versions of `pydocumentdb` (<=2.3.5) and `azure-cosmosdb-table`.
gotchaCreating multiple `CosmosClient` instances in an application can lead to socket exhaustion and connectivity issues due to excessive resource allocation. It is a common misstep in client-side code.fixUtilize a single, shared `CosmosClient` instance (singleton pattern) across your application to manage connections efficiently.
affects: All versions
gotchaApplications may encounter HTTP 429 (Too Many Requests) errors, indicating that the provisioned request units (RU/s) for a database or container have been exceeded, or `NoNodeAvailableException` / `ClosedConnectionException` for intermittent connectivity issues.fixFor 429 errors, consider scaling up the throughput of your Cosmos DB resources or implement retry logic in your application. For connection issues, ensure client machines have sufficient resources, consider adjusting Azure Load Balancer idle timeout, and set driver-level keep-alive settings if applicable (e.g., for Cassandra API, but generally good practice for long-lived connections).
affects: All versions
gotchaWhen querying items with `query_items`, ensure to specify the `partition_key` or set `enable_cross_partition_query=True` for queries that span multiple logical partitions. Failing to do so will result in an error if the query cannot be routed to a single partition.fixAlways provide the `partition_key` in `read_item`, `replace_item`, `delete_item`, and in `query_items` if the query targets a specific partition. For queries that may cross partitions, set `enable_cross_partition_query=True`.
affects: All versions
breakingThe `azure-cosmos` client library requires authentication credentials (endpoint and key) to connect to Azure Cosmos DB. These are typically provided via environment variables (`AZURE_COSMOS_ENDPOINT`, `AZURE_COSMOS_KEY`), direct arguments to `CosmosClient`, or a configuration file. Failing to provide them will prevent any operations with the database.fixEnsure that the `AZURE_COSMOS_ENDPOINT` and `AZURE_COSMOS_KEY` environment variables are correctly set, or pass the endpoint and key directly when initializing `CosmosClient`.
affects: All versions
Upgrade
Version history
4.16.3latest on PyPI · released Jul 29, 2026
Audit
Dependencies
azure-identityrequiredRecommended for Azure Active Directory authentication, providing various credential types.