Use Claude on Microsoft Foundry

Su Suriya Ravichandran Updated 10 Nov 2026
4 min read ·Lesson 163 of 200

Claude Inside the Microsoft Cloud

Microsoft Foundry is the third platform through which Claude is offered to developers, alongside the direct API, Amazon Bedrock, and Google Cloud's Vertex AI. An organization that runs on Microsoft's cloud, and manages identity through Microsoft Entra ID, can reach Claude through the same resources, billing, and access controls it uses for its other Azure services. The SDK includes a Foundry client for this, and the Messages API you have learned is the interface.

This lesson covers how the Foundry client is created, the two ways it can authenticate, how the resource name determines where requests go, and how to check the configuration for mistakes that are easy to make, including the most serious one: writing a secret into source code.


Resources and Endpoints

A Foundry request is addressed to a resource, which is the Azure object that holds your Claude access. The client builds the address of the service from the resource name, so the name is the one setting that decides where requests go. A wrong name sends the request to the wrong resource, or to none, and the error is typically a not-found or access problem rather than a clear message about the name itself.

The resource name appears in the endpoint address, so it follows the rules for web hostnames: lowercase letters, digits, and hyphens, with no spaces or underscores. A name that fails those rules cannot be a valid endpoint, and the check in this lesson catches it before a request is attempted.


Installing and Creating the Client

Like the other cloud clients, the Foundry client is available with the SDK. The client is created with the resource name, and it reads the credentials from the environment:

from anthropic import AnthropicFoundry

client = AnthropicFoundry(resource="acme-claude")

message = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=256,
    messages=[{"role": "user", "content": "Say hello."}],
)

The model name in this example is an illustration of the call's shape. Model names on Foundry come from the deployments in your resource, so the name must match a deployment that exists there. The Foundry documentation lists the available models and how deployments are named, and that list is the authority.


Two Ways to Authenticate

Foundry accepts two kinds of credential, and the choice depends on how the application runs:

MethodHow it worksSuits
API keyA key for the resource, read from the environment variable ANTHROPIC_FOUNDRY_API_KEYLocal development, and simple deployments with a secret store
Microsoft Entra IDA token issued to a managed identity or a service principalProduction workloads on Azure, where no secret needs to be stored

The API key method is the simplest to start with. Entra ID is generally preferred in production, because the application holds no long-lived secret, and access can be granted and revoked through the identity system. Lesson 164 covers both methods in detail, including where each credential should live.


Validating the Configuration

The configuration check below does two jobs. It verifies that the resource name follows hostname rules, and it refuses a configuration in which the API key is written directly into the code. The second check is the more important one, because a key in source code is copied into version control, into build logs, and into every copy of the project:

"""foundry_config.py: check a Foundry resource name and where the credential comes from."""

import re

RESOURCE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$")


def check_foundry(resource: str, credential_source: str) -> list[str]:
    problems = []
    if not RESOURCE.match(resource):
        problems.append(f"resource name {resource} must use lowercase letters, digits, and hyphens")
    if credential_source == "literal":
        problems.append("API key must not be written in code; use the environment or Entra ID")
    return problems


if __name__ == "__main__":
    cases = [
        ("acme-claude", "environment"),
        ("Acme_Claude", "environment"),
        ("acme-claude", "literal"),
    ]
    for number, (resource, source) in enumerate(cases, start=1):
        print(f"case {number}:", check_foundry(resource, source) or "ok")

Output:

case 1: ok
case 2: ['resource name Acme_Claude must use lowercase letters, digits, and hyphens']
case 3: ['API key must not be written in code; use the environment or Entra ID']

How It Works

  1. The resource pattern follows hostname rules. It requires a lowercase letter or digit at each end, with lowercase letters, digits, or hyphens between them, up to sixty-four characters. Acme_Claude fails on its capital letters and underscore.
  2. The credential check is about where a value comes from, not what it looks like. The configuration states the source, and a literal value is refused, because a literal in code is a secret in the repository.
  3. Each problem names the rule it breaks, so the fix is clear. A developer reading the message knows whether to rename the resource or move the key.
  4. The checks run before the client is created, which means a bad configuration fails at startup, not on the first user request.

Summary

Microsoft Foundry provides Claude through an Azure resource, addressed by a resource name that must follow hostname rules. The Foundry client is created with that name, and it authenticates with either an API key from the environment or a Microsoft Entra ID identity. The most important rule is that the key never appears in code, and the configuration check enforces it. The next lesson covers how to supply credentials to all three platforms safely.

0 Comments

Reviewed before they appear

No comments yet.

Anthropic SDK Using Python
Anthropic SDK Intro Claude API Intro SDK Requirements Install Anthropic SDK Upgrade the SDK Create an API Key Set API Keys Use Environment Variables Import Anthropic Create a Client Send Your First Message Choose a Claude Model Set Max Tokens Read a Response Print Response Text Understand Message Blocks Use System Prompts Send User Messages Set Temperature Handle Stop Reasons Messages API Intro Create Messages Use Message Roles Send Conversation History Continue a Conversation Build a Chat Loop Reset Chat History Use Multiple Turns Inspect Message IDs Read Usage Data Write Clear Prompts Set a System Prompt Add Context to Prompts Use Prompt Templates Add Examples to Prompts Request JSON Output Use XML Tags Control Response Length Improve Prompt Quality Avoid Prompt Injection Read Text Blocks Read Content Blocks Check Stop Reasons Count Input Tokens Count Output Tokens Count Tokens Before Sending Limit Output Tokens Use Stop Sequences Read Request IDs Parse API Responses Streaming Intro Stream Text Output Use Stream Events Use Stream Helpers Get Final Messages Stream Async Responses Handle Stream Errors Build a Live Chat Stream Long Responses Close Streams Safely Build a Chatbot Keep Chat History Manage Chat Sessions Add Chat Memory Build a CLI Chatbot Build a Web Chatbot Use Flask with Claude Use FastAPI with Claude Return JSON from an API Add Chat Error Messages Async SDK Intro Create an Async Client Send Async Messages Use asyncio Run Parallel Requests Stream Async Text Handle Async Errors Set Async Timeouts Close Async Clients Choose Sync or Async Tool Use Intro Define a Tool Create Tool Schemas Send Tools to Claude Read Tool Calls Run Python Tools Return Tool Results Continue After Tool Use Control Tool Choice Handle Tool Errors Use the beta_tool Decorator Create a Tool Runner Add Tool Docstrings Validate Tool Inputs Use Multiple Tools Limit Tool Calls Log Tool Activity Build a Weather Tool Build a Search Tool Build a Calculator Tool Structured Output Intro Request JSON Data Validate JSON Output Use Pydantic Models Handle Invalid JSON Extract Fields from Text Generate Typed Data Use Image URLs Send Base64 Images Read PDFs with Claude Use Output Schemas Build Data Extraction Test Structured Responses Send Image Inputs Upload Files Use File IDs Process Text Files Summarize Documents Extract Table Data Handle File Errors Read Cache Usage Reduce Repeated Input Costs Debug Cache Misses Prompt Caching Intro Enable Prompt Caching Cache System Prompts Cache Long Context Test Cache Performance Use Cache Breakpoints Cache Best Practices Message Batches Intro Create a Message Batch Set Batch IDs Check Batch Status List Message Batches Get Batch Results Process Batch Outputs Handle Failed Batch Items Use Batches for Bulk Tasks Compare Batches and Requests Handle API Errors Handle Rate Limits Retry Failed Requests Set Request Timeouts Handle Network Errors Use Exponential Backoff Build Reliable API Calls Use Extended Thinking Log API Errors Track Request IDs Paginate API Results Set Thinking Budgets Read Thinking Blocks Use Tool Search Use Web Search Tools Use Computer Tools Use Citations Use Token Counting Read Raw Responses Set Custom Headers Use Claude on AWS Bedrock Use Claude on Vertex AI Use Claude on Microsoft Foundry Configure Cloud Credentials Choose a Cloud Provider Compare API Integrations Configure Provider Clients Handle Cloud Errors Use Cloud SDK Extras Deploy Cloud Apps Protect API Keys Use a .env File Ignore Secrets in Git Validate User Input Reduce Prompt Injection Limit Tool Permissions Avoid Unsafe Tool Calls Sanitize Tool Results Set Usage Limits Review Security Logs Test SDK Functions Mock API Responses Test Error Handling Test Streaming Code Measure Token Usage Track API Costs Configure Logging Deploy with Docker Deploy a FastAPI App Monitor Production Apps Build a Claude Chatbot Build a Text Summarizer Build a Code Explainer Build a JSON Extractor Build a PDF Assistant Build a Streaming Chat App Build a Tool-Calling Agent Build a Batch Processor Build a Research Assistant Build a Claude API Dashboard
Ask about this post
AI Ask about this post

Ask questions about Use Claude on Microsoft Foundry and get answers drawn from it.

Signed-in readers only.