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.
It's recommended to maintain a single instance of CosmosClient per lifetime of the application which enables efficient connection management and performance.
CosmosClient initialization is a heavy operation - don't use initialization CosmosClient instances as credentials or network connectivity validations.
Instantiate a new CosmosClient.
Constructor
CosmosClient(url: str, credential: str | dict[str, str] | AsyncTokenCredential, *, consistency_level: str | None = None, **kwargs: Any)
Parameters
| Name | Description |
|---|---|
|
url
Required
|
The URL of the Cosmos DB account. |
|
credential
Required
|
Can be the account key, or a dictionary of resource tokens. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
consistency_level
|
Consistency level to use for the session. Default value is None (account-level). More on consistency levels and possible values: https://aka.ms/cosmos-consistency-levels Default value: None
|
|
timeout
|
An absolute timeout in seconds, for the combined HTTP request and response processing. |
|
connection_timeout
|
The HTTP request timeout in seconds. |
|
connection_mode
|
The connection mode for the client - currently only supports 'Gateway'. |
|
proxy_config
|
Connection proxy configuration. |
|
ssl_config
|
Connection SSL configuration. |
|
connection_verify
|
Whether to verify the connection, default value is True. |
|
connection_cert
|
An alternative certificate to verify the connection. |
|
retry_total
|
Maximum retry attempts. |
|
retry_backoff_max
|
Maximum retry wait time in seconds. |
|
retry_fixed_interval
|
Fixed retry interval in milliseconds. |
|
retry_read
|
Maximum number of socket read retry attempts. |
|
retry_connect
|
Maximum number of connection error retry attempts. |
|
retry_status
|
Maximum number of retry attempts on error status codes. |
|
retry_on_status_codes
|
A list of specific status codes to retry on. |
|
retry_backoff_factor
|
Factor to calculate wait time between retry attempts. |
|
retry_write
|
Indicates whether the SDK should automatically retry write operations for items, even if the operation is not guaranteed to be idempotent. This should only be enabled if the application can tolerate such risks or has logic to safely detect and handle duplicate operations. |
|
enable_endpoint_discovery
|
Enable endpoint discovery for geo-replicated database accounts. (Default: True) |
|
preferred_locations
|
The preferred locations for geo-replicated database accounts. |
|
excluded_locations
|
The excluded locations to be skipped from preferred locations. The locations in this list are specified as the names of the azure Cosmos locations like, 'West US', 'East US' and so on. If all preferred locations were excluded, primary/hub location will be used. |
|
enable_diagnostics_logging
|
Enable the CosmosHttpLogging policy. Must be used along with a logger to work. |
|
logger
|
Logger to be used for collecting request diagnostics. Can be passed in at client level (to log all requests) or at a single request level. Requests will be logged at INFO level. |
|
no_response_on_write
|
Indicates whether service should be instructed to skip sending response payloads for write operations on items by default unless specified differently per operation. |
|
throughput_bucket
|
The desired throughput bucket for the client |
|
user_agent_suffix
|
Allows user agent suffix to be specified when creating client |
Examples
Create a new instance of the Cosmos DB client:
url = os.environ["ACCOUNT_URI"]
key = os.environ["ACCOUNT_KEY"]
async with CosmosClient(url, key) as client:
Methods
| close |
Close this instance of CosmosClient. |
| 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_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. |
close
Close this instance of CosmosClient.
async close() -> None
create_database
Create a new database with the given ID (name).
async create_database(id: str, *, offer_throughput: int | ThroughputProperties | None = None, initial_headers: dict[str, str] | None = None, response_hook: Callable[[Mapping[str, Any]], None] | None = None, throughput_bucket: int | None = None, return_properties: Literal[False] = False, **kwargs: Any) -> DatabaseProxy
Parameters
| Name | Description |
|---|---|
|
args
Required
|
args |
|
id
Required
|
ID (name) of the database to read or create. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
offer_throughput
|
The provisioned throughput for this database. |
|
initial_headers
|
Initial headers to be sent as part of the request. |
|
response_hook
|
A callable invoked with the response metadata. |
|
throughput_bucket
|
The desired throughput bucket for the client |
|
return_properties
|
Specifies whether to return either a DatabaseProxy or a Tuple containing a DatabaseProxy and the associated database properties. |
Returns
| Type | Description |
|---|---|
|
A DatabaseProxy instance representing the database or a tuple of DatabaseProxy and CosmosDict with the database properties. |
Exceptions
| Type | Description |
|---|---|
|
Database with the given ID already exists. |
Examples
Create a database in the Cosmos DB account:
database_name = "testDatabase"
try:
database = await 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.
async create_database_if_not_exists(id: str, *, offer_throughput: int | ThroughputProperties | None = None, initial_headers: dict[str, str] | None = None, response_hook: Callable[[Mapping[str, Any]], None] | None = None, throughput_bucket: int | None = None, return_properties: Literal[False] = False, **kwargs: Any) -> DatabaseProxy
Parameters
| Name | Description |
|---|---|
|
args
Required
|
args |
|
id
Required
|
ID (name) of the database to read or create. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
offer_throughput
|
The provisioned throughput for this database. |
|
initial_headers
|
Initial headers to be sent as part of the request. |
|
response_hook
|
A callable invoked with the response metadata. |
|
throughput_bucket
|
The desired throughput bucket for the client |
|
return_properties
|
Specifies whether to return either a DatabaseProxy or a Tuple containing a DatabaseProxy and the associated database properties. |
Returns
| Type | Description |
|---|---|
|
A DatabaseProxy instance representing the database or a tuple of DatabaseProxy and CosmosDict with the database properties. |
Exceptions
| Type | Description |
|---|---|
|
The database read or creation failed. |
delete_database
Delete the database with the given ID (name).
async delete_database(database: str | DatabaseProxy | dict[str, Any], *, initial_headers: dict[str, str] | None = None, response_hook: Callable[[Mapping[str, Any]], None] | None = None, throughput_bucket: int | None = None, **kwargs: Any) -> None
Parameters
| Name | Description |
|---|---|
|
database
Required
|
The ID (name), dict representing the properties, or DatabaseProxy instance of the database to delete. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
Returns
| Type | Description |
|---|---|
Exceptions
| Type | Description |
|---|---|
|
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: str | dict[str, str] | None = None, consistency_level: str | None = None, **kwargs: Any) -> CosmosClient
Parameters
| Name | Description |
|---|---|
|
conn_str
Required
|
The connection string. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
credential
|
Alternative credentials to use instead of the key provided in the connection string. Default value: None
|
|
consistency_level
|
Consistency level to use for the session. Default value is None (account-level). More on consistency levels and possible values: https://aka.ms/cosmos-consistency-levels Default value: None
|
Returns
| Type | Description |
|---|---|
|
a CosmosClient instance |
get_database_client
Retrieve an existing database with the ID (name) id.
get_database_client(database: str | DatabaseProxy | dict[str, Any]) -> DatabaseProxy
Parameters
| Name | Description |
|---|---|
|
database
Required
|
The ID (name), dict representing the properties, or DatabaseProxy instance of the database to get. |
Returns
| Type | Description |
|---|---|
|
A DatabaseProxy instance representing the retrieved database. |
list_databases
List the databases in a Cosmos DB SQL database account.
list_databases(*, max_item_count: int | None = None, initial_headers: dict[str, str] | None = None, response_hook: Callable[[Mapping[str, Any]], None] | None = None, throughput_bucket: int | None = None, **kwargs: Any) -> AsyncItemPaged[dict[str, Any]]
Keyword-Only Parameters
| Name | Description |
|---|---|
|
max_item_count
|
Max number of items to be returned in the enumeration operation. Default value: None
|
|
session_token
|
Token for use with Session consistency. |
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
Returns
| Type | Description |
|---|---|
|
An AsyncItemPaged of database properties (dicts). |
query_databases
Query the databases in a Cosmos DB SQL database account.
query_databases(query: str, *, parameters: list[dict[str, Any]] | None = None, max_item_count: int | None = None, initial_headers: dict[str, str] | None = None, response_hook: Callable[[Mapping[str, Any]], None] | None = None, throughput_bucket: int | None = None, **kwargs: Any) -> AsyncItemPaged[dict[str, Any]]
Parameters
| Name | Description |
|---|---|
|
query
Required
|
The Azure Cosmos DB SQL query to execute. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
parameters
|
Optional array of parameters to the query. Each parameter is a dict() with 'name' and 'value' keys. Default value: None
|
|
max_item_count
|
Max number of items to be returned in the enumeration operation. Default value: None
|
|
session_token
|
Token for use with Session consistency. |
|
initial_headers
|
Initial headers to be sent as part of the request. Default value: None
|
|
response_hook
|
A callable invoked with the response metadata. Default value: None
|
|
throughput_bucket
|
The desired throughput bucket for the client Default value: None
|
Returns
| Type | Description |
|---|---|
|
An AsyncItemPaged of database properties (dicts). |