Microsoft Docs

Azure Cosmos DB SDK for Python

Welcome to the official documentation for the Azure Cosmos DB SDK for Python. This SDK allows you to interact with your Azure Cosmos DB accounts from your Python applications, enabling you to perform CRUD operations, query data, and manage your resources.

Getting Started

To begin using the SDK, you first need to install it via pip:

Installation
pip install azure-cosmos

Core Concepts

  • Client: The entry point for interacting with Cosmos DB.
  • Database: Represents a logical namespace for containers.
  • Container: The fundamental unit of scalability in Cosmos DB, storing items.
  • Item: A JSON document within a container.
  • Query: SQL-like queries to retrieve data from containers.

Connecting to Cosmos DB

You'll need your Cosmos DB endpoint and primary key. You can find these in the Azure portal under your Cosmos DB account's "Keys" section.

Python Connection Example
from azure.cosmos import CosmosClient

endpoint = "YOUR_COSMOS_DB_ENDPOINT"
key = "YOUR_COSMOS_DB_PRIMARY_KEY"

client = CosmosClient(endpoint, key)

Working with Containers

You can create, read, update, and delete containers. Here's how to get a reference to an existing container:

Get Container Reference
database_name = 'mydatabase'
container_name = 'mycontainer'

database = client.get_database_client(database_name)
container = database.get_container_client(container_name)

CRUD Operations

Create Item

Items are typically represented as Python dictionaries.

Create Item Example
item = {
    'id': 'item1',
    'name': 'sample item',
    'category': 'example',
    'tags': ['python', 'cosmosdb']
}

created_item = container.create_item(body=item)

Read Item

Read Item Example
read_item = container.read_item(item='item1', partition_key='item1') # If partition key is same as id

Query Items

Use SQL-like syntax for querying.

Query Example
query = "SELECT * FROM c WHERE c.category = 'example'" 

for item in container.query_items(query=query, enable_cross_partition_query=True):
    print(item)

Further Resources