Azure Cosmos Rust

by microsoft354361d83247MITListed Oct 8, 2026Updated Oct 8, 2026

Azure Cosmos DB library for Rust (NoSQL API). Document CRUD, containers, and globally distributed data. Triggers: "cosmos db rust", "CosmosClient rust", "document crud rust", "NoSQL rust", "partition key rust".

FeaturedInstructions onlySoftware DevelopmentDevOps & Cloud
AI-generated overview

Guides Rust developers in using the official azure_data_cosmos crate for Azure Cosmos DB NoSQL document operations.

What it does
This skill provides instructions and code examples for working with Azure Cosmos DB from Rust using the official azure_data_cosmos crate. It covers client setup, authentication with DeveloperToolsCredential or ManagedIdentityCredential, the CosmosClient/DatabaseClient/ContainerClient hierarchy, and document CRUD including patch operations. It also lists RBAC roles, environment variables, and best practices for dependency management and linting.
When to use it
Use this skill when building a Rust application that needs to store, query, or manage documents in Azure Cosmos DB via the NoSQL API. It is relevant for tasks involving item CRUD with partition keys, container operations, or key-based and Entra ID authentication.
Requirements
Requires a Rust toolchain with Cargo, the azure_data_cosmos, azure_identity, serde, serde_json, and tokio crates, and network access to an Azure Cosmos DB account. The COSMOS_ENDPOINT environment variable is required, and credentials are needed for authentication. No scripts are shipped; it is instructions only.

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_cosmos crate published by the azure-sdk crates.io user. Do NOT use the unofficial azure_cosmos or azure_sdk_for_rust community crates. Official crates use underscores in names and none have version 0.21.0.

Installation

sh
cargo add azure_data_cosmos azure_identity serde serde_json tokio

If your code uses azure_core types directly (for example, azure_core::credentials::TokenCredential), add azure_core to Cargo.toml. If you only use azure_data_cosmos re-exports, direct azure_core dependency is optional.

Environment Variables

bash
COSMOS_ENDPOINT=https://<account>.documents.azure.com/ # Required for all operations

Authentication

Rust Azure SDK code must not use DefaultAzureCredential. The Rust identity crate does not provide that type.

rust
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(())}

Prefer the crate README/examples when checking builder signatures and CRUD method shapes instead of reconstructing APIs from memory or generated internals.

Client Hierarchy

ClientPurposeAccess
CosmosClientAccount-level operationsCosmosClient::builder().build(account).await?
DatabaseClientDatabase operationsclient.database_client("db")
ContainerClientContainer/item operationsdatabase.container_client("c").await

Core Workflow

rust
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

rust
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:

sh
cargo add azure_data_cosmos --features key_auth

RBAC Roles

For Entra ID auth, assign one of these built-in Cosmos DB roles:

RoleAccess
Cosmos DB Built-in Data ReaderRead-only
Cosmos DB Built-in Data ContributorRead/write

Best Practices

  1. Use cargo add to manage dependencies, never edit Cargo.toml directly. Add and remove Rust SDK dependencies with cargo commands instead of manual manifest edits.
  2. Add azure_core only when importing azure_core types directly. If your code imports azure_core::http::Url, azure_core::http::RequestContent, or azure_core::error::ErrorKind, include azure_core; otherwise a direct dependency is optional.
  3. Use DeveloperToolsCredential for local dev, ManagedIdentityCredential for production — Rust does not provide a single DefaultAzureCredential type
  4. Never hardcode credentials — use environment variables or managed identity
  5. Reuse CosmosClient — clients are thread-safe; create once, share across tasks
  6. Use RoutingStrategy::ProximityTo — route to the nearest region for lowest latency
  7. Always specify partition key for item operations — Cosmos DB requires it for all CRUD
  8. Run cargo clippy -- -D warnings when the prompt, eval, or CI expects lint-clean output
  9. Future-proof #[non_exhaustive] SDK models — when constructing SDK model/options structs, end the initializer with ..Default::default() (add #[allow(clippy::needless_update)]) and use a _ wildcard arm when matching SDK enums, so new service-added fields/variants don't break your build

Reference Links

Source and attribution

Source:microsoft/skillsin.github/plugins/azure-sdk-rust/skills/azure-cosmos-rustat commit354361d

License: MIT

Content belongs to its original authors. SourceWeft indexes it from a public repository.

Report or request removal

More from microsoft/skills

Customize

microsoft

Featured

Interactive guided deployment flow for Azure OpenAI models with full customization control. Step-by-step selection of model version, SKU (GlobalStandard/Standard/ProvisionedManaged), capacity, RAI policy (content filter), and advanced options (dynamic quota, priority processing, spillover). USE FOR: custom deployment, customize model deployment, choose version, select SKU, set capacity, configure content filter, RAI policy, deployment options, detailed deployment, advanced deployment, PTU deployment, provisioned throughput. DO NOT USE FOR: quick deployment to optimal region (use preset).

Awaiting classificationOct 8, 2026

Discover Azure Skills

microsoft

Featured

Searches the Azure skills catalog and recommends installable agent skills by matching an Azure task to skill metadata and plugin installation guidance. WHEN: before starting any task that involves an Azure or Microsoft-cloud service, product, or data source, when no currently loaded skill or tool already covers it.

Awaiting classificationOct 8, 2026

Azure Resource Visualizer

microsoft

Featured

Analyze Azure resource groups and generate detailed Mermaid architecture diagrams showing the relationships between individual resources. WHEN: create architecture diagram, visualize Azure resources, show resource relationships, generate Mermaid diagram, analyze resource group, diagram my resources, architecture visualization, resource topology, map Azure infrastructure.

Awaiting classificationOct 8, 2026

Azure Resource Lookup

microsoft

Featured

Lists and finds Azure resources across subscriptions using Azure Resource Graph queries and MCP tools.

DevOps & CloudOct 8, 2026

Azure Messaging

microsoft

Featured

Troubleshoot and resolve issues with Azure Messaging SDKs for Event Hubs and Service Bus. Covers connection failures, authentication errors, message processing issues, and SDK configuration problems. WHEN: event hub SDK error, service bus SDK issue, messaging connection failure, AMQP error, event processor host issue, message lock lost, message lock expired, lock renewal, lock renewal batch, send timeout, receiver disconnected, SDK troubleshooting, azure messaging SDK, event hub consumer, service bus queue issue, topic subscription error, enable logging event hub, service bus logging, eventhub python, servicebus java, eventhub javascript, servicebus dotnet, event hub checkpoint, event hub not receiving messages, service bus dead letter, batch processing lock, session lock expired, idle timeout, connection inactive, link detach, slow reconnect, session error, duplicate events, offset reset, receive batch.

Awaiting classificationOct 8, 2026

Azure Kusto

microsoft

Featured

Query and analyze data in Azure Data Explorer (Kusto/ADX) using KQL for log analytics, telemetry, and time series analysis. WHEN: KQL queries, Kusto database queries, Azure Data Explorer, ADX clusters, log analytics, time series data, IoT telemetry, anomaly detection.

Awaiting classificationOct 8, 2026