references/azure-sdk-patterns.md · 24000
match error_code {
StorageErrorCode::BlobNotFound => println!("Blob does not exist."),
StorageErrorCode::ContainerNotFound => println!("Container does not exist."),
StorageErrorCode::AuthorizationFailure => println!("Auth failed."),
_ => println!("Other error: {error_code}"),
}
}
}
}
}
Note that `StorageError::try_into` requires an owned error object, it will not compile if handed a reference to an error.
### Model Types
```rust
// Request/response models: Clone + Default + Serialize/Deserialize
// All non-vector fields are Option<T>
// Response-only models are #[non_exhaustive]
// Use ..Default::default() for struct update syntax
let parameters = UpdateSecretPropertiesParameters {
content_type: Some("text/plain".into()),
tags: Some(HashMap::from_iter(vec![("key".into(), "value".into())])),
..Default::default()
};
// Cosmos DB uses serde for document types
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Item {
pub id: String,
pub partition_key: String,
pub value: String,
}
When documenting Rust model types, explicitly teach users how to handle #[non_exhaustive] structs and enums:
- When constructing SDK model structs, always include
..Default::default()even if every currently known field is set. - When matching SDK enums, include a wildcard arm so future service-added variants do not break the match.
- If Clippy or the compiler flags those future-proofing patterns in a minimal example, it is acceptable to locally suppress the warning on that example.
#![allow(dead_code, unused_variables)]
#[derive(Default)]
struct Model {
one: Option<String>,
two: Option<i32>,
}
enum E {
One,
Two,
}
fn main() {
// Future-proof struct construction for non-exhaustive SDK models.
#[allow(clippy::needless_update)]
let model = Model {
one: Some("one".into()),
two: Some(2),
..Default::default()
};
// Future-proof enum matching for non-exhaustive SDK enums.
let value = E::One;
match value {
E::One => println!("One"),
E::Two => println!("Two"),
#[allow(unreachable_patterns)]
_ => panic!("unexpected variant"),
};
}
Async Only
The Rust SDK provides only async methods. No sync wrappers:
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let credential = DeveloperToolsCredential::new(None)?;
let client = SecretClient::new(endpoint, credential.clone(), None)?;
let secret = client.get_secret("name", None).await?.into_model()?;
Ok(())
}
Key Differences from Other Azure SDKs
| Aspect | Rust | Other Languages |
| ------ | ---- | --------------- |
| Auth default | DeveloperToolsCredential | DefaultAzureCredential |
| Client creation | Client::new() or builder pattern (varies by service) | Constructors or builders |
| Sync support | Async only (tokio) | Sync + Async |
| Options | Option<ClientOptions> param | Separate options class |
| Response access | response.into_model()? | Direct return or .Value |
| LRO prefix | begin_ prefix (e.g., begin_create_certificate) | begin_ or Begin |
| Debug safety | SafeDebug derive (redacts PII) | Standard debug |
| Pagination stream | futures::TryStreamExt | Language iterators |
| Serialization | serde for Cosmos DB documents | Built-in serializers |
| Thread safety | All clients are Send + Sync; reuse is safe | Same guarantee |
Rust Skill Authoring Guardrails
When writing or refreshing a Rust Azure SDK skill, include explicit anti-pattern callouts for the mistakes most likely to happen when an agent generalizes from other languages:
- Name the exact credential type to use, and name at least one tempting but invalid credential type if cross-language confusion is likely.
- Show the exact pager item shape for the relevant service client and say whether
try_next()yields items or pages. - Call out optional SDK fields that cannot be printed directly with
{}and show the idiomatic fallback pattern. - If the target scenario or eval expects strict linting, say so explicitly and require
cargo clippy -- -D warningsas a completion gate. - Prefer examples copied from the service crate README or examples directory over reconstructed snippets from generated source.
Authentication (All Languages)
Use the language-idiomatic primary credential pattern:
Python
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
client = ServiceClient(endpoint, credential)
.NET
var credential = new DefaultAzureCredential();
var client = new ServiceClient(new Uri(endpoint), credential);
Java
TokenCredential credential = new DefaultAzureCredentialBuilder().build();
ServiceClient client = new ServiceClientBuilder()
.endpoint(endpoint)
.credential(credential)
.buildClient();
TypeScript
import { DefaultAzureCredential } from "@azure/identity";
const credential = new DefaultAzureCredential();
const client = new ServiceClient(endpoint, credential);
Rust
use azure_identity::DeveloperToolsCredential;
// Key Vault, Storage: Client::new()
let credential = DeveloperToolsCredential::new(None)?;
let client = SecretClient::new(endpoint, credential.clone(), None)?;
// Cosmos DB: Builder pattern
let account = AccountReference::with_credential(endpoint.parse()?, credential);
let cosmos_client = CosmosClient::builder().build(account).await?;
// Event Hubs: Builder with open()
let producer = ProducerClient::builder()
.open(host, eventhub, credential.clone())
.await?;
Important: Rust does not have
DefaultAzureCredential. Skills for Rust should explicitly say “do not useDefaultAzureCredential” when there is any chance of cross-language confusion. UseDeveloperToolsCredentialfor development (tries Azure CLI, then Azure Developer CLI). UseManagedIdentityCredentialfor production on Azure-hosted apps. See Credential structures for the full list.
Rules:
- Never hardcode credentials
- Never persist/cache tokens manually (credential handles refresh)
- Use environment variables for configuration
Quick Reference Tables
Client Types by Language
| Pattern | Python | .NET | Java | TypeScript | Rust |
| ------- | ------ | ---- | ---- | ---------- | ---- |
| Sync Client | Client | Client | Client | Client | N/A (Async only) |
| Async Client | AsyncClient | N/A (Async methods) | AsyncClient | N/A (Promise) | Client |
| Builder | N/A | N/A | ClientBuilder | N/A | new() or builder (varies by service) |
Pagination Types
| Language | Sync | Async |
| -------- | ---- | ----- |
| Python | ItemPaged[T] | AsyncItemPaged[T] |
| .NET | Pageable<T> | AsyncPageable<T> |
| Java | PagedIterable<T> | PagedFlux<T> |
| TypeScript | N/A | PagedAsyncIterableIterator<T> |
| Rust | N/A | Pager<T> (via futures::TryStreamExt) |
LRO Types
| Language | Sync | Async |
| -------- | ---- | ----- |
| Python | LROPoller[T] | AsyncLROPoller[T] |
| .NET | Operation<T> | Operation<T> |
| Java | SyncPoller<T,U> | PollerFlux<T,U> |
| TypeScript | N/A | PollerLike<T> |
| Rust | N/A | Poller<T> (implements IntoFuture + Stream) |
Response Wrappers
| Language | Single Item | Collection |
| -------- | ----------- | ---------- |
| Python | Direct return | ItemPaged[T] |
| .NET | Response<T> | Pageable<T> |
| Java | Direct return | PagedIterable<T> |
| TypeScript | Promise<T> | PagedAsyncIterableIterator<T> |
| Rust | Response<T> | Pager<T> |
Official Documentation Links
- General Guidelines: https://azure.github.io/azure-sdk/general_introduction.html
- Python: https://azure.github.io/azure-sdk/python_design.html
- .NET: https://azure.github.io/azure-sdk/dotnet_introduction.html
- Java: https://azure.github.io/azure-sdk/java_introduction.html
- TypeScript: https://azure.github.io/azure-sdk/typescript_introduction.html
- Rust: https://azure.github.io/azure-sdk/rust_introduction.html
When creating Azure SDK skills, reference these docs via the microsoft-docs MCP for current API signatures.