Expand description
§Azure Cosmos DB SDK for Rust
This client library enables client applications to connect to Azure Cosmos DB via the NoSQL API. Azure Cosmos DB is a globally distributed, multi-model database service.
Source code | Package (crates.io) | API reference documentation | Azure Cosmos DB for NoSQL documentation
§Getting started
§Install the package
Install the Azure Cosmos DB SDK for Rust with cargo:
cargo add azure_data_cosmos§Prerequisites
- An Azure subscription or free Azure Cosmos DB trial account.
Note: If you don’t have an Azure subscription, create a free account before you begin. You can Try Azure Cosmos DB for free without an Azure subscription, free of charge and commitments, or create an Azure Cosmos DB free tier account, with the first 400 RU/s and 5 GB of storage for free. You can also use the Azure Cosmos DB Emulator with a URI of https://localhost:8081. For the key to use with the emulator, see how to develop with the emulator.
§Known Issue: Using the vNext emulator
The Azure Cosmos DB Linux vNext emulator does not currently support Cosmos binary JSON encoding. Binary encoding is enabled by default in this SDK and must be explicitly disabled when connecting to the vNext emulator. This is a temporary known issue, and we’re working towards an automatic resolution. Please see the tracking issue at Azure/azure-sdk-for-rust#5240.
NOTE: This does NOT apply to the Windows emulator. Only the Linux emulators require disabling binary encoding.
For now, you must disable Binary Encoding explicitly when building the client:
use azure_data_cosmos::{options::BinaryEncodingOptions, CosmosClient};
let client = CosmosClient::builder()
.with_binary_encoding_options(BinaryEncodingOptions::new().with_enabled(false))
.build(account, routing_strategy)
.await?;Alternatively, disable binary encoding through the environment before starting the application:
export AZURE_COSMOS_BINARY_ENCODING_ENABLED=falseAn explicit client option takes precedence over the environment variable.
§Create an Azure Cosmos DB account
You can create an Azure Cosmos DB account using:
§Authenticate the client
In order to interact with the Azure Cosmos DB service you’ll need to create an instance of the CosmosClient struct. To make this possible you will need a URL and key of the Azure Cosmos DB service.
§Examples
The following section provides several code snippets covering some of the most common Azure Cosmos DB NoSQL API tasks, including:
§Create Cosmos DB Client
In order to interact with the Azure Cosmos DB service, you’ll need to create an instance of the CosmosClient. You need an endpoint URL and credentials to instantiate a client object.
§Using Microsoft Entra ID
The example shown below use a DeveloperToolsCredential, which is appropriate for most local development environments. Additionally, we recommend using a managed identity for authentication in production environments. You can find more information on different ways of authenticating and their corresponding credential types in the Azure Identity documentation.
The DeveloperToolsCredential will automatically pick up on an Azure CLI authentication. Ensure you are logged in with the Azure CLI:
az loginInstantiate a DeveloperToolsCredential to pass to the client. The same instance of a token credential can be used with multiple clients if they will be authenticating with the same identity.
use azure_identity::DeveloperToolsCredential;
use azure_data_cosmos::{
CosmosClient, AccountReference, AccountEndpoint, RoutingStrategy,
};
async fn example() -> Result<(), Box<dyn std::error::Error>> {
let credential: std::sync::Arc<dyn azure_core::credentials::TokenCredential> =
DeveloperToolsCredential::new(None)?;
let endpoint: AccountEndpoint = "https://myaccount.documents.azure.com/"
.parse()?;
let account = AccountReference::with_credential(endpoint, credential);
let cosmos_client = CosmosClient::builder()
.build(account, RoutingStrategy::ProximityTo("East US".into()))
.await?;
Ok(())
}§Using account keys
Cosmos DB also supports account keys, though we strongly recommend using Entra ID authentication. To use account keys, you will need to enable the key_auth feature:
cargo add azure_data_cosmos --features key_authFor more information, see the API reference documentation.
§Control-plane operations
Management operations for databases and containers — creating, replacing, and
deleting databases and containers, reading database properties, and reading and
updating throughput (offers) — are gated behind the non-default control_plane
feature:
cargo add azure_data_cosmos --features control_planeNOTE: Currently, these operations require key-based authentication, and are not supported with Entra ID authentication.
Reading container properties via ContainerClient::read() is an exception: it is available
without the control_plane feature and works with Entra ID authentication, since it mirrors the
container metadata read the SDK already performs internally.
§CRUD operation on Items
use serde::{Serialize, Deserialize};
use azure_data_cosmos::CosmosClient;
#[derive(Serialize, Deserialize)]
struct Item {
pub id: String,
pub partition_key: String,
pub value: String,
}
async fn example(cosmos_client: CosmosClient) -> Result<(), Box<dyn std::error::Error>> {
let item = Item {
id: "1".into(),
partition_key: "partition1".into(),
value: "2".into(),
};
let container = cosmos_client
.database_client("myDatabase")
.container_client("myContainer", None)
.await?;
// Create an item
container.create_item("partition1", "1", item, None).await?;
// Read an item
let item_response = container.read_item("partition1", "1", None).await?;
let mut item: Item = item_response.into_model()?;
item.value = "3".into();
// Replace an item
container.replace_item("partition1", "1", item, None).await?;
// Delete an item
container.delete_item("partition1", "1", None).await?;
Ok(())
}§Partial updates with PATCH (preview)
ContainerClient::patch_item() applies JSON-Patch-style operations to a single item. It is
gated behind the preview_patch feature and is not production-ready:
cargo add azure_data_cosmos --features preview_patchuse azure_data_cosmos::models::{PatchInstructions, PatchOperation};
let patch = PatchInstructions::from(vec![
PatchOperation::set("/value", serde_json::json!("4")),
]);
let patched: Item = container
.patch_item("partition1", "1", patch, None)
.await?
.into_model()?;The default PatchStrategy::Auto uses one server-side request for retry-safe
lists containing at most 10 instructions. Unsafe or longer lists use the
client-side read-modify-write path. Marker-backed tracking is used only for
non-retry-safe lists. Explicit ServerSide never falls back and Cosmos DB
rejects more than 10 instructions with HTTP 400.
§Next steps
§Provide feedback
If you encounter bugs or have suggestions, open an issue.
§Internal features
This crate exposes several feature flags prefixed with __internal_. Features behind these feature flags are internal APIs for testing within the Azure SDK for Rust and are not intended for public use. These APIs may change without warning, and using them may lead to broken code.
§Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You’ll only need to do this once across all repos using our CLA.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
Re-exports§
pub use error::CosmosError;pub use error::CosmosStatus;pub use error::Result;pub use error::SubStatusCode;pub use feed::FeedScope;pub use feed::Query;pub use models::TransactionalBatch;pub use options::RoutingStrategy;
Modules§
- clients
- Clients used to communicate with Azure Cosmos DB
- diagnostics
- Per-operation diagnostics surfaced by the Cosmos DB SDK.
- error
- SDK-owned newtype wrapper around the driver’s
CosmosError. - fault_
injection fault_injection - Fault injection framework for testing Cosmos DB client behavior under error conditions.
- feed
- Types related to Cosmos DB feed operations, including query and change feed iteration, pagination and related models.
- models
- Resource model types sent to and received from the Azure Cosmos DB API.
- options
- Per-request options types for Cosmos DB SDK operations.
Structs§
- Account
Endpoint - The endpoint URL for a Cosmos DB account.
- Account
Reference - A reference to a Cosmos DB account, combining an endpoint with a credential.
- Container
Client - A client for working with a specific container in a Cosmos DB account.
- Cosmos
Client - Client for Azure Cosmos DB.
- Cosmos
Client Builder - Builder for creating
CosmosClientinstances. - Cosmos
Runtime - Shared runtime for one or more
CosmosClientinstances. - Cosmos
Runtime Builder - Builder for constructing a customized
CosmosRuntime. - Database
Client - A client for working with a specific database in a Cosmos DB account.
- Partition
Key - A partition key used to identify the target partition for an operation.
- Resource
Id - A Cosmos DB resource identifier (RID).
Enums§
- Cosmos
Credential - Authentication credential for connecting to a Cosmos DB account.
- Resource
Identity - Identifies a Cosmos DB database or container, either by user-provided name or
by
ResourceId(RID).