Azure Cosmos DB (NoSQL API) Client Library

raw JSON →
4.5.1 verified Tue May 12 auth: no python install: verified

The `azure-cosmos` library is the official Python client for interacting with Azure Cosmos DB's NoSQL API. It allows developers to manage databases, containers, and items (JSON documents) in a globally distributed, multi-model database service. The library provides capabilities for creating, reading, updating, deleting, and querying data. The `azure-cosmosdb-nspkg` (version 2.0.2 provided in the prompt) is an internal namespace package for older Azure SDKs and is not intended for direct use; the modern client library is `azure-cosmos`. As of its latest stable release, it continues to receive active development and features.

pip install azure-cosmos azure-identity
error ModuleNotFoundError: No module named 'azure.cosmos'
cause The 'azure-cosmos' package is not installed in the Python environment.
fix
Install the package using pip: 'pip install azure-cosmos'.
error The input content is invalid because the required properties - 'id;' - are missing
cause The JSON document being sent to Azure Cosmos DB lacks the required 'id' property.
fix
Ensure that each document includes an 'id' property with a string value.
error Partition key ... is invalid
cause The partition key value provided is of an invalid type.
fix
Ensure the partition key value is either a string or a number.
error Response status code does not indicate success: BadRequest (400); Substatus: 1001
cause The partition key value provided does not match the value in the document's body.
fix
Provide a partition key value that matches the corresponding property value in the document.
error Response status code does not indicate success: Forbidden (403); Substatus: 1014
cause A partition key has reached its maximum storage size limit.
fix
Redesign the partitioning strategy to distribute data more evenly across partitions.
deprecated The `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.
fix Always install the specific client library (e.g., `azure-cosmos`) directly. Do not explicitly install `azure-cosmosdb-nspkg`.
breaking Older 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`.
fix Migrate applications using `pydocumentdb` to `azure-cosmos`. Migrate applications using `azure-cosmosdb-table` to `azure-data-tables` for the Table API.
gotcha Creating 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.
fix Utilize a single, shared `CosmosClient` instance (singleton pattern) across your application to manage connections efficiently.
gotcha Applications 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.
fix For 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).
gotcha When 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.
fix Always 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`.
breaking The `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.
fix Ensure that the `AZURE_COSMOS_ENDPOINT` and `AZURE_COSMOS_KEY` environment variables are correctly set, or pass the endpoint and key directly when initializing `CosmosClient`.
python os / libc status wheel install import disk mem side effects
3.10 alpine (musl) - - 0.60s 26.6M 12.1M -
3.10 alpine (musl) wheel - 0.59s 45.5M 12.1M clean
3.10 alpine (musl) - - 0.68s 44.3M 12.1M -
3.10 slim (glibc) - - 0.39s 27M 12.1M -
3.10 slim (glibc) wheel 3.8s 0.41s 46M 12.1M clean
3.10 slim (glibc) - - 0.42s 45M 12.1M -
3.11 alpine (musl) - - 0.82s 29.4M 14.1M -
3.11 alpine (musl) wheel - 0.75s 49.3M 14.1M clean
3.11 alpine (musl) - - 0.88s 48.1M 14.1M -
3.11 slim (glibc) - - 0.62s 30M 14.1M -
3.11 slim (glibc) wheel 3.7s 0.66s 50M 14.1M clean
3.11 slim (glibc) - - 0.69s 48M 14.1M -
3.12 alpine (musl) - - 0.95s 21.1M 14.0M -
3.12 alpine (musl) wheel - 0.96s 40.7M 14.0M clean
3.12 alpine (musl) - - 1.05s 39.6M 14.0M -
3.12 slim (glibc) - - 0.89s 22M 14.0M -
3.12 slim (glibc) wheel 3.2s 0.87s 41M 14.0M clean
3.12 slim (glibc) - - 1.02s 40M 14.0M -
3.13 alpine (musl) - - 0.93s 20.7M 14.7M -
3.13 alpine (musl) wheel - 0.90s 40.4M 14.7M clean
3.13 alpine (musl) - - 0.99s 39.1M 14.7M -
3.13 slim (glibc) - - 0.88s 21M 14.7M -
3.13 slim (glibc) wheel 3.3s 0.87s 41M 14.7M clean
3.13 slim (glibc) - - 1.00s 39M 14.7M -
3.9 alpine (musl) - - 0.56s 25.9M 12.1M -
3.9 alpine (musl) wheel - 0.58s 45.4M 12.1M clean
3.9 alpine (musl) - - 0.60s 44.3M 12.1M -
3.9 slim (glibc) - - 0.47s 26M 12.1M -
3.9 slim (glibc) wheel 4.5s 0.51s 46M 12.1M clean
3.9 slim (glibc) - - 0.55s 45M 12.1M -

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