Skip to main content

Crate azure_data_cosmos

Crate azure_data_cosmos 

Source
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

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.

§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 login

Instantiate 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_auth

For more information, see the API reference documentation.

§CRUD operation on Items

use serde::{Serialize, Deserialize};
use azure_data_cosmos::{CosmosClient, PatchInstructions, PatchOperation};

#[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").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?;

    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()?;
    println!("patched value = {}", patched.value);

    // Delete an item
    container.delete_item("partition1", "1", None).await?;
    Ok(())
}

§Next steps

§Provide feedback

If you encounter bugs or have suggestions, open an issue.

§Developer notes

This crate exposes feature flags prefixed with __internal_ (currently __internal_in_memory_emulator). These are intended only for in-repo testing, are not part of the public API, are not subject to semver, and may change or be removed without notice. Do not enable them on builds shipped to crates.io or to other consumers.

Note: enabling __internal_in_memory_emulator also implicitly enables the key_auth feature (the in-memory emulator authenticates with master keys), which will appear in your dependency graph (cargo tree) when the emulator feature is on.

§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 clients::ThroughputPoller;
pub use models::BatchResponse;
pub use models::ItemResponse;
pub use models::ResourceResponse;
pub use models::ResponseBody;
pub use models::ResponseHeaders;
pub use query::Query;
pub use transactional_batch::BatchDeleteOptions;
pub use transactional_batch::BatchReadOptions;
pub use transactional_batch::BatchReplaceOptions;
pub use transactional_batch::BatchUpsertOptions;
pub use transactional_batch::TransactionalBatch;
pub use transactional_batch::TransactionalBatchOperationResult;
pub use transactional_batch::TransactionalBatchResponse;
pub use options::*;

Modules§

clients
Clients used to communicate with Azure Cosmos DB
fault_injectionfault_injection
Fault injection framework for testing Cosmos DB client behavior under error conditions.
models
Model types sent to and received from the Azure Cosmos DB API.
options
query
Models and components used to represents and execute queries.
regions
Azure region constants for Cosmos DB.
transactional_batch
Types for working with transactional batch operations in Cosmos DB.

Structs§

AccountEndpoint
The endpoint URL for a Cosmos DB account.
AccountReference
A reference to a Cosmos DB account, combining an endpoint with a credential.
ContinuationToken
Opaque continuation token for resuming a paginated Cosmos DB operation.
CosmosClient
Client for Azure Cosmos DB.
CosmosClientBuilder
Builder for creating CosmosClient instances.
CosmosError
The error type returned by every fallible public API in azure_data_cosmos.
DiagnosticsContext
Diagnostic context for a Cosmos DB operation.
EffectivePartitionKey
A newtype wrapping the hex-encoded effective partition key string.
FeedPage
Represents a single page of results from a Cosmos DB feed.
FeedRange
A contiguous range of the effective partition key space.
PartitionKey
A partition key used to identify the target partition for an operation.
PartitionKeyValue
Represents a value for a single partition key.
PatchInstructions
A set of instructions for a Cosmos DB PATCH operation, consisting of an ordered list of PatchOperation values representing the individual operations to apply to an item.
QueryFeedPage
Represents a single page of results from a Cosmos DB query.
QueryItemIterator
Represents a stream of items from a Cosmos DB query.
QueryPageIterator
A stream of pages from a Cosmos DB feed operation.

Enums§

CosmosCredential
Authentication credential for connecting to a Cosmos DB account.
CosmosNumber
A typed numeric increment delta for PatchOperation::Increment.
PatchOperation
A single operation in a Cosmos DB PATCH document.
RoutingStrategy
Determines how the SDK selects Azure regions for routing requests.

Type Aliases§

CosmosStatus
Typed Cosmos status (HTTP status code + optional sub-status) — type alias re-exporting the driver definition so SDK-only callers can stay on a single crate import.
Result
azure_data_cosmos crate-wide Result alias.
SubStatusCode
Sub-status code — type alias re-exporting the driver definition.