Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 57 ยท Infrastructure as Code and DevOps

Azure SDKs: Java, C# and Python Quickstarts

Use the Azure SDKs from Java, C# and Python: DefaultAzureCredential, client objects, pagers, retries, a Cosmos DB example and a Flask translator app, with runnable stand-ins.

The portal and the az CLI are for people. Applications talk to Azure through SDKs, libraries that wrap the REST API in your language. This lesson shows the design they all share and a short quickstart in Java, C# and Python, so you can recognize the pattern whichever Azure service you use next.

Running real SDK code needs credentials and resources, so the Java, C# and Python snippets are read-only. The runnable examples are JavaScript stand-ins for the two behaviors you will use all the time: the credential chain and retry with paging.

The shared design

Microsoft publishes SDKs for .NET, Java, JavaScript, Python and Go that follow common guidelines, so they feel alike:

  • One package per service, such as Azure.Storage.Blobs (C#), azure-storage-blob (Java and Python) or @azure/storage-blob (JavaScript). Add only what you need.
  • A client object per service, built from an endpoint URL and a credential: BlobServiceClient, CosmosClient, SecretClient.
  • A shared identity library (Azure.Identity, azure-identity) whose DefaultAzureCredential finds a credential automatically.
  • Pagers for lists, which fetch pages lazily while you iterate.
  • Built-in retry with backoff for throttling (429) and transient errors, with settings for attempts and timeouts.
  • Long-running operations that return a poller object you wait on.

The main rule is the one from Managed Identities and Service Principals: use the endpoint URL plus an identity, not a connection string with a key. The same code then works on your laptop and in Azure.

DefaultAzureCredential

DefaultAzureCredential tries several sources in order and uses the first that works. Roughly:

  1. Environment variables (a service principal with AZURE_CLIENT_ID, AZURE_TENANT_ID and a secret or certificate).
  2. Workload identity (for Kubernetes pods, see Azure Kubernetes Service).
  3. Managed identity (when running on App Service, Functions, a VM, Container Apps and so on).
  4. Developer tools: Visual Studio, Visual Studio Code, the Azure CLI (az login), Azure PowerShell and the Azure Developer CLI.

The exact list differs by language and SDK version, so read the docs of the version you use. The practical effect: on your laptop it uses the account from az login; in Azure it uses the managed identity; you never change code. The identity must also have an RBAC role on the target (for blobs, Storage Blob Data Contributor; see Role-Based Access Control). A 403 error while authentication succeeded almost always means a missing role assignment.

The chain: a stand-in

JS How a credential chain picks a source

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same program runs in four places without a code change, and the failure message tells you what each source said, which is exactly how to debug a real credential error.

Java quickstart: Blob Storage

Add com.azure:azure-storage-blob and com.azure:azure-identity to your build. This code is read-only here:

Java
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.azure.storage.blob.*;
import com.azure.storage.blob.models.BlobItem;

public class Main {
    public static void main(String[] args) {
        BlobServiceClient service = new BlobServiceClientBuilder()
            .endpoint("https://mydata12345.blob.core.windows.net")
            .credential(new DefaultAzureCredentialBuilder().build())
            .buildClient();

        BlobContainerClient container = service.getBlobContainerClient("reports");
        container.createIfNotExists();

        container.getBlobClient("hello.txt")
            .upload(com.azure.core.util.BinaryData.fromString("Hello from Java"), true);

        for (BlobItem item : container.listBlobs()) {   // a pager: pages are fetched lazily
            System.out.println(item.getName());
        }
    }
}

To deploy a Java web app, package it (a JAR for Spring Boot) and deploy it to App Service or Container Apps; the Maven and Gradle plugins can deploy for you, and the VS Code Azure extensions give a right-click workflow.

C# quickstart: Cosmos DB

Add Microsoft.Azure.Cosmos and Azure.Identity. Cosmos DB supports Entra ID for data access once a data-plane role is assigned (see Azure Cosmos DB):

C#
using Azure.Identity;
using Microsoft.Azure.Cosmos;

var client = new CosmosClient(
    "https://my-cosmos.documents.azure.com:443/",
    new DefaultAzureCredential());

Database db = await client.CreateDatabaseIfNotExistsAsync("shop");
Container orders = await db.CreateContainerIfNotExistsAsync("orders", "/customerId");

await orders.UpsertItemAsync(new { id = "o-1001", customerId = "c-7", total = 42.5 },
                             new PartitionKey("c-7"));

var iterator = orders.GetItemQueryIterator<dynamic>(
    new QueryDefinition("SELECT * FROM c WHERE c.customerId = @id").WithParameter("@id", "c-7"),
    requestOptions: new QueryRequestOptions { PartitionKey = new PartitionKey("c-7") });

while (iterator.HasMoreResults)
{
    foreach (var item in await iterator.ReadNextAsync())
        Console.WriteLine(item);
}

Create one CosmosClient for the whole application and reuse it; it manages connections and is meant to be a singleton. Passing the partition key to the query keeps it on one partition, which is cheaper.

Python quickstart: a Flask translator app

This small Flask app calls the Translator service from the previous AI lesson (Azure AI Services and Azure OpenAI). Read-only, because it needs a key:

Python
import os
import requests
from flask import Flask, request, jsonify

app = Flask(__name__)

ENDPOINT = "https://api.cognitive.microsofttranslator.com/translate"
HEADERS = {
    "Ocp-Apim-Subscription-Key": os.environ["TRANSLATOR_KEY"],
    "Ocp-Apim-Subscription-Region": os.environ["TRANSLATOR_REGION"],
    "Content-Type": "application/json",
}

@app.post("/translate")
def translate():
    data = request.get_json()
    params = {"api-version": "3.0", "to": data.get("to", "de")}
    r = requests.post(ENDPOINT, params=params, headers=HEADERS,
                      json=[{"Text": data["text"]}], timeout=10)
    r.raise_for_status()
    return jsonify(text=r.json()[0]["translations"][0]["text"])

Run it locally with flask run, then deploy the same code to App Service, with the key in an app setting that references Key Vault. Flask itself is taught in the Flask tutorial of this site; here the point is only that the SDK or REST call is a few lines inside a normal web route.

Retries and pagers

Cloud calls fail in transient ways: a throttled request, a dropped connection, a service restart. The SDKs retry automatically, with growing delays, for errors that are worth retrying, and return the error otherwise. Lists are paged: the service returns, say, 100 items and a continuation token, and the SDK's pager asks for the next page only when your loop needs it.

Retry and paging: a stand-in

JS Retry with backoff and a lazy pager

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the [fetched page] lines appear between the items: the pager is lazy, so stopping early saves requests, and the retry hid the first two failures from the loop.

A workflow that scales

A good developer loop with the SDKs is: sign in with az login, develop against a dev resource group, give your identity the data roles it needs, keep endpoints (not secrets) in configuration, then deploy the same code with a managed identity through a pipeline (see CI/CD with GitHub Actions and Azure Pipelines). Visual Studio Code extensions for App Service, Functions and Cosmos DB let you browse resources and deploy from the editor.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use DefaultAzureCredential?

    It tries several credential sources in order, so no code change is needed between environments.
  2. 2. Authentication succeeds but the call returns 403. What is the likeliest cause?

    403 means 'known identity, not allowed'. Assign a data role such as Storage Blob Data Contributor.
  3. 3. How should an application normally create a CosmosClient?

    The client manages connections and caches metadata; creating one per request wastes resources.
  4. 4. What does a pager do?

    Pagers hide continuation tokens and request more data lazily.

Summary

  • Azure SDKs share one design: a package per service, a client built from endpoint plus credential, pagers, retries and pollers.
  • DefaultAzureCredential chooses environment, workload identity, managed identity or developer-tool credentials automatically; the identity still needs an RBAC role.
  • Use endpoints plus identities instead of keys; keep unavoidable secrets in Key Vault.
  • Reuse long-lived clients, pass partition keys, and let the SDK retry transient errors.
  • The same patterns apply in Java, C#, Python, JavaScript and Go.

Next: Azure Key Vault.