Azure Cosmos DB library for Rust
Client library for Azure Cosmos DB NoSQL API — document CRUD, containers, and globally distributed data.
Use this skill when:
- An app needs to store or query documents in Cosmos DB from Rust
- You need CRUD operations on items with partition keys
- You need key-based auth as an alternative to Entra ID
IMPORTANT: Only use the official
azure_data_cosmoscrate published by the azure-sdk crates.io user. Do NOT use the unofficialazure_cosmosorazure_sdk_for_rustcommunity crates. Official crates use underscores in names and none have version 0.21.0.
Installation
cargo add azure_data_cosmos azure_identity serde serde_json tokio
If your code uses
azure_coretypes directly (for example,azure_core::credentials::TokenCredential), addazure_coretoCargo.toml. If you only useazure_data_cosmosre-exports, directazure_coredependency is optional.
Environment Variables
COSMOS_ENDPOINT=https://<account>.documents.azure.com/ # Required for all operations
Authentication
use azure_identity::DeveloperToolsCredential;
use azure_data_cosmos::{
CosmosClient, AccountReference, AccountEndpoint, RoutingStrategy,
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Local dev: DeveloperToolsCredential. Production: use ManagedIdentityCredential.
let credential = DeveloperToolsCredential::new(None)?;
let endpoint: AccountEndpoint = "https://<account>.documents.azure.com/"
.parse()?;
let account = AccountReference::with_credential(endpoint, credential);
let client = CosmosClient::builder()
.build(account, RoutingStrategy::ProximityTo("East US".into()))
.await?;
Ok(())
}
Client Hierarchy
| Client | Purpose | Access |
| ----------------- | ------------------------- | --------------------------------------- |
| CosmosClient | Account-level operations | CosmosClient::builder().build(account).await? |
| DatabaseClient | Database operations | client.database_client("db") |
| ContainerClient | Container/item operations | database.container_client("c").await |
Core Workflow
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 crud(client: CosmosClient) -> Result<(), Box<dyn std::error::Error>> {
let container = client
.database_client("myDatabase")
.container_client("myContainer")
.await;
let item = Item {
id: "1".into(),
partition_key: "pk1".into(),
value: "hello".into(),
};
// Create
container.create_item("pk1", "1", item, None).await?;
// Read
let resp = container.read_item("pk1", "1", None).await?;
let mut item: Item = resp.into_model()?;
// Update
item.value = "updated".into();
container.replace_item("pk1", "1", item, None).await?;
// Delete
container.delete_item("pk1", "1", None).await?;
Ok(())
}
Patch Item
use azure_data_cosmos::{PatchInstructions, PatchOperation};
let patch = PatchInstructions::from(vec![
PatchOperation::set("/value", serde_json::json!("patched")),
]);
let patched: Item = container
.patch_item("pk1", "1", patch, None)
.await?
.into_model()?;
println!("Patched value: {}", patched.value);
Key Auth (Optional)
Enable account key authentication with the feature flag:
cargo add azure_data_cosmos --features key_auth
RBAC Roles
For Entra ID auth, assign one of these built-in Cosmos DB roles:
| Role | Access |
| ------------------------------------- | ---------- |
| Cosmos DB Built-in Data Reader | Read-only |
| Cosmos DB Built-in Data Contributor | Read/write |
Best Practices
- Use
cargo addto manage dependencies, never editCargo.tomldirectly. Add and remove Rust SDK dependencies with cargo commands instead of manual manifest edits. - Add
azure_coreonly when importingazure_coretypes directly. If your code importsazure_core::http::Url,azure_core::http::RequestContent, orazure_core::error::ErrorKind, includeazure_core; otherwise a direct dependency is optional. - Use
DeveloperToolsCredentialfor local dev,ManagedIdentityCredentialfor production — Rust does not provide a singleDefaultAzureCredentialtype - Never hardcode credentials — use environment variables or managed identity
- Reuse
CosmosClient— clients are thread-safe; create once, share across tasks - Use
RoutingStrategy::ProximityTo— route to the nearest region for lowest latency - Always specify partition key for item operations — Cosmos DB requires it for all CRUD
Reference Links
| Resource | Link | | ------------- | ---------------------------------------------------------------------------------- | | API Reference | https://docs.rs/azure_data_cosmos/latest/azure_data_cosmos | | crates.io | https://crates.io/crates/azure_data_cosmos | | Source Code | https://github.com/Azure/azure-sdk-for-rust/tree/main/sdk/cosmos/azure_data_cosmos |