Azure Cosmos DB Client Library for Python
The `azure-cosmos` library is the official Microsoft Azure Cosmos DB client library for Python. It provides a client-side logical representation to access Azure Cosmos DB for NoSQL accounts, enabling developers to manage databases, containers (collections of JSON documents), and items (individual JSON documents). It supports common operations like CRUD (Create, Read, Update, Delete) and SQL-like querying. The library is actively maintained, with the current stable version being 4.15.0, and receives regular updates and feature enhancements.
Warnings
- breaking Version 4.0.0 introduced significant breaking changes. Key class names were renamed (e.g., `DocumentClient` to `CosmosClient`, `Collection` to `Container`, `Document` to `Item`). Many `read_all` operations were renamed to `list` operations (e.g., `read_all_databases` to `list_databases`). The error hierarchy also changed, inheriting from `azure.core.AzureError` instead of `CosmosError`.
- breaking Python 2.x support has been dropped. Version 4.x and all future versions of `azure-cosmos` require Python 3.9 or later. Specifically, versions 4.5.2b4 and higher require Python 3.8+, and 4.15.0 and higher require Python 3.9+.
- gotcha When querying items by their `id` property, ensure that the `id` value passed in the query or read operations is always a string type. Azure Cosmos DB only allows string `id` values. Passing other data types will result in no results being returned and no error messages from the SDK, which can be difficult to debug.
- gotcha When using the Azure Cosmos DB Emulator for local development, its HTTPS certificate is self-signed. The Python SDK may fail to connect unless the emulator's certificate is properly imported into your system's trusted certificates.
- gotcha If running the `azure-cosmos` SDK from Azure Virtual Machines, you might encounter connection failures or timeouts due to Azure Source Network Address Translation (SNAT) port exhaustion. This typically happens with a high volume of outbound connections.
- deprecated The Azure Cosmos DB extension for Azure Functions (version 3.x) has been retired as of August 31, 2024. This impacts Azure Functions that use Cosmos DB bindings, as the underlying SDK changed to use the Cosmos DB V3 SDK. Migration to extension version 4.x involves breaking changes.
Install
-
pip install azure-cosmos
Imports
- CosmosClient
from azure.cosmos import CosmosClient
- PartitionKey
from azure.cosmos import PartitionKey
- exceptions
from azure.cosmos import exceptions
Quickstart
import os
from azure.cosmos import CosmosClient, PartitionKey, exceptions
# These environment variables must be set for the quickstart to run
# In Azure Portal, navigate to your Cosmos DB account -> Keys
# ACCOUNT_URI = "<your-cosmos-db-endpoint>"
# ACCOUNT_KEY = "<your-cosmos-db-primary-key>"
ACCOUNT_URI = os.environ.get('ACCOUNT_URI', 'https://localhost:8081') # Use emulator default if not set
ACCOUNT_KEY = os.environ.get('ACCOUNT_KEY', 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9ndKll+E/6DrURj/Dd/C04hZlwsEaLicensedy6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9ndKll+E/6DrURj/Dd/C04hZlwsEaLicensed==') # Use emulator default if not set
DATABASE_NAME = 'myDatabase'
CONTAINER_NAME = 'myContainer'
PARTITION_KEY_PATH = '/category'
def main():
if not ACCOUNT_URI or not ACCOUNT_KEY:
print("Please set the ACCOUNT_URI and ACCOUNT_KEY environment variables.")
print("You can find these in your Azure Cosmos DB account's 'Keys' section.")
print("For local emulator, ensure it's running and use default key.")
return
try:
# Initialize the Cosmos client
client = CosmosClient(ACCOUNT_URI, credential=ACCOUNT_KEY)
print("CosmosClient initialized.")
# Create a database if it doesn't exist
try:
database = client.create_database_if_not_exists(id=DATABASE_NAME)
print(f"Database '{DATABASE_NAME}' created or already exists.")
except exceptions.CosmosHttpResponseError as e:
print(f"Error creating/getting database: {e}")
return
# Create a container if it doesn't exist
try:
container = database.create_container_if_not_exists(
id=CONTAINER_NAME,
partition_key=PartitionKey(path=PARTITION_KEY_PATH),
offer_throughput=400 # Or specify autoscale settings
)
print(f"Container '{CONTAINER_NAME}' created or already exists with partition key '{PARTITION_KEY_PATH}'.")
except exceptions.CosmosHttpResponseError as e:
print(f"Error creating/getting container: {e}")
return
# Create an item
new_item = {
'id': 'item1',
'name': 'Laptop',
'category': 'Electronics',
'price': 1200.00
}
try:
created_item = container.upsert_item(body=new_item)
print(f"Item created/updated: {created_item['id']}")
except exceptions.CosmosHttpResponseError as e:
print(f"Error creating/updating item: {e}")
return
# Read an item
try:
read_item = container.read_item(item=new_item['id'], partition_key=new_item['category'])
print(f"Item read: {read_item['name']}, Price: {read_item['price']}")
except exceptions.CosmosHttpResponseError as e:
print(f"Error reading item: {e}")
return
# Query items
query = f"SELECT * FROM c WHERE c.category = '{new_item['category']}'"
items = list(container.query_items(query=query, enable_cross_partition_query=False))
print(f"Items found by query:")
for item in items:
print(f" - {item['name']}")
# Delete an item
try:
container.delete_item(item=new_item['id'], partition_key=new_item['category'])
print(f"Item '{new_item['id']}' deleted.")
except exceptions.CosmosHttpResponseError as e:
print(f"Error deleting item: {e}")
return
except Exception as ex:
print(f"An unexpected error occurred: {ex}")
if __name__ == '__main__':
main()