azure_core

Crates.ioazure_core
lib.rsazure_core
version0.22.0
sourcesrc
created_at2021-12-29 12:29:51.714408+00
updated_at2025-02-18 21:57:30.476267+00
descriptionRust wrappers around Microsoft Azure REST APIs - Core crate
homepagehttps://github.com/azure/azure-sdk-for-rust
repositoryhttps://github.com/azure/azure-sdk-for-rust
max_upload_size
id504812
size75,381
Patrick Hallisey (hallipr)

documentation

https://docs.rs/azure_core

README

Azure Core shared client library for Rust

azure_core provides shared primitives, abstractions, and helpers for modern Rust Azure SDK client libraries. These libraries follow the Azure SDK Design Guidelines for Rust and can typically be identified by package and namespaces names starting with azure_, e.g. azure_identity.

azure_core allows client libraries to expose common functionality in a consistent fashion so that once you learn how to use these APIs in one client library, you will know how to use them in other client libraries.

Source code | Package (crates.io) | API Reference Documentation

Getting started

Typically, you will not need to install azure_core; it will be installed for you when you install one of the client libraries using it. In case you want to install it explicitly - to implement your own client library, for example - you can find the crates.io package here.

Key concepts

The main shared concepts of azure_core - and Azure SDK libraries using azure_core - include:

  • Configuring service clients, e.g. configuring retries, logging (ClientOptions).
  • Accessing HTTP response details (Response<T>).
  • Paging and asynchronous streams (Pager<T>).
  • Errors from service requests in a consistent fashion. (azure_core::Error).
  • Customizing requests (ClientOptions).
  • Abstractions for representing Azure SDK credentials. (TokenCredentials).

Thread safety

We guarantee that all client instance methods are thread-safe and independent of each other (guidelines). This ensures that the recommendation of reusing client instances is always safe, even across threads.

Additional concepts

Client options | Accessing the response | Handling Errors Results | Consuming Service Methods Returning Pager<T>

Examples

NOTE: Samples in this file apply only to packages that follow Azure SDK Design Guidelines. Names of such packages typically start with azure_.

Configuring service clients using ClientOptions

Azure SDK client libraries typically expose one or more service client types that are the main starting points for calling corresponding Azure services. You can easily find these client types as their names end with the word Client. For example, SecretClient can be used to call the Key Vault service and interact with secrets, and KeyClient can be used to access Key Vault service cryptographic keys.

These client types can be instantiated by calling a simple new function that takes various configuration options.These options are passed as a parameter that extends ClientOptions class exposed by azure_core. Various service specific options are usually added to its subclasses, but a set of SDK-wide options are available directly on ClientOptions.

use azure_core::ClientOptions;
use azure_identity::DefaultAzureCredential;
use azure_security_keyvault_secrets::{SecretClient, SecretClientOptions};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let credential = DefaultAzureCredential::new()?;

    let options = SecretClientOptions {
        api_version: "7.5".to_string(),
        ..Default::default()
    };

    let client = SecretClient::new(
        "https://your-key-vault-name.vault.azure.net/",
        credential.clone(),
        Some(options),
    )?;

    Ok(())
}

Accessing HTTP response details using Response<T>

Service clients have methods that can be used to call Azure services. We refer to these client methods as service methods. Service methods return a shared azure_core type Response<T> where T is either a Model type or a ResponseBody representing a raw stream of bytes. This type provides access to both the deserialized result of the service call, and to the details of the HTTP response returned from the server.

use azure_core::Response;
use azure_identity::DefaultAzureCredential;
use azure_security_keyvault_secrets::{models::SecretBundle, SecretClient};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // create a client
    let credential = DefaultAzureCredential::new()?;
    let client = SecretClient::new(
        "https://your-key-vault-name.vault.azure.net/",
        credential.clone(),
        None,
    )?;

    // call a service method, which returns Response<T>
    let response = client.get_secret("secret-name", "", None).await?;

    // Response<T> has two main accessors:
    // 1. The `into_body()` function consumes self to deserialize into a model type
    let secret = response.into_body().await?;

    // get response again because it was moved in above statement
    let response: Response<SecretBundle> = client.get_secret("secret-name", "", None).await?;

    // 2. The deconstruct() method for accessing all the details of the HTTP response
    let (status, headers, body) = response.deconstruct();

    // for example, you can access HTTP status
    println!("Status: {}", status);

    // or the headers
    for (header_name, header_value) in headers.iter() {
        println!("{}: {}", header_name.as_str(), header_value.as_str());
    }

    Ok(())
}

Handling errors results

When a service call fails, the returned Result will contain an Error. The Error type provides a status property with an HTTP status code and an error_code property with a service-specific error code.

use azure_core::{error::{ErrorKind, HttpError}, Response, StatusCode};
use azure_identity::DefaultAzureCredential;
use azure_security_keyvault_secrets::SecretClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // create a client
    let credential = DefaultAzureCredential::new()?;
    let client = SecretClient::new(
        "https://your-key-vault-name.vault.azure.net/",
        credential.clone(),
        None,
    )?;

    match client.get_secret("secret-name", "", None).await {
        Ok(secret) => println!("Secret: {:?}", secret.into_body().await?.value),
        Err(e) => match e.kind() {
            ErrorKind::HttpResponse { status, error_code, .. } if *status == StatusCode::NotFound => {
                // handle not found error
                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(())
}

Consuming service methods returning Pager<T>

If a service call returns multiple values in pages, it would return Result<Pager<T>> as a result. You can iterator over each page's vector of results.

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

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // create a client
    let credential = DefaultAzureCredential::new()?;
    let client = SecretClient::new(
        "https://your-key-vault-name.vault.azure.net/",
        credential.clone(),
        None,
    )?;

    // get a stream
    let mut pager = client.get_secrets(None)?.into_stream();

    // poll the pager until there are no more SecretListResults
    while let Some(secrets) = pager.try_next().await? {
        let Some(secrets) = secrets.into_body().await?.value else {
            continue;
        };

        // loop through secrets in SecretsListResults
        for secret in secrets {
            // get the secret name from the ID
            let name = secret.resource_id()?.name;
            println!("Found secret with name: {}", name);
        }
    }

    Ok(())
}

Contributing

See the CONTRIBUTING.md for details on building, testing, and contributing to these libraries.

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://opensource.microsoft.com/cla/.

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 will 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.

Commit count: 2080

cargo fmt