or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-operations.mdclient-operations.mdcontainer-operations.mddatabase-operations.mdindex.mdscript-operations.mduser-management.md

index.mddocs/

0

# Azure Cosmos DB Client Library

1

2

Microsoft Azure Cosmos Client Library for Python provides access to Azure Cosmos DB, a globally distributed, multi-model NoSQL database service. This library enables developers to perform CRUD operations on JSON documents, manage databases and containers, execute queries with SQL-like syntax, and leverage advanced features like stored procedures, triggers, and batch operations.

3

4

## Package Information

5

6

- **Package Name**: azure-cosmos

7

- **Language**: Python

8

- **Installation**: `pip install azure-cosmos`

9

- **Requires**: Python 3.8+

10

11

## Core Imports

12

13

```python

14

from azure.cosmos import CosmosClient, ConsistencyLevel, PartitionKey

15

```

16

17

For async operations:

18

19

```python

20

from azure.cosmos.aio import CosmosClient

21

```

22

23

Common data types and configuration:

24

25

```python

26

from azure.cosmos import (

27

ThroughputProperties,

28

DatabaseAccount,

29

ProxyConfiguration,

30

SSLConfiguration

31

)

32

```

33

34

## Basic Usage

35

36

```python

37

from azure.cosmos import CosmosClient, ConsistencyLevel, PartitionKey

38

39

# Initialize client with account endpoint and key

40

client = CosmosClient(

41

url="https://your-account.documents.azure.com:443/",

42

credential="your-account-key",

43

consistency_level=ConsistencyLevel.Session

44

)

45

46

# Get or create database

47

database = client.create_database_if_not_exists(id="ToDoDatabase")

48

49

# Get or create container

50

container = database.create_container_if_not_exists(

51

id="ToDoContainer",

52

partition_key=PartitionKey(path="/category"),

53

offer_throughput=400

54

)

55

56

# Create an item

57

item = {

58

"id": "item1",

59

"category": "personal",

60

"description": "Grocery shopping",

61

"isComplete": False

62

}

63

container.create_item(body=item)

64

65

# Query items

66

items = list(container.query_items(

67

query="SELECT * FROM c WHERE c.category = @category",

68

parameters=[{"name": "@category", "value": "personal"}],

69

enable_cross_partition_query=True

70

))

71

72

# Read a specific item

73

item = container.read_item(item="item1", partition_key="personal")

74

75

# Update an item

76

item["isComplete"] = True

77

container.replace_item(item=item["id"], body=item)

78

79

# Delete an item

80

container.delete_item(item="item1", partition_key="personal")

81

```

82

83

## Architecture

84

85

Azure Cosmos DB client follows a hierarchical structure:

86

87

- **CosmosClient**: Top-level client managing account-level operations and authentication

88

- **DatabaseProxy**: Interface for database operations, container management, and user management

89

- **ContainerProxy**: Interface for item operations, queries, batch operations, and conflict resolution

90

- **UserProxy**: Interface for user and permission management

91

- **ScriptsProxy**: Interface for stored procedures, triggers, and user-defined functions

92

93

Both synchronous and asynchronous versions are available, with the async API providing the same functionality with coroutine-based methods.

94

95

## Capabilities

96

97

### Client Operations

98

99

Account-level operations including database management, authentication, and client configuration. Provides entry points to all Azure Cosmos DB functionality.

100

101

```python { .api }

102

class CosmosClient:

103

def __init__(self, url: str, credential: str, consistency_level: ConsistencyLevel = None, **kwargs): ...

104

def create_database(self, id: str, populate_query_metrics: bool = None, offer_throughput: int = None, **kwargs): ...

105

def get_database_client(self, database: str) -> DatabaseProxy: ...

106

def list_databases(self, max_item_count: int = None, populate_query_metrics: bool = None, **kwargs): ...

107

def get_database_account(**kwargs) -> DatabaseAccount: ...

108

```

109

110

[Client Operations](./client-operations.md)

111

112

### Database Operations

113

114

Database-level operations including container management, user management, and throughput configuration. Provides access to all resources within a database.

115

116

```python { .api }

117

class DatabaseProxy:

118

def read(self, populate_query_metrics: bool = None, **kwargs): ...

119

def create_container(self, id: str, partition_key: PartitionKey, indexing_policy: dict = None, default_ttl: int = None, **kwargs): ...

120

def get_container_client(self, container: str) -> ContainerProxy: ...

121

def list_containers(self, max_item_count: int = None, populate_query_metrics: bool = None, **kwargs): ...

122

def get_throughput(**kwargs) -> ThroughputProperties: ...

123

```

124

125

[Database Operations](./database-operations.md)

126

127

### Container Operations

128

129

Container-level operations including item CRUD operations, querying, batch operations, change feed processing, and conflict resolution.

130

131

```python { .api }

132

class ContainerProxy:

133

def create_item(self, body: dict, populate_query_metrics: bool = None, pre_trigger_include: str = None, post_trigger_include: str = None, **kwargs): ...

134

def read_item(self, item: str, partition_key: str, populate_query_metrics: bool = None, **kwargs): ...

135

def query_items(self, query: str = None, parameters: list = None, partition_key: str = None, enable_cross_partition_query: bool = None, **kwargs): ...

136

def execute_item_batch(self, batch_operations: list, partition_key: str, **kwargs): ...

137

def query_items_change_feed(**kwargs): ...

138

```

139

140

[Container Operations](./container-operations.md)

141

142

### Script Operations

143

144

Stored procedures, triggers, and user-defined functions management. Enables server-side logic execution and advanced data processing scenarios.

145

146

```python { .api }

147

class ScriptsProxy:

148

def create_stored_procedure(self, body: dict, **kwargs): ...

149

def execute_stored_procedure(self, sproc: str, partition_key: str = None, params: list = None, enable_script_logging: bool = None, **kwargs): ...

150

def create_trigger(self, body: dict, **kwargs): ...

151

def create_user_defined_function(self, body: dict, **kwargs): ...

152

```

153

154

[Script Operations](./script-operations.md)

155

156

### User and Permission Management

157

158

User management and permission-based access control for fine-grained security in multi-tenant applications.

159

160

```python { .api }

161

class UserProxy:

162

def read(**kwargs): ...

163

def create_permission(self, body: dict, **kwargs): ...

164

def list_permissions(self, max_item_count: int = None, **kwargs): ...

165

def get_permission(self, permission: str, **kwargs): ...

166

```

167

168

[User Management](./user-management.md)

169

170

### Async Operations

171

172

Asynchronous versions of all client operations for high-performance, non-blocking applications. All async classes mirror their synchronous counterparts.

173

174

```python { .api }

175

class CosmosClient: # async version

176

async def create_database(self, id: str, **kwargs): ...

177

async def close(self): ...

178

```

179

180

[Async Operations](./async-operations.md)

181

182

## Configuration and Data Types

183

184

### Core Configuration Types

185

186

```python { .api }

187

class PartitionKey(dict):

188

def __init__(self, path: Union[str, List[str]], kind: str = "Hash", version: int = 2): ...

189

# Supports both single path: PartitionKey(path="/category")

190

# And multiple paths: PartitionKey(path=["/category", "/id"], kind="MultiHash")

191

192

class ThroughputProperties:

193

offer_throughput: Optional[int]

194

auto_scale_max_throughput: Optional[int]

195

auto_scale_increment_percent: Optional[int]

196

properties: Optional[Dict[str, Any]]

197

instant_maximum_throughput: Optional[int]

198

soft_allowed_maximum_throughput: Optional[int]

199

200

class ProxyConfiguration:

201

Host: str

202

Port: int

203

Username: str

204

Password: str

205

206

class SSLConfiguration:

207

SSLKeyFile: str

208

SSLCertFile: str

209

SSLCaCerts: str

210

```

211

212

### Consistency Levels

213

214

```python { .api }

215

class ConsistencyLevel:

216

Strong: str

217

BoundedStaleness: str

218

Session: str

219

Eventual: str

220

ConsistentPrefix: str

221

```

222

223

### Response Types

224

225

```python { .api }

226

class CosmosDict(dict):

227

def get_response_headers(self) -> dict: ...

228

229

class CosmosList(list):

230

def get_response_headers(self) -> dict: ...

231

```

232

233

### Index and Data Types

234

235

```python { .api }

236

class IndexKind:

237

Hash: str

238

Range: str

239

MultiHash: str

240

241

class IndexingMode:

242

Consistent: str

243

NoIndex: str

244

245

class DataType:

246

Number: str

247

String: str

248

Point: str

249

LineString: str

250

Polygon: str

251

MultiPolygon: str

252

```

253

254

### Permissions and Triggers

255

256

```python { .api }

257

class PermissionMode:

258

Read: str

259

All: str

260

261

class TriggerType:

262

Pre: str

263

Post: str

264

265

class TriggerOperation:

266

All: str

267

Create: str

268

Update: str

269

Delete: str

270

Replace: str

271

```

272

273

### Priority and Advanced Types

274

275

```python { .api }

276

class Priority:

277

High: str

278

Low: str

279

280

class CosmosBatchOperationError(Exception):

281

"""Exception raised when batch operations fail."""

282

pass

283

284

class CosmosResourceExistsError(Exception):

285

"""Exception raised when trying to create a resource that already exists."""

286

pass

287

288

class CosmosResourceNotFoundError(Exception):

289

"""Exception raised when trying to access a resource that doesn't exist."""

290

pass

291

292

class CosmosAccessConditionFailedError(Exception):

293

"""Exception raised when conditional operations fail."""

294

pass

295

```