Expand description
§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.
Modules§
- authority_
hosts - A list of known Azure authority hosts
- base64
- Base64 encoding and decoding functions.
- builders
- Client options and client method options builders.
- content_
type - Constants related to the Content-Type header
- credentials
- Azure authentication and authorization.
- date
- Date and time parsing and formatting functions.
- error
- headers
- hmac
- json
- JSON serialization functions.
- lro
- parsing
- Parser helper utilities.
- query_
param - Constants related to query parameters
- request_
options - resource_
manager_ endpoint - Endpoints for Azure Resource Manager in different Azure clouds
- sleep
- Sleep functions.
- test
- Shared utilities for testing client libraries built on
azure_core. - tokio
- xml
- XML serialization functions.
Macros§
- future
- Declare a
Futurewith the given name - static_
url
Structs§
- Bearer
Token Credential Policy - Bytes
- A cheaply cloneable and sliceable chunk of contiguous memory.
- Bytes
Stream - Convenience struct that maps a
bytes::Bytesbuffer into a stream. - Client
Method Options - Method options allow customization of client method calls.
- Client
Options - Client options allow customization of general client policies, retry options, and more.
- Context
- Pipeline execution context.
- Custom
Headers - Custom headers to add to a request.
- Custom
Headers Policy Policyto addCustomHeadersto a request.- Error
- An error encountered when communicating with the service.
- Etag
- Exponential
Retry Options - Options for how an exponential retry strategy should behave.
- Exponential
Retry Policy - Retry policy with exponential back-off.
- Fixed
Retry Options - Options for how a fixed retry strategy should behave.
- Fixed
Retry Policy - Retry policy with a fixed back-off.
- NoRetry
Policy - Retry policy that does not retry.
- Pager
- Represents a paginated result across multiple requests.
- Pipeline
- Execution pipeline.
- Request
- A pipeline request.
- Request
Content - The body content of a service client request. This allows callers to pass a model to serialize or raw content to client methods.
- Response
- An HTTP response.
- Response
Body - A response body stream.
- Retry
Options - Specify how retries should behave.
- Telemetry
Options - Telemetry options.
- Telemetry
Policy - Transport
Options - Transport options.
- Transport
Policy - Url
- A parsed URL record.
- Uuid
- A Universally Unique Identifier (UUID).
Enums§
- Body
- An HTTP Body.
- Lease
Action - The lease action to perform on an Azure resource.
- Lease
Duration - Lease duration of an Azure resource.
- Lease
State - State of a lease of an Azure resource.
- Lease
Status - Lease status of an Azure resource.
- Method
- HTTP request methods.
- Status
Code - HTTP response status codes.
Constants§
- EMPTY_
BODY - An empty HTTP body.
Traits§
- Append
ToUrl Query - Add a new query pair into the target
Url’s query string. - Header
- View a type as an HTTP header.
- Http
Client - An HTTP client which can send requests.
- Model
- Trait that represents types that can be deserialized from an HTTP response body.
- Policy
- A pipeline policy.
- Retry
Policy - A retry policy.
- Seekable
Stream - Enable a type implementing
AsyncReadto be consumed as if it were aStreamofBytes.
Functions§
- get_
retry_ after - Get the duration to delay between retry attempts, provided by the headers from the response.
- new_
http_ client - Create a new
HttpClient. - sleep
- Waits until
durationhas elapsed.
Type Aliases§
- Pinned
Stream - Policy
Result - A specialized
Resulttype for policies. - Request
Id - A unique identifier for a request.
- Result
- A convenience alias for
Resultwhere the error type is hard coded toError. - Session
Token - A unique session token.