Edit

Share via


Use Azure SDK for Rust crates to access Azure services

The Azure SDK for Rust crates help you access Azure services from Rust applications. This article explains how to use these crates, including authentication, supported services, and best practices.

Crates | API reference documentation | Source code

Prerequisites to develop with crates

Tip

For the best development experience, ensure you have the latest stable version of Rust installed.

Provide authentication credentials

The Azure crates need credentials to authenticate to Microsoft Entra ID. Azure services provide different authentication methods for connection. We recommend using the azure_identity crate for authentication. Learn more about authentication for Azure SDK for Rust crates.

Client objects

You use client objects to interact with Azure services. Each client object, from a service's crate, corresponds to a specific Azure service and provides methods to perform operations on that service. For example, azure_security_keyvault_secrets::SecretClient is used to interact with Azure Key Vault secrets.

When you create the client objects, you can provide a ClientOptions parameter for customizing the interactions with the service. Use ClientOptions to set things like timeouts, retry policies, and other configurations.

use azure_identity::AzureCliCredential;
use azure_security_keyvault_secrets::SecretClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    dotazure::load()?;

    let vault_url = std::env::var("AZURE_KEYVAULT_URL")
        .map_err(|_| "AZURE_KEYVAULT_URL environment variable is required")?;

    let credential = AzureCliCredential::new(None)?;

    let client = SecretClient::new(&vault_url, credential.clone(), None)?;

    Ok(())
}

Error handling

When a service call fails, the returned Response contains the status.

use azure_core::{error::ErrorKind, http::StatusCode};
use azure_identity::AzureCliCredential;
use azure_security_keyvault_secrets::SecretClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    dotazure::load()?;

    let credential = AzureCliCredential::new(None)?;

    let vault_url = std::env::var("AZURE_KEYVAULT_URL")
        .map_err(|_| "AZURE_KEYVAULT_URL environment variable is required")?;

    let client = SecretClient::new(&vault_url, credential.clone(), None)?;

    match client.get_secret("secret-0", None).await {
        Ok(secret) => println!("Secret value: {}", secret.into_body()?.value.unwrap_or_default()),
        Err(e) => match e.kind() {
            ErrorKind::HttpResponse { status, error_code, .. } if *status == StatusCode::NotFound => {

                if let Some(code) = error_code {
                    println!("ErrorCode: {}", code);
                } else {
                    println!("Secret not found, but no error code provided.");
                }
            },
            _ => println!("An error occurred: {e:?}"),
        },
    }

    Ok(())
}

Page results

If a service call returns multiple values in pages, it returns Result<Pager<T>> as a Result of Pager.

use azure_identity::AzureCliCredential;
use azure_security_keyvault_secrets::SecretClient;
use futures::TryStreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    dotazure::load()?;

    let credential = AzureCliCredential::new(None)?;

    let vault_url = std::env::var("AZURE_KEYVAULT_URL")
        .map_err(|_| "AZURE_KEYVAULT_URL environment variable is required")?;

    let client = SecretClient::new(&vault_url, credential.clone(), None)?;

    let mut pager = client.list_secret_properties(None)?.into_pages();

    while let Some(page) = pager.try_next().await? {

        let page = page.into_body()?;
        println!("items_in_page: {}", page.value.len());
    }

    Ok(())
}

Pagination to process each page of items

To iterate through all items in a paginated response, use the into_pages() method on the returned Pager. This method returns an async stream of pages as a PageIterator, so you can process each page as it becomes available.

use azure_identity::AzureDeveloperCliCredential;
use azure_security_keyvault_secrets::{ResourceExt, SecretClient};
use futures::TryStreamExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    dotazure::load()?;

    let credential = AzureDeveloperCliCredential::new(None)?;

    let vault_url = std::env::var("AZURE_KEYVAULT_URL")
        .map_err(|_| "AZURE_KEYVAULT_URL environment variable is required")?;

    let client = SecretClient::new(vault_url.as_str(), credential.clone(), None)?;

    let mut pager = client.list_secret_properties(None)?;

    while let Some(secret) = pager.try_next().await? {

        let name = secret.resource_id()?.name;
        println!("Found secret with name: {}", name);
    }

    Ok(())
}

Sample code

The code shown in this article is available on https://github.com/azure-samples/azure-sdk-for-rust-docs/.

Next steps