CosmosClient Class

A client-side logical representation of an Azure Cosmos DB account.

Use this client to configure and execute requests to the Azure Cosmos DB service.

Inheritance
builtins.object
CosmosClient

Constructor

CosmosClient(url: str, credential: Any, consistency_level: str = 'Session', **kwargs: Any)

Parameters

url
str
Required

The URL of the Cosmos DB account.

credential
str or dict[str, str]
Required

Can be the account key, or a dictionary of resource tokens.

consistency_level
str
default value: Session

Consistency level to use for the session. The default value is "Session".

timeout
int

An absolute timeout in seconds, for the combined HTTP request and response processing.

request_timeout
int

The HTTP request timeout in seconds.

connection_mode
str

The connection mode for the client - currently only supports 'Gateway'.

proxy_config
ProxyConfiguration

Connection proxy configuration.

ssl_config
SSLConfiguration

Connection SSL configuration.

connection_verify
bool

Whether to verify the connection, default value is True.

connection_cert
str

An alternative certificate to verify the connection.

retry_total
int

Maximum retry attempts.

retry_backoff_max
int

Maximum retry wait time in seconds.

retry_fixed_interval
int

Fixed retry interval in milliseconds.

retry_read
int

Maximum number of socket read retry attempts.

retry_connect
int

Maximum number of connection error retry attempts.

retry_status
int

Maximum number of retry attempts on error status codes.

retry_on_status_codes
list[int]

A list of specific status codes to retry on.

retry_backoff_factor
float

Factor to calculate wait time between retry attempts.

enable_endpoint_discovery
bool

Enable endpoint discovery for geo-replicated database accounts. (Default: True)

preferred_locations
list[str]

The preferred locations for geo-replicated database accounts.

Examples

Create a new instance of the Cosmos DB client:


   from azure.cosmos import exceptions, CosmosClient, PartitionKey

   import os

   url = os.environ["ACCOUNT_URI"]
   key = os.environ["ACCOUNT_KEY"]
   client = CosmosClient(url, key)

Methods

create_database

Create a new database with the given ID (name).

create_database_if_not_exists

Create the database if it does not exist already.

If the database already exists, the existing settings are returned.

..note:: This function does not check or update existing database settings or offer throughput if they differ from what is passed in.

delete_database

Delete the database with the given ID (name).

from_connection_string

Create a CosmosClient instance from a connection string.

This can be retrieved from the Azure portal.For full list of optional keyword arguments, see the CosmosClient constructor.

get_database_account

Retrieve the database account information.

get_database_client

Retrieve an existing database with the ID (name) id.

list_databases

List the databases in a Cosmos DB SQL database account.

query_databases

Query the databases in a Cosmos DB SQL database account.

create_database

Create a new database with the given ID (name).

create_database(id: str, populate_query_metrics: Optional[bool] = None, offer_throughput: Optional[int] = None, **kwargs: Any) -> azure.cosmos.database.DatabaseProxy

Parameters

id
Required

ID (name) of the database to create.

populate_query_metrics
bool
Required

Enable returning query metrics in response headers.

offer_throughput
int
Required

The provisioned throughput for this offer.

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

Initial headers to be sent as part of the request.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition
MatchConditions

The match condition to use upon the etag.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

A DatabaseProxy instance representing the new database.

Return type

Exceptions

Database with the given ID already exists.

Examples

Create a database in the Cosmos DB account:


   database_name = "testDatabase"
   try:
       database = client.create_database(id=database_name)
   except exceptions.CosmosResourceExistsError:
       database = client.get_database_client(database=database_name)

create_database_if_not_exists

Create the database if it does not exist already.

If the database already exists, the existing settings are returned.

..note:: This function does not check or update existing database settings or offer throughput if they differ from what is passed in.

create_database_if_not_exists(id: str, populate_query_metrics: Optional[bool] = None, offer_throughput: Optional[int] = None, **kwargs: Any) -> azure.cosmos.database.DatabaseProxy

Parameters

id
Required

ID (name) of the database to read or create.

populate_query_metrics
bool
Required

Enable returning query metrics in response headers.

offer_throughput
int
Required

The provisioned throughput for this offer.

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

Initial headers to be sent as part of the request.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition
MatchConditions

The match condition to use upon the etag.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

A DatabaseProxy instance representing the database.

Return type

Exceptions

The database read or creation failed.

delete_database

Delete the database with the given ID (name).

delete_database(database: Union[str, azure.cosmos.database.DatabaseProxy, Dict[str, Any]], populate_query_metrics: Optional[bool] = None, **kwargs: Any) -> None

Parameters

database
str or dict(str, str) or DatabaseProxy
Required

The ID (name), dict representing the properties or <xref:azure.cosmos.cosmos_client.DatabaseProxy> instance of the database to delete.

populate_query_metrics
bool
Required

Enable returning query metrics in response headers.

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

Initial headers to be sent as part of the request.

etag
str

An ETag value, or the wildcard character (*). Used to check if the resource has changed, and act according to the condition specified by the match_condition parameter.

match_condition
MatchConditions

The match condition to use upon the etag.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Return type

Exceptions

If the database couldn't be deleted.

from_connection_string

Create a CosmosClient instance from a connection string.

This can be retrieved from the Azure portal.For full list of optional keyword arguments, see the CosmosClient constructor.

from_connection_string(conn_str: str, credential: Optional[Any] = None, consistency_level: str = 'Session', **kwargs: Any) -> azure.cosmos.cosmos_client.CosmosClient

Parameters

conn_str
str
Required

The connection string.

credential
str or dict(str, str)
Required

Alternative credentials to use instead of the key provided in the connection string.

consistency_level
str
default value: None

Consistency level to use for the session. The default value is "Session".

consistency_level
default value: Session

Exceptions

Database with the given ID already exists.

get_database_account

Retrieve the database account information.

get_database_account(**kwargs: Any) -> azure.cosmos.documents.DatabaseAccount

Parameters

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

A DatabaseAccount instance representing the Cosmos DB Database Account.

Return type

Exceptions

Database with the given ID already exists.

get_database_client

Retrieve an existing database with the ID (name) id.

get_database_client(database: Union[str, azure.cosmos.database.DatabaseProxy, Dict[str, Any]]) -> azure.cosmos.database.DatabaseProxy

Parameters

database
str or dict(str, str) or DatabaseProxy
Required

The ID (name), dict representing the properties or DatabaseProxy instance of the database to read.

Returns

A DatabaseProxy instance representing the retrieved database.

Return type

Exceptions

Database with the given ID already exists.

list_databases

List the databases in a Cosmos DB SQL database account.

list_databases(max_item_count: Optional[int] = None, populate_query_metrics: Optional[bool] = None, **kwargs: Any) -> Iterable[Dict[str, Any]]

Parameters

max_item_count
int
Required

Max number of items to be returned in the enumeration operation.

populate_query_metrics
bool
Required

Enable returning query metrics in response headers.

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

Initial headers to be sent as part of the request.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

An Iterable of database properties (dicts).

Return type

<xref:Iterable>[dict[str, str]]

Exceptions

Database with the given ID already exists.

query_databases

Query the databases in a Cosmos DB SQL database account.

query_databases(query: Optional[str] = None, parameters: Optional[List[str]] = None, enable_cross_partition_query: Optional[bool] = None, max_item_count: Optional[int] = None, populate_query_metrics: Optional[bool] = None, **kwargs: Any) -> Iterable[Dict[str, Any]]

Parameters

query
str
Required

The Azure Cosmos DB SQL query to execute.

parameters
list[str]
Required

Optional array of parameters to the query. Ignored if no query is provided.

enable_cross_partition_query
bool
Required

Allow scan on the queries which couldn't be served as indexing was opted out on the requested paths.

max_item_count
int
Required

Max number of items to be returned in the enumeration operation.

populate_query_metrics
bool
Required

Enable returning query metrics in response headers.

session_token
str

Token for use with Session consistency.

initial_headers
dict[<xref:str,str>]

Initial headers to be sent as part of the request.

response_hook
<xref:Callable>

A callable invoked with the response metadata.

Returns

An Iterable of database properties (dicts).

Return type

<xref:Iterable>[dict[str, str]]

Exceptions

Database with the given ID already exists.