One read of Claude Developer Platformapi-20260814T043121Z
565 pages moved out of 565 read.
What this read moved
476-500 of 565, page 20 of 23This capture is too large to show at once. Changes 476-500 of 565 are below, significant first; the rest are on the following screens.
cli-sdks-libraries/middleware First recorded · 178 lines, first recorded
## Registering middleware ## Middleware ordering ## Replacing the HTTP client ## Built-in middleware
The first capture of this source. The page was already there, and this is what it said.
---
title: SDK middleware
url: https://platform.claude.com/docs/en/cli-sdks-libraries/middleware
description: Intercept and modify requests and responses in the Anthropic SDKs.
---
The Anthropic SDKs provide a middleware (or interceptor) hook that lets you run code before a request is sent and after the response is received. Use middleware for cross-cutting concerns such as logging, custom retries, request annotation, and refusal fallback handling.
```mermaid
sequenceDiagram
autonumber
participant App as Your code
participant M1 as Middleware A
participant M2 as Middleware B
participant Core as SDK core
participant API as Claude API
App->>M1: request
M1->>M2: next(request)
M2->>Core: next(request)
Core->>API: HTTP request
API-->>Core: HTTP response
Core-->>M2: response
M2-->>M1: response
M1-->>App: response
```
Each middleware can inspect or replace the request before calling `next()`, and the response after `next()` returns.
## Registering middleware
Each middleware is a function that receives the outgoing request and a `next` callable. Call `next` to forward the request to the rest of the chain (or directly to the SDK core if this is the last middleware), and return its response. Anything before the `next` call runs on the way out; anything after runs on the way back.
<CodeGroup exclude="shell">
```python Python
def logging_middleware(request: APIRequest, call_next: CallNext) -> APIResponse[Any]:
# Before the request
print(f"-> {request.method} {request.url}")
# Forward the request to the rest of the chain
response = call_next(request)
# After the request
print(f"<- {response.status_code}")
return response
client = Anthropic(middleware=[logging_middleware])
```
```typescript TypeScript
import type { Middleware } from "@anthropic-ai/sdk";
const loggingMiddleware: Middleware = async (request, next, ctx) => {
// Before the request
ctx.logger.debug("->", request.method, request.url);
// Forward the request to the rest of the chain
const response = await next(request);
// After the request
ctx.logger.debug("<-", response.status, request.url);
return response;
};
const client = new Anthropic({ middleware: [loggingMiddleware] });
```
```csharp C#
AnthropicClient client = new()
{
Handlers =
[
Handler.Create(async (request, next, cancellationToken) =>
{
// Before the request
Console.WriteLine($"Sending {request.Method} {request.RequestUri}");
// Forward the request to the next handler
var response = await next(request, cancellationToken);
// After the request
Console.WriteLine($"Received {(int)response.StatusCode}");
return response;
}),
],
};
```
```go Go
client := anthropic.NewClient(
option.WithMiddleware(func(req *http.Request, next option.MiddlewareNext) (*http.Response, error) {
// Before the request
start := time.Now()
slog.Info("sending request", "method", req.Method, "url", req.URL)
// Forward the request to the rest of the chain
res, err := next(req)
if err != nil {
return nil, err
}
// After the request
slog.Info("received response", "status", res.StatusCode, "duration", time.Since(start))
return res, nil
}),
)
```
```java Java
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.addInterceptor(Interceptor.syncOnly((nextClient, request, requestOptions) -> {
// Before the request
IO.println(request.method() + " /" + String.join("/", request.pathSegments()));
// Forward the request to the next handler
HttpResponse response = nextClient.execute(request, requestOptions);
// After the request
IO.println(response.statusCode());
return response;
}))
.build();
```
```php PHP
$loggingMiddleware = function (RequestInterface $request, callable $next): ResponseInterface {
// Before the request
error_log("-> {$request->getMethod()} {$request->getUri()}");
// Forward the request to the rest of the chain
$response = $next($request);
// After the request
error_log("<- {$response->getStatusCode()}");
return $response;
};
$client = new Client(requestOptions: ['middleware' => [$loggingMiddleware]]);
```
```ruby Ruby
logging_middleware = lambda do |request, call_next|
# Before the request
puts "-> #{request.method.upcase} #{request.url}"
# Forward the request to the rest of the chain
response = call_next.call(request)
# After the request
puts "<- #{response.status}"
response
end
client = Anthropic::Client.new(middleware: [logging_middleware])
```
</CodeGroup>
## Middleware ordering
When you register multiple middleware, they apply in the order given: the first middleware's "before" code runs first, and its "after" code runs last. Middleware registered on the client runs before middleware passed as a per-request option.
In the Go SDK, repeated `option.WithMiddleware` calls concatenate (client first, then method). In the other SDKs, pass an array; later entries wrap inner.
## Replacing the HTTP client
Each SDK also accepts a custom HTTP client (for proxy configuration, custom TLS, or connection pooling). Only one HTTP client is used per SDK client; setting it replaces the default. The custom HTTP client receives requests after all middleware has run.
## Built-in middleware
The SDKs ship a refusal-fallback middleware that automatically retries requests Claude Fable 5 declines on a fallback model. See [Detect and retry on a fallback model](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#client-side-fallback) for setup and per-language examples.
cli-sdks-libraries/overview First recorded · 87 lines, first recorded
## CLI ## Client SDKs ## Libraries and integrations ## Building agents or using Claude Code?
The first capture of this source. The page was already there, and this is what it said.
---
title: CLI, SDKs, and libraries
url: https://platform.claude.com/docs/en/cli-sdks-libraries/overview
description: "Official tools for building with the Claude API: the ant CLI, client SDKs in seven languages, and framework-specific libraries."
---
Anthropic provides three kinds of official tooling for building with the Claude API:
* **CLI:** The `ant` command-line tool for shell scripting and interactive use.
* **Client SDKs:** General-purpose Messages API clients for Python, TypeScript, C#, Go, Java, PHP, and Ruby. Each SDK provides idiomatic interfaces, type safety, and built-in support for streaming, retries, and error handling.
* **Libraries and integrations:** Packages and compatibility layers that expose Claude inside another framework's API surface rather than the Messages API directly.
<Info>
For the full API specification, see the [API reference](https://platform.claude.com/docs/en/api/overview).
</Info>
## CLI
<CardGroup cols={3}>
<Card title="ant CLI" href="https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart">
Shell scripting, typed flags, response transforms
</Card>
</CardGroup>
## Client SDKs
<CardGroup cols={3}>
<Card title="Python" href="https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python">
Sync and async clients, Pydantic models
</Card>
<Card title="TypeScript" href="https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript">
Node.js, Deno, Bun, and browser support
</Card>
<Card title="C#" href="https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/csharp">
.NET Standard 2.0+, IChatClient integration
</Card>
<Card title="Go" href="https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/go">
Context-based cancellation, functional options
</Card>
<Card title="Java" href="https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java">
Builder pattern, CompletableFuture async
</Card>
<Card title="PHP" href="https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/php">
Value objects, builder pattern
</Card>
<Card title="Ruby" href="https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/ruby">
Sorbet types, streaming helpers
</Card>
</CardGroup>
## Libraries and integrations
Libraries and integrations expose Claude through another framework's API surface. They are not general-purpose Messages API clients.
<CardGroup cols={3}>
<Card title="Apple Foundation Models" href="https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/apple-foundation-models">
Swift package for Apple's `LanguageModelSession` API
</Card>
<Card title="OpenAI SDK compatibility" href="https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/openai-sdk">
Use Claude through the OpenAI SDK surface
</Card>
</CardGroup>
## Building agents or using Claude Code?
The CLI, client SDKs, and libraries are for calling the Claude API yourself: you send each request and handle each response. Claude Code, the Claude Agent SDK, and Claude Managed Agents work at a higher level, providing the agent loop, tool execution, and runtime.
<CardGroup cols={3}>
<Card title="Claude Code" href="https://code.claude.com/docs/en/overview">
Agentic coding tool for delegating coding tasks to Claude
</Card>
<Card title="Claude Agent SDK" href="https://code.claude.com/docs/en/agent-sdk/overview">
Build agents that run in a process you operate
</Card>
<Card title="Claude Managed Agents" href="https://platform.claude.com/docs/en/managed-agents/overview">
Run agents in Anthropic's managed infrastructure
</Card>
</CardGroup>
cli-sdks-libraries/sdks/csharp First recorded · 467 lines, first recorded
## Installation ## Requirements ## Usage ## Client configuration ### Modifying configuration ## Streaming ## Error handling ## Retries ## Timeouts ## Pagination ### Auto-pagination ### Manual pagination ## Response validation ## IChatClient integration ## Requests and responses ## Advanced usage ### Binary responses ### Raw responses ### Logging ### Undocumented API functionality ## Platform integrations ## Semantic versioning ## Additional resources
The first capture of this source. The page was already there, and this is what it said.
---
title: C# SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/csharp
description: Install and configure the Anthropic C# SDK for .NET applications with IChatClient integration
---
The Anthropic C# SDK provides convenient access to the Claude API from applications written in C#.
<Info>
The C# SDK is currently in beta. APIs may change between versions.
</Info>
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers C#-specific SDK features and configuration.
</Info>
<Warning>
As of version 10+, the `Anthropic` package is now the official Anthropic SDK for C#. Package versions 3.X and below were previously used for the tryAGI community-built SDK, which has moved to [`tryAGI.Anthropic`](https://www.nuget.org/packages/tryagi.Anthropic/). If you need to continue using the former client in your project, update your package reference to `tryAGI.Anthropic`.
</Warning>
## Installation
Install the package from [NuGet](https://www.nuget.org/packages/Anthropic):
```bash
dotnet add package Anthropic
```
## Requirements
This library requires .NET Standard 2.0 or later.
## Usage
```csharp
using System;
using Anthropic;
using Anthropic.Models.Messages;
AnthropicClient client = new();
MessageCreateParams parameters = new()
{
MaxTokens = 1024,
Messages =
[
new()
{
Role = Role.User,
Content = "Hello, Claude",
},
],
Model = Model.ClaudeOpus5,
};
var message = await client.Messages.Create(parameters);
foreach (var block in message.Content)
{
if (block.TryPickText(out var textBlock))
{
Console.WriteLine(textBlock.Text);
}
}
```
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
## Client configuration
Configure the client using environment variables:
```csharp
using Anthropic;
// Configured using the ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN and ANTHROPIC_BASE_URL environment variables
AnthropicClient client = new();
```
Or manually:
```csharp
using Anthropic;
AnthropicClient client = new() { ApiKey = "my-anthropic-api-key" };
```
Or using a combination of the two approaches.
See this table for the available options:
| Property | Environment variable | Required | Default value |
| ----------- | ---------------------- | -------- | ----------------------------- |
| `ApiKey` | `ANTHROPIC_API_KEY` | false | - |
| `AuthToken` | `ANTHROPIC_AUTH_TOKEN` | false | - |
| `BaseUrl` | `ANTHROPIC_BASE_URL` | true | `"https://api.anthropic.com"` |
### Modifying configuration
To temporarily use a modified client configuration, while reusing the same connection and thread pools, call `WithOptions` on any client or service:
```csharp
using System;
var message = await client
.WithOptions(options =>
options with
{
BaseUrl = "https://example.com",
Timeout = TimeSpan.FromSeconds(42),
}
)
.Messages.Create(parameters);
Console.WriteLine(message);
```
Using a [`with` expression](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression) makes it easy to construct the modified options.
The `WithOptions` method does not affect the original client or service.
## Streaming
The SDK defines methods that return response "chunk" streams, where each chunk can be individually processed as soon as it arrives instead of waiting on the full response. Streaming methods generally correspond to [SSE](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) or [JSONL](https://jsonlines.org) responses.
A streaming method always has a `Streaming` suffix in its name, even if it doesn't have a non-streaming variant.
These streaming methods return [`IAsyncEnumerable`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.iasyncenumerable-1):
```csharp
using System;
using Anthropic.Models.Messages;
MessageCreateParams parameters = new()
{
MaxTokens = 1024,
Messages =
[
new()
{
Role = Role.User,
Content = "Hello, Claude",
},
],
Model = Model.ClaudeOpus5,
};
await foreach (var message in client.Messages.CreateStreaming(parameters))
{
Console.WriteLine(message);
}
```
## Error handling
The SDK throws custom unchecked exception types:
* `AnthropicApiException`: Base class for API errors. See this table for which exception subclass is thrown for each HTTP status code:
| Status | Exception |
| ------ | ---------------------------------------- |
| 400 | `AnthropicBadRequestException` |
| 401 | `AnthropicUnauthorizedException` |
| 403 | `AnthropicForbiddenException` |
| 404 | `AnthropicNotFoundException` |
| 422 | `AnthropicUnprocessableEntityException` |
| 429 | `AnthropicRateLimitException` |
| 5xx | `Anthropic5xxException` |
| others | `AnthropicUnexpectedStatusCodeException` |
Additionally, all 4xx errors inherit from `Anthropic4xxException`.
* `AnthropicSseException`: thrown for errors encountered during SSE streaming after a successful initial HTTP response.
* `AnthropicIOException`: I/O networking errors.
* `AnthropicInvalidDataException`: Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response.
* `AnthropicException`: Base class for all exceptions.
## Retries
The SDK automatically retries 2 times by default, with a short exponential backoff between requests.
Only the following error types are retried:
* Connection errors (for example, because of a network connectivity problem)
* 408 Request Timeout
* 409 Conflict
* 429 Rate Limit
* 5xx Internal
The API may also explicitly instruct the SDK to retry or not retry a request.
To set a custom number of retries, configure the client using the `MaxRetries` property:
```csharp
using Anthropic;
AnthropicClient client = new() { MaxRetries = 3 };
```
Or configure a single method call using `WithOptions`:
```csharp
using System;
var message = await client
.WithOptions(options =>
options with { MaxRetries = 3 }
)
.Messages.Create(parameters);
Console.WriteLine(message);
```
## Timeouts
Requests time out after 10 minutes by default.
To set a custom timeout, configure the client using the `Timeout` option:
```csharp
using System;
using Anthropic;
AnthropicClient client = new() { Timeout = TimeSpan.FromSeconds(42) };
```
Or configure a single method call using `WithOptions`:
```csharp
using System;
var message = await client
.WithOptions(options =>
options with { Timeout = TimeSpan.FromSeconds(42) }
)
.Messages.Create(parameters);
Console.WriteLine(message);
```
## Pagination
The SDK defines methods that return paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.
### Auto-pagination
To iterate through all results across all pages, use the `Paginate` method, which automatically fetches more pages as needed. The method returns an [`IAsyncEnumerable`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.iasyncenumerable-1):
```csharp
using System;
var page = await client.Messages.Batches.List(parameters);
await foreach (var item in page.Paginate())
{
Console.WriteLine(item);
}
```
### Manual pagination
To access individual page items and manually request the next page, use the `Items` property, and `HasNext` and `Next` methods:
```csharp
var page = await client.Messages.Batches.List();
while (true)
{
foreach (var item in page.Items)
{
Console.WriteLine(item);
}
if (!page.HasNext())
{
break;
}
page = await page.Next();
}
```
## Response validation
In rare cases, the API may return a response that doesn't match the expected type. By default, the SDK does not throw an exception in this case. It throws `AnthropicInvalidDataException` only if you directly access the property.
If you would prefer to check that the response is completely well-typed upfront, then either call `Validate`:
```csharp
var message = await client.Messages.Create(parameters);
message.Validate();
```
Or configure the client using the `ResponseValidation` option:
```csharp
using Anthropic;
AnthropicClient client = new() { ResponseValidation = true };
```
Cut at 300 lines. The page has the rest.
cli-sdks-libraries/sdks/go First recorded · 752 lines, first recorded
## Installation ## Requirements ## Usage ## Request fields ### Request unions ### Deserializing params ## Response objects ### Response unions ## Error handling ## Retries ## Timeouts ## Long requests ## File uploads ## Pagination ## RequestOptions ## HTTP client customization ## Platform integrations ## Advanced usage ### Accessing raw response data (for example, response headers) ### Making custom/undocumented requests #### Undocumented endpoints #### Undocumented request params #### Undocumented response properties ## Semantic versioning ## Additional resources
The first capture of this source. The page was already there, and this is what it said.
---
title: Go SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/go
description: Install and configure the Anthropic Go SDK with context-based cancellation and functional options
---
The Anthropic Go library provides convenient access to the Claude API from applications written in Go.
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers Go-specific SDK features and configuration.
</Info>
## Installation
```go
import (
"github.com/anthropics/anthropic-sdk-go" // imported as anthropic
)
```
Install with `go get`:
```bash
go get github.com/anthropics/anthropic-sdk-go
```
## Requirements
This library requires Go 1.23+.
## Usage
```go
package main
import (
"context"
"fmt"
"github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
)
func main() {
client := anthropic.NewClient(
option.WithAPIKey("my-anthropic-api-key"), // defaults to os.LookupEnv("ANTHROPIC_API_KEY")
)
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("What is a quaternion?")),
},
Model: anthropic.ModelClaudeOpus5,
})
if err != nil {
panic(err.Error())
}
for _, block := range message.Content {
if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
fmt.Println(textBlock.Text)
}
}
}
```
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
<AccordionGroup>
<Accordion title="Conversations">
```go
messages := []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("What is my first name?")),
}
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
Messages: messages,
MaxTokens: 1024,
})
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", message.Content)
messages = append(messages, message.ToParam())
messages = append(messages, anthropic.NewUserMessage(
anthropic.NewTextBlock("My full name is John Doe"),
))
message, err = client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
Messages: messages,
MaxTokens: 1024,
})
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", message.Content)
```
</Accordion>
<Accordion title="System prompts">
```go
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 1024,
System: []anthropic.TextBlockParam{
{Text: "Be very serious at all times."},
},
Messages: messages,
})
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", message.Content)
```
</Accordion>
<Accordion title="Streaming">
```go
content := "What is a quaternion?"
stream := client.Messages.NewStreaming(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 1024,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
},
})
message := anthropic.Message{}
for stream.Next() {
event := stream.Current()
err := message.Accumulate(event)
if err != nil {
panic(err)
}
switch eventVariant := event.AsAny().(type) {
case anthropic.ContentBlockDeltaEvent:
switch deltaVariant := eventVariant.Delta.AsAny().(type) {
case anthropic.TextDelta:
print(deltaVariant.Text)
}
}
}
if stream.Err() != nil {
panic(stream.Err())
}
```
</Accordion>
<Accordion title="Tool calling">
```go
messages := []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock(content)),
}
toolParams := []anthropic.ToolParam{
{
Name: "get_coordinates",
Description: anthropic.String("Accepts a place as an address, then returns the latitude and longitude coordinates."),
InputSchema: GetCoordinatesInputSchema,
},
}
tools := make([]anthropic.ToolUnionParam, len(toolParams))
for i, toolParam := range toolParams {
tools[i] = anthropic.ToolUnionParam{OfTool: &toolParam}
}
for {
message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 1024,
Messages: messages,
Tools: tools,
})
if err != nil {
panic(err)
}
print(color("[assistant]: "))
for _, block := range message.Content {
switch block := block.AsAny().(type) {
case anthropic.TextBlock:
println(block.Text)
println()
case anthropic.ToolUseBlock:
inputJSON, _ := json.Marshal(block.Input)
println(block.Name + ": " + string(inputJSON))
println()
}
}
messages = append(messages, message.ToParam())
toolResults := []anthropic.ContentBlockParamUnion{}
for _, block := range message.Content {
switch variant := block.AsAny().(type) {
case anthropic.ToolUseBlock:
print(color("[user (" + block.Name + ")]: "))
var response interface{}
switch block.Name {
case "get_coordinates":
var input struct {
Location string `json:"location"`
}
err := json.Unmarshal([]byte(variant.JSON.Input.Raw()), &input)
if err != nil {
panic(err)
}
response = GetCoordinates(input.Location)
}
b, err := json.Marshal(response)
if err != nil {
panic(err)
}
println(string(b))
toolResults = append(toolResults, anthropic.NewToolResultBlock(block.ID, string(b), false))
}
}
if len(toolResults) == 0 {
break
}
messages = append(messages, anthropic.NewUserMessage(toolResults...))
}
```
</Accordion>
</AccordionGroup>
## Request fields
The anthropic library uses the [`omitzero`](https://tip.golang.org/doc/go1.24#encodingjsonpkgencodingjson) semantics from the Go 1.24+ `encoding/json` release for request fields.
Required primitive fields (such as `int64` or `string`) feature the tag `` `json:"...,required"` ``. These fields are always serialized, even their zero values.
Optional primitive types are wrapped in a `param.Opt[T]`. These fields can be set with the provided constructors, such as `anthropic.String(string)` or `anthropic.Int(int64)`.
Any `param.Opt[T]`, map, slice, struct or string enum uses the tag `` `json:"...,omitzero"` ``. Its zero value is considered omitted.
The `param.IsOmitted(any)` function can confirm the presence of any `omitzero` field.
```go
p := anthropic.ExampleParams{
ID: "id_xxx", // required property
Name: anthropic.String("..."), // optional property
Point: anthropic.Point{
X: 0, // required field will serialize as 0
Y: anthropic.Int(1), // optional field will serialize as 1
// ... omitted non-required fields will not be serialized
},
Origin: anthropic.Origin{}, // the zero value of [Origin] is considered omitted
}
```
To send `null` instead of a `param.Opt[T]`, use `param.Null[T]()`. To send `null` instead of a struct `T`, use `param.NullStruct[T]()`.
```go
p.Name = param.Null[string]() // 'null' instead of string
p.Point = param.NullStruct[Point]() // 'null' instead of struct
param.IsNull(p.Name) // true
param.IsNull(p.Point) // true
```
Request structs contain a `.SetExtraFields(map[string]any)` method which can send non-conforming fields in the request body. Extra fields overwrite any struct fields with a matching key.
<Warning>
For security reasons, only use `SetExtraFields` with trusted data.
</Warning>
To send a custom value instead of a struct, use the generic function `param.Override` (for example, `param.Override[anthropic.FooParams](12)`).
```go
// In cases where the API specifies a given type,
// but you want to send something else, use [SetExtraFields]:
p.SetExtraFields(map[string]any{
"x": 0.01, // send "x" as a float instead of int
})
// Send a number instead of an object
custom := param.Override[anthropic.FooParams](12)
```
### Request unions
Cut at 300 lines. The page has the rest.
cli-sdks-libraries/sdks/java First recorded · 1280 lines, first recorded
## Installation ## Requirements ## Quick start ## Client configuration ### API key setup ### Configuration options ### Modifying configuration ## Async usage ## Streaming ### Synchronous streaming ### Asynchronous streaming ### Streaming with message accumulator ## Structured outputs ## Tool use ### Defining tools with annotations ### Calling tools ### Tool name conversion ### Local tool JSON schema validation ### Annotating tool classes ## Message batches ## File uploads ### Binary responses ## Error handling ### Status code mapping ## Request IDs ## Retries ## Timeouts ## Long requests ## Pagination ### Auto-pagination ### Manual pagination ## Type system ### Immutability and builders ### Requests and responses ### Undocumented parameters ### JsonValue creation ### Forcibly omitting required parameters ### Response properties ### Response validation ## HTTP client customization ### Proxy configuration ### HTTPS / SSL configuration ### Custom HTTP client #### Customized OkHttpClient #### Completely custom HTTP client ## Platform integrations ## Advanced usage ### Raw response access ### Logging ### Undocumented API functionality #### Undocumented request parameters #### Undocumented response properties #### New or unreleased enum values ## Beta features ## Frequently asked questions ## Semantic versioning ## Additional resources
The first capture of this source. The page was already there, and this is what it said.
---
title: Java SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/java
description: Install and configure the Anthropic Java SDK with builder patterns and async support
---
The Anthropic Java SDK provides convenient access to the Claude API from applications written in Java. It uses the builder pattern for creating requests and supports both synchronous and asynchronous operations.
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers Java-specific SDK features and configuration.
</Info>
## Installation
<Tabs>
<Tab title="Gradle">
```kotlin
implementation("com.anthropic:anthropic-java:2.53.0")
```
</Tab>
<Tab title="Maven">
```xml
<dependency>
<groupId>com.anthropic</groupId>
<artifactId>anthropic-java</artifactId>
<version>2.53.0</version>
</dependency>
```
</Tab>
</Tabs>
## Requirements
This library requires Java 8 or later.
<Note>
The SDK supports Java 8 and later. Code examples in this documentation are written as [JDK 25 compact source files](https://openjdk.org/jeps/512), using a bare `void main()` entry point and `IO.println()` for output. The API calls themselves are identical on every supported JDK; to compile an example on an earlier version, replace `IO.println(...)` with `System.out.println(...)` and place the body inside `public static void main(String[] args)` within a class.
</Note>
## Quick start
```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
// Configures using the `anthropic.apiKey`, `anthropic.authToken` and `anthropic.baseUrl` system properties
// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL` environment variables
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_5)
.build();
Message message = client.messages().create(params);
```
## Client configuration
### API key setup
Configure the client using system properties or environment variables:
```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
// Configures using the `anthropic.apiKey`, `anthropic.authToken` and `anthropic.baseUrl` system properties
// Or configures using the `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_BASE_URL` environment variables
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
```
Or configure manually:
```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.apiKey("my-anthropic-api-key")
.build();
```
Or use a combination of both approaches:
```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
// Configures using system properties or environment variables
.fromEnv()
.apiKey("my-anthropic-api-key")
.build();
```
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
### Configuration options
| Setter | System property | Environment variable | Required | Default value |
| ----------- | --------------------- | ---------------------- | -------- | ----------------------------- |
| `apiKey` | `anthropic.apiKey` | `ANTHROPIC_API_KEY` | false | - |
| `authToken` | `anthropic.authToken` | `ANTHROPIC_AUTH_TOKEN` | false | - |
| `baseUrl` | `anthropic.baseUrl` | `ANTHROPIC_BASE_URL` | true | `"https://api.anthropic.com"` |
System properties take precedence over environment variables.
<Tip>
Don't create more than one client in the same application. Each client has a connection pool and thread pools, which are more efficient to share between requests.
</Tip>
### Modifying configuration
To temporarily use a modified client configuration while reusing the same connection and thread pools, call `withOptions()` on any client or service:
```java
import com.anthropic.client.AnthropicClient;
AnthropicClient clientWithOptions = client.withOptions(optionsBuilder -> {
optionsBuilder.baseUrl("https://example.com");
optionsBuilder.maxRetries(42);
});
```
The `withOptions()` method does not affect the original client or service.
## Async usage
The default client is synchronous. To switch to asynchronous execution, call the `async()` method:
```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_5)
.build();
CompletableFuture<Message> message = client.async().messages().create(params);
```
Or create an asynchronous client from the beginning:
```java
import com.anthropic.client.AnthropicClientAsync;
import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_5)
.build();
CompletableFuture<Message> message = client.messages().create(params);
```
The asynchronous client supports the same options as the synchronous one, except most methods return `CompletableFuture`s.
## Streaming
The SDK defines methods that return response "chunk" streams, where each chunk can be individually processed as soon as it arrives instead of waiting on the full response.
### Synchronous streaming
These streaming methods return `StreamResponse` for synchronous clients:
```java
import com.anthropic.core.http.StreamResponse;
import com.anthropic.models.messages.RawMessageStreamEvent;
try (StreamResponse<RawMessageStreamEvent> streamResponse = client.messages().createStreaming(params)) {
streamResponse.stream().forEach(chunk -> {
IO.println(chunk);
});
IO.println("No more chunks!");
}
```
### Asynchronous streaming
For asynchronous clients, the method returns `AsyncStreamResponse`:
```java
import com.anthropic.core.http.AsyncStreamResponse;
import com.anthropic.models.messages.RawMessageStreamEvent;
client.async().messages().createStreaming(params).subscribe(chunk -> {
IO.println(chunk);
});
// If you need to handle errors or completion of the stream
client.async().messages().createStreaming(params).subscribe(new AsyncStreamResponse.Handler<>() {
@Override
public void onNext(RawMessageStreamEvent chunk) {
IO.println(chunk);
}
@Override
public void onComplete(Optional<Throwable> error) {
if (error.isPresent()) {
IO.println("Something went wrong!");
throw new RuntimeException(error.get());
} else {
IO.println("No more chunks!");
}
}
});
// Or use futures
client.async().messages().createStreaming(params)
.subscribe(chunk -> {
IO.println(chunk);
})
.onCompleteFuture()
.whenComplete((unused, error) -> {
if (error != null) {
IO.println("Something went wrong!");
throw new RuntimeException(error);
} else {
IO.println("No more chunks!");
}
});
```
Async streaming uses a dedicated per-client cached thread pool `Executor` to stream without blocking the current thread. To use a different `Executor`:
```java
Executor executor = Executors.newFixedThreadPool(4);
client.async().messages().createStreaming(params).subscribe(
chunk -> IO.println(chunk), executor
);
```
Or configure the client globally using the `streamHandlerExecutor` method:
```java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.streamHandlerExecutor(Executors.newFixedThreadPool(4))
.build();
```
### Streaming with message accumulator
A `MessageAccumulator` can record the stream of events in the response as they are processed and accumulate a `Message` object similar to what would have been returned by the non-streaming API.
For a synchronous response, add a `Stream.peek()` call to the stream pipeline to accumulate each event:
```java
import com.anthropic.core.http.StreamResponse;
import com.anthropic.helpers.MessageAccumulator;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.RawMessageStreamEvent;
MessageAccumulator messageAccumulator = MessageAccumulator.create();
try (StreamResponse<RawMessageStreamEvent> streamResponse =
client.messages().createStreaming(createParams)) {
streamResponse.stream()
.peek(messageAccumulator::accumulate)
.flatMap(event -> event.contentBlockDelta().stream())
.flatMap(deltaEvent -> deltaEvent.delta().text().stream())
.forEach(textDelta -> IO.print(textDelta.text()));
}
Message message = messageAccumulator.message();
```
For an asynchronous response, add the `MessageAccumulator` to the `subscribe()` call:
```java
import com.anthropic.helpers.MessageAccumulator;
import com.anthropic.models.messages.Message;
MessageAccumulator messageAccumulator = MessageAccumulator.create();
client.async().messages()
.createStreaming(createParams)
.subscribe(event -> messageAccumulator.accumulate(event).contentBlockDelta().stream()
Cut at 300 lines. The page has the rest.
cli-sdks-libraries/sdks/php First recorded · 248 lines, first recorded
## Installation ## Requirements ## Usage ## Value objects ## Streaming ## Error handling ## Retries ## Pagination ## Advanced usage ### Undocumented properties ### Undocumented request parameters ### Undocumented endpoints ## Platform integrations ## Semantic versioning ## Additional resources
The first capture of this source. The page was already there, and this is what it said.
---
title: PHP SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/php
description: Install and configure the Anthropic PHP SDK with value objects and builder patterns
---
The Anthropic PHP library provides convenient access to the Claude API from any PHP 8.1.0+ application.
<Info>
The PHP SDK is currently in beta. APIs might change between versions.
</Info>
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers PHP-specific SDK features and configuration.
</Info>
## Installation
The SDK uses [PSR-18](https://www.php-fig.org/psr/psr-18/) for HTTP and discovers any installed PSR-18 client automatically. [Guzzle](https://docs.guzzlephp.org/) is recommended because the SDK configures it for streaming with no additional setup:
```bash
composer require "anthropic-ai/sdk" "guzzlehttp/guzzle:^7"
```
## Requirements
PHP 8.1.0 or higher.
## Usage
This library uses named parameters to specify optional arguments. Parameters with a default value must be set by name.
```php
$client = new Client();
$message = $client->messages->create(
maxTokens: 1024,
messages: [['role' => 'user', 'content' => 'Hello, Claude']],
model: 'claude-opus-5',
);
$textBlock = array_find($message->content, static fn ($block): bool => $block->type === 'text');
echo $textBlock->text;
```
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
## Value objects
It is recommended to use the static `with` constructor `Base64ImageSource::with(data: "U3RhaW5sZXNzIHJvY2tz", ...)` and named parameters to initialize value objects.
However, builders are also provided `(new Base64ImageSource)->withData("U3RhaW5sZXNzIHJvY2tz")`.
## Streaming
The SDK provides support for streaming responses using Server-Sent Events (SSE).
```php
$client = new Client();
$stream = $client->messages->createStream(
maxTokens: 1024,
messages: [['role' => 'user', 'content' => 'Hello, Claude']],
model: 'claude-opus-5',
);
foreach ($stream as $event) {
echo $event->type . PHP_EOL;
}
```
Streaming requires an HTTP client that returns the response body incrementally. When Guzzle is the discovered PSR-18 client, the SDK configures it for streaming automatically. With a buffering client, the `foreach` loop yields every event at once when the response completes instead of incrementally; if you observe that symptom, install Guzzle or supply a streaming-capable PSR-18 client through the `streamingTransporter` request option:
```php
$client = new Anthropic\Client(
requestOptions: Anthropic\RequestOptions::with(streamingTransporter: $myStreamingClient),
);
```
## Error handling
When the library is unable to connect to the API, or if the API returns a non-success status code (that is, a 4xx or 5xx response), a subclass of `Anthropic\Core\Exceptions\APIException` is thrown:
```php
<?php
// ...
use Anthropic\Core\Exceptions\APIConnectionException;
use Anthropic\Core\Exceptions\APIStatusException;
use Anthropic\Core\Exceptions\RateLimitException;
// ...
try {
$message = $client->messages->create(
maxTokens: 1024,
messages: [['role' => 'user', 'content' => 'Hello, Claude']],
model: 'claude-opus-5',
);
} catch (APIConnectionException $e) {
echo "The server could not be reached", PHP_EOL;
echo $e->getPrevious()?->getMessage(), PHP_EOL;
} catch (RateLimitException $_) {
echo "A 429 status code was received; we should back off a bit.", PHP_EOL;
} catch (APIStatusException $e) {
echo "Another non-200-range status code was received", PHP_EOL;
echo $e->getMessage();
}
```
Error codes are as follows:
| Cause | Error Type |
| ---------------- | ------------------------------ |
| HTTP 400 | `BadRequestException` |
| HTTP 401 | `AuthenticationException` |
| HTTP 403 | `PermissionDeniedException` |
| HTTP 404 | `NotFoundException` |
| HTTP 409 | `ConflictException` |
| HTTP 422 | `UnprocessableEntityException` |
| HTTP 429 | `RateLimitException` |
| HTTP >= 500 | `InternalServerException` |
| Other HTTP error | `APIStatusException` |
| Timeout | `APITimeoutException` |
| Network error | `APIConnectionException` |
## Retries
Certain errors are automatically retried two times by default, with a short exponential backoff.
Connection errors (for example, because of a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts are all retried by default.
You can use the `maxRetries` option to configure or disable this:
```php
use Anthropic\RequestOptions;
// ...
// Configure the default for all requests:
$client = new Client(requestOptions: RequestOptions::with(maxRetries: 0));
// Or, configure per-request:
$result = $client->messages->create(
maxTokens: 1024,
messages: [['role' => 'user', 'content' => 'Hello, Claude']],
model: 'claude-opus-5',
requestOptions: RequestOptions::with(maxRetries: 5),
);
```
## Pagination
List methods in the Claude API are paginated.
This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:
```php
$client = new Client();
$page = $client->beta->messages->batches->list(limit: 20);
// fetch items from the current page
foreach ($page->getItems() as $item) {
echo $item->id, PHP_EOL;
}
// make additional network requests to fetch items from all pages, including and after the current page
foreach ($page->pagingEachItem() as $item) {
echo $item->id, PHP_EOL;
}
```
## Advanced usage
### Undocumented properties
You can send undocumented parameters to any endpoint, and read undocumented response properties, as follows:
<Note>
The `extra*` parameters of the same name override the documented parameters.
</Note>
```php
<?php
// ...
use Anthropic\RequestOptions;
// ...
$message = $client->messages->create(
maxTokens: 1024,
messages: [['role' => 'user', 'content' => 'Hello, Claude']],
model: 'claude-opus-5',
requestOptions: RequestOptions::with(
extraQueryParams: ['my_query_parameter' => 'value'],
extraBodyParams: ['my_body_parameter' => 'value'],
extraHeaders: ['my-header' => 'value'],
),
);
```
### Undocumented request parameters
If you want to explicitly send an extra parameter, you can do so with the `extraQueryParams`, `extraBodyParams`, and `extraHeaders` options under `RequestOptions::with()` when making a request, as seen in the preceding example.
### Undocumented endpoints
To make requests to undocumented endpoints while retaining the benefit of authentication, retries, and other client features, you can make requests using `client->request`, as follows:
```php
$client = new Client();
$response = $client->request(
method: "post",
path: '/undocumented/endpoint',
query: ['dog' => 'woof'],
headers: ['useful-header' => 'interesting-value'],
body: ['hello' => 'world']
);
```
## Platform integrations
<Note>
For detailed platform setup guides with code examples, see:
* [Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock)
* [Amazon Bedrock (Opus 4.6 and earlier)](https://platform.claude.com/docs/en/build-with-claude/claude-on-amazon-bedrock-legacy)
* [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws)
* [Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai)
* [Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry)
</Note>
The PHP SDK supports the following platforms:
* **Agent Platform:** `Anthropic\Vertex\Client`. Use `::fromEnvironment()`.
* **Bedrock:** `Anthropic\Bedrock\MantleClient`. Use `new MantleClient(awsRegion: ...)`.
* **Bedrock (legacy):** `Anthropic\Bedrock\Client`. Use `::fromEnvironment()` or `::withCredentials()`.
* **Claude Platform on AWS:** `Anthropic\Aws\Client` (requires `aws/aws-sdk-php` as a soft dependency). Use `new Anthropic\Aws\Client(workspaceId: ...)` or set `ANTHROPIC_AWS_WORKSPACE_ID`. Available in beta.
* **Foundry:** `Anthropic\Foundry\Client`. Use `::withCredentials()`.
Use `MantleClient` for new projects; `Anthropic\Bedrock\Client` remains for existing applications using the Bedrock `InvokeModel` API.
## Semantic versioning
This package follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions. As the library is in initial development and has a major version of `0`, APIs might change at any time.
This package considers improvements to the (non-runtime) PHPDoc type definitions to be non-breaking changes.
## Additional resources
* [GitHub repository](https://github.com/anthropics/anthropic-sdk-php)
* [Packagist](https://packagist.org/packages/anthropic-ai/sdk)
* [API reference](https://platform.claude.com/docs/en/api/overview)
* [Streaming Messages](https://platform.claude.com/docs/en/build-with-claude/streaming)
cli-sdks-libraries/sdks/python First recorded · 790 lines, first recorded
## Installation ## Requirements ## Usage ## Async usage ### Using aiohttp for better concurrency ## Streaming responses ### Streaming helpers ## Token counting ## Tool use ### Tool helpers ## Message batches ### Creating a batch ### Getting results from a batch ## File uploads ## Handling errors ## Request IDs ## Retries ## Timeouts ## Long requests ## Auto-pagination ## Default headers ## Type system ### Request parameters ### Response models ### Handling null vs missing fields ## Advanced usage ### Accessing raw response data (for example, headers) ### Streaming response body ### Logging ### Making custom/undocumented requests #### Undocumented endpoints #### Undocumented request params #### Undocumented response properties ### Configuring the HTTP client ### Managing HTTP resources ## Beta features ## Platform integrations ## Semantic versioning ### Determining the installed version ## Additional resources
The first capture of this source. The page was already there, and this is what it said.
---
title: Python SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python
description: Install and configure the Anthropic Python SDK with sync and async client support
---
The Anthropic Python SDK provides convenient access to the Claude API from Python applications. It supports both synchronous and asynchronous operations, streaming, and integrations with Amazon Bedrock, Claude Platform on AWS, Google Cloud, and Microsoft Foundry.
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers Python-specific SDK features and configuration.
</Info>
## Installation
```bash
pip install anthropic
```
For platform-specific integrations or improved async performance, install with extras:
```bash
# For Amazon Bedrock support
pip install "anthropic[bedrock]"
# For Google Cloud support
pip install "anthropic[vertex]"
# For Claude Platform on AWS support
pip install "anthropic[aws]"
# Microsoft Foundry support is included in the base package
# For improved async performance with aiohttp
pip install "anthropic[aiohttp]"
```
## Requirements
Python 3.9 or later is required.
## Usage
```python
import os
from anthropic import Anthropic
client = Anthropic(
# This is the default and can be omitted
api_key=os.environ.get("ANTHROPIC_API_KEY"),
)
message = client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
)
for block in message.content:
if block.type == "text":
print(block.text)
```
<Tip>
Consider using [python-dotenv](https://pypi.org/project/python-dotenv/) to add `ANTHROPIC_API_KEY="my-anthropic-api-key"` to your `.env` file so that your API key isn't stored in source control.
</Tip>
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
## Async usage
```python
import os
import asyncio
from anthropic import AsyncAnthropic
client = AsyncAnthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY"),
)
async def main() -> None:
message = await client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
)
print(message.content)
asyncio.run(main())
```
### Using aiohttp for better concurrency
For improved async performance, you can use the `aiohttp` HTTP backend instead of the default `httpx`:
```python
import os
import asyncio
from anthropic import AsyncAnthropic, DefaultAioHttpClient
async def main() -> None:
async with AsyncAnthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY"),
http_client=DefaultAioHttpClient(),
) as client:
message = await client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
)
print(message.content)
asyncio.run(main())
```
## Streaming responses
The SDK provides support for streaming responses using Server-Sent Events (SSE).
```python
client = Anthropic()
stream = client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
stream=True,
)
for event in stream:
print(event.type)
```
The async client uses the exact same interface:
```python
client = AsyncAnthropic()
stream = await client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
stream=True,
)
async for event in stream:
print(event.type)
```
### Streaming helpers
The SDK also provides streaming helpers that use context managers and provide access to the accumulated text and the final message:
```python
async def main() -> None:
async with client.messages.stream(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Say hello there!",
}
],
model="claude-opus-5",
) as stream:
async for text in stream.text_stream:
print(text, end="", flush=True)
print()
message = await stream.get_final_message()
print(message.to_json())
asyncio.run(main())
```
Streaming with `client.messages.stream(...)` exposes various helpers including accumulation and SDK-specific events.
Alternatively, you can use `client.messages.create(..., stream=True)` which only returns an iterable of the events in the stream and uses less memory (it doesn't build up a final message object for you).
## Token counting
You can see the exact usage for a given request through the `usage` response property:
```python
message = client.messages.create(...)
print(message.usage)
# Usage(input_tokens=25, output_tokens=13)
```
You can also count tokens before making a request:
```python
count = client.messages.count_tokens(
model="claude-opus-5", messages=[{"role": "user", "content": "Hello, world"}]
)
print(count.input_tokens) # 10
```
## Tool use
This SDK provides support for tool use, also known as function calling. For more details, see [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).
### Tool helpers
The SDK provides helpers for defining and running tools as pure Python functions. The `@beta_tool` decorator generates the tool schema from the function signature and docstring:
```python
import json
from anthropic import Anthropic, beta_tool
client = Anthropic()
@beta_tool
def get_weather(location: str) -> str:
"""Get the weather for a given location.
Args:
location: The city and state, for example, San Francisco, CA
Returns:
A JSON-encoded string with the location, temperature, and weather condition.
"""
return json.dumps(
{
"location": location,
"temperature": "68°F",
"condition": "Sunny",
}
)
# Use the tool_runner to automatically handle tool calls
runner = client.beta.messages.tool_runner(
max_tokens=1024,
model="claude-opus-5",
tools=[get_weather],
messages=[
{"role": "user", "content": "What is the weather in SF?"},
],
)
for message in runner:
print(message)
```
On every iteration, an API request is made. If the response includes a call to one of the given tools, the tool is automatically called, and the result is returned directly to the model in the next iteration.
## Message batches
This SDK provides support for [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) under `client.messages.batches`.
### Creating a batch
Message Batches takes an array of requests, where each object has a `custom_id` identifier and the same request `params` as the standard Messages API:
```python
client.messages.batches.create(
requests=[
{
"custom_id": "my-first-request",
"params": {
"model": "claude-opus-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello, world"}],
},
},
{
"custom_id": "my-second-request",
"params": {
"model": "claude-opus-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hi again, friend"}],
},
},
Cut at 300 lines. The page has the rest.
cli-sdks-libraries/sdks/ruby First recorded · 416 lines, first recorded
## Installation ## Requirements ## Usage ## Streaming ### Streaming helpers ## Input schema and tool calling ## Structured outputs ## Handling errors ## Retries ## Timeouts ## Pagination ## File uploads ## Sorbet ### Enums ## BaseModel ## Concurrency and connection pooling ## Making custom or undocumented requests ### Undocumented properties ### Undocumented request params ### Undocumented endpoints ## Platform integrations ## Semantic versioning ## Additional resources
The first capture of this source. The page was already there, and this is what it said.
---
title: Ruby SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/ruby
description: Install and configure the Anthropic Ruby SDK with Sorbet types, streaming helpers, and connection pooling
---
The Anthropic Ruby library provides convenient access to the Claude API from any Ruby 3.2.0+ application. It ships with comprehensive types and docstrings in Yard, RBS, and RBI. The standard library's `net/http` is used as the HTTP transport, with connection pooling through the `connection_pool` gem.
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers Ruby-specific SDK features and configuration.
</Info>
## Installation
Add the gem to your application's `Gemfile` with Bundler:
```bash
bundle add anthropic
```
## Requirements
Ruby 3.2.0 or higher.
## Usage
```ruby
anthropic = Anthropic::Client.new(
api_key: ENV["ANTHROPIC_API_KEY"] # This is the default and can be omitted
)
message = anthropic.messages.create(
max_tokens: 1024,
messages: [{role: "user", content: "Hello, Claude"}],
model: :"claude-opus-5"
)
message.content.each do |block|
puts block.text if block.type == :text
end
```
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
## Streaming
The SDK provides support for streaming responses using Server-Sent Events (SSE).
```ruby
anthropic = Anthropic::Client.new
stream = anthropic.messages.stream(
max_tokens: 1024,
messages: [{role: "user", content: "Hello, Claude"}],
model: :"claude-opus-5"
)
stream.each do |message|
puts(message.type)
end
```
### Streaming helpers
This library provides several conveniences for streaming messages, for example:
```ruby
anthropic = Anthropic::Client.new
stream = anthropic.messages.stream(
max_tokens: 1024,
messages: [{role: :user, content: "Say hello there!"}],
model: :"claude-opus-5"
)
stream.text.each do |text|
print(text)
end
```
Streaming with `anthropic.messages.stream(...)` exposes various helpers including accumulation and SDK-specific events.
## Input schema and tool calling
The SDK provides helper mechanisms to define structured data classes for tools and let Claude automatically execute them. For detailed documentation on tool use patterns including the tool runner, see [Tool Runner (SDK)](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-runner).
```ruby
anthropic = Anthropic::Client.new
class CalculatorInput < Anthropic::BaseModel
required :lhs, Float
required :rhs, Float
required :operator, Anthropic::InputSchema::EnumOf[:+, :-, :*, :/]
end
class Calculator < Anthropic::BaseTool
input_schema CalculatorInput
def call(expr)
expr.lhs.public_send(expr.operator, expr.rhs)
end
end
# Automatically handles tool execution loop
anthropic.beta.messages.tool_runner(
model: "claude-opus-5",
max_tokens: 1024,
messages: [{role: "user", content: "What's 15 * 7?"}],
tools: [Calculator.new]
).each_message { |message| puts message.content }
```
## Structured outputs
For complete structured outputs documentation including Ruby examples, see [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs).
## Handling errors
When the library is unable to connect to the API, or if the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of `Anthropic::Errors::APIError` is raised:
```ruby
anthropic = Anthropic::Client.new
begin
message = anthropic.messages.create(
max_tokens: 1024,
messages: [{role: "user", content: "Hello, Claude"}],
model: :"claude-opus-5"
)
rescue Anthropic::Errors::APIConnectionError => e
puts("The server could not be reached")
puts(e.cause) # an underlying Exception, likely raised within `net/http`
rescue Anthropic::Errors::RateLimitError => e
puts("A 429 status code was received; we should back off a bit.")
rescue Anthropic::Errors::APIStatusError => e
puts("Another non-200-range status code was received")
puts(e.status)
end
```
Error codes are as follows:
| Cause | Error Type |
| ---------------- | -------------------------- |
| HTTP 400 | `BadRequestError` |
| HTTP 401 | `AuthenticationError` |
| HTTP 403 | `PermissionDeniedError` |
| HTTP 404 | `NotFoundError` |
| HTTP 409 | `ConflictError` |
| HTTP 422 | `UnprocessableEntityError` |
| HTTP 429 | `RateLimitError` |
| HTTP >= 500 | `InternalServerError` |
| Other HTTP error | `APIStatusError` |
| Timeout | `APITimeoutError` |
| Network error | `APIConnectionError` |
## Retries
Certain errors will be automatically retried 2 times by default, with a short exponential backoff.
Connection errors (for example, because of a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, >=500 Internal errors, and timeouts are all retried by default.
You can use the `max_retries` option to configure or disable this:
```ruby
# Configure the default for all requests:
anthropic = Anthropic::Client.new(
max_retries: 0 # default is 2
)
# Or, configure per-request:
anthropic.messages.create(
max_tokens: 1024,
messages: [{role: "user", content: "Hello, Claude"}],
model: :"claude-opus-5",
request_options: {max_retries: 5}
)
```
## Timeouts
By default, requests time out after 10 minutes. You can use the `timeout` option to configure this:
```ruby
# Configure the default for all requests:
anthropic = Anthropic::Client.new(
timeout: 20 # 20 seconds (default is 10 minutes)
)
# Or, configure per-request:
anthropic.messages.create(
max_tokens: 1024,
messages: [{role: "user", content: "Hello, Claude"}],
model: :"claude-opus-5",
request_options: {timeout: 5}
)
```
On timeout, `Anthropic::Errors::APITimeoutError` is raised.
Note that requests that time out are retried by default.
## Pagination
List methods in the Claude API are paginated.
This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:
```ruby
anthropic = Anthropic::Client.new
page = anthropic.messages.batches.list(limit: 20)
# Fetch single item from page.
batch = page.data[0]
puts(batch.id)
# Automatically fetches more pages as needed.
page.auto_paging_each do |batch|
puts(batch.id)
end
```
Alternatively, you can use the `#next_page?` and `#next_page` methods for more granular control working with pages.
```ruby
anthropic = Anthropic::Client.new
page = anthropic.messages.batches.list(limit: 20)
loop do
page.data&.each { |batch| puts(batch.id) }
break unless page.next_page?
page = page.next_page
end
```
## File uploads
Request parameters that correspond to file uploads can be passed as raw contents, a [`Pathname`](https://rubyapi.org/3.2/o/pathname) instance, [`StringIO`](https://rubyapi.org/3.2/o/stringio), or more.
```ruby
anthropic = Anthropic::Client.new
require "pathname"
# Use `Pathname` to send the filename and/or avoid paging a large file into memory:
file_metadata = anthropic.beta.files.upload(file: Pathname("/path/to/file"))
# Alternatively, pass file contents or a `StringIO` directly:
file_metadata = anthropic.beta.files.upload(file: File.read("/path/to/file"))
# Or, to control the filename and/or content type:
file = Anthropic::FilePart.new(File.read("/path/to/file"), filename: "/path/to/file", content_type: "...")
file_metadata = anthropic.beta.files.upload(file: file)
puts(file_metadata.id)
```
Note that you can also pass a raw `IO` descriptor, but this disables retries, as the library can't be sure if the descriptor is a file or pipe (which cannot be rewound).
## Sorbet
This library provides comprehensive [RBI](https://sorbet.org/docs/rbi) definitions, and has no dependency on sorbet-runtime.
You can provide typesafe request parameters like so:
```ruby
anthropic = Anthropic::Client.new
anthropic.messages.create(
max_tokens: 1024,
messages: [Anthropic::MessageParam.new(role: "user", content: "Hello, Claude")],
model: :"claude-opus-5"
)
```
Or, equivalently:
```ruby
anthropic = Anthropic::Client.new
# Hashes work, but are not typesafe:
anthropic.messages.create(
max_tokens: 1024,
messages: [{role: "user", content: "Hello, Claude"}],
model: :"claude-opus-5"
)
# You can also splat a full Params class:
params = Anthropic::MessageCreateParams.new(
max_tokens: 1024,
messages: [Anthropic::MessageParam.new(role: "user", content: "Hello, Claude")],
model: :"claude-opus-5"
)
anthropic.messages.create(**params)
```
### Enums
Since this library does not depend on `sorbet-runtime`, it cannot provide [`T::Enum`](https://sorbet.org/docs/tenum) instances. Instead, the SDK provides "tagged symbols", which is always a primitive at runtime:
```ruby
# :auto
puts(Anthropic::MessageCreateParams::ServiceTier::AUTO)
# Revealed type: `T.all(Anthropic::MessageCreateParams::ServiceTier, Symbol)`
T.reveal_type(Anthropic::MessageCreateParams::ServiceTier::AUTO)
```
Cut at 300 lines. The page has the rest.
cli-sdks-libraries/sdks/typescript First recorded · 812 lines, first recorded
## Installation ## Requirements ## Usage ## Request and response types ## Counting tokens ## Streaming responses ## Streaming helpers ## Tool helpers ### Tool errors ## Tool use ## MCP helpers ### MCP error handling ## Message batches ### Creating a batch ### Getting results from a batch ## File uploads ## Handling errors ## Request IDs ## Retries ## Timeouts ## Long requests ## Auto-pagination ## Default headers ## Advanced usage ### Accessing raw Response data (for example, headers) ### Logging #### Log levels #### Custom logger ### Making custom/undocumented requests #### Undocumented endpoints #### Undocumented request parameters #### Undocumented response properties ### Customizing the fetch client ### Fetch options ### Configuring proxies ## Beta features ## Runtime support ## Platform integrations ## Semantic versioning ## Frequently asked questions ## Additional resources
The first capture of this source. The page was already there, and this is what it said.
---
title: TypeScript SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript
description: Install and configure the Anthropic TypeScript SDK for Node.js, Deno, Bun, and browser environments
---
This library provides convenient access to the Claude API from TypeScript or JavaScript.
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers TypeScript-specific SDK features and configuration.
</Info>
## Installation
```bash
npm install @anthropic-ai/sdk
```
## Requirements
TypeScript >= 4.9 is supported.
The following runtimes are supported:
* Node.js 20 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions.
* Deno v1.28.0 or higher.
* Bun 1.0 or later.
* Cloudflare Workers.
* Vercel Edge Runtime.
* Jest 28 or greater with the `"node"` environment (`"jsdom"` is not supported at this time).
* Nitro v2.6 or greater.
* Web browsers: disabled by default to avoid exposing your secret API credentials (see [API key best practices](https://support.claude.com/en/articles/9767949-api-key-best-practices-keeping-your-keys-safe-and-secure)). Enable browser support by explicitly setting `dangerouslyAllowBrowser` to `true`.
Note that React Native is not supported at this time.
If you are interested in other runtime environments, open or upvote an issue on the [GitHub repository](https://github.com/anthropics/anthropic-sdk-typescript).
## Usage
```typescript
const client = new Anthropic({
apiKey: process.env["ANTHROPIC_API_KEY"] // This is the default and can be omitted
});
const message = await client.messages.create({
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }],
model: "claude-opus-5"
});
for (const block of message.content) {
if (block.type === "text") {
console.log(block.text);
}
}
```
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
## Request and response types
This library includes TypeScript definitions for all request parameters and response fields. You may import and use them like so:
```typescript
const client = new Anthropic({
apiKey: process.env["ANTHROPIC_API_KEY"] // This is the default and can be omitted
});
const params: Anthropic.MessageCreateParams = {
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }],
model: "claude-opus-5"
};
const message: Anthropic.Message = await client.messages.create(params);
```
Documentation for each method, request parameter, and response field is available in docstrings and appears on hover in most modern editors.
## Counting tokens
You can see the exact usage for a given request through the `usage` response property, for example:
```typescript
const message = await client.messages.create(/* ... */);
console.log(message.usage);
// { input_tokens: 25, output_tokens: 13 }
```
## Streaming responses
The SDK provides support for streaming responses using Server Sent Events (SSE).
```typescript
const client = new Anthropic();
const stream = await client.messages.create({
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }],
model: "claude-opus-5",
stream: true
});
for await (const messageStreamEvent of stream) {
console.log(messageStreamEvent.type);
}
```
If you need to cancel a stream, you can `break` from the loop or call `stream.controller.abort()`.
## Streaming helpers
This library provides several conveniences for streaming messages, for example:
```typescript
const anthropic = new Anthropic();
const stream = anthropic.messages
.stream({
model: "claude-opus-5",
max_tokens: 1024,
messages: [
{
role: "user",
content: "Say hello there!"
}
]
})
.on("text", (text) => {
console.log(text);
});
const message = await stream.finalMessage();
console.log(message);
```
Streaming with `client.messages.stream(...)` exposes various helpers for your convenience including event handlers and accumulation.
Alternatively, you can use `client.messages.create({ ..., stream: true })` which only returns an async iterable of the events in the stream and thus uses less memory (it does not build up a final message object for you).
## Tool helpers
This SDK provides helpers for making it easy to create and run tools in the Messages API. You can use Zod schemas or JSON Schemas to describe the input to a tool. You can then run those tools using the `client.beta.messages.toolRunner()` method. This method handles passing the inputs generated by the chosen model into the right tool and passing the result back to the model.
For more details on tool use, see [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).
```typescript
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";
const anthropic = new Anthropic();
const weatherTool = betaZodTool({
name: "get_weather",
inputSchema: z.object({
location: z.string()
}),
description: "Get the current weather in a given location",
run: (input) => {
return `The weather in ${input.location} is foggy and 60°F`;
}
});
const finalMessage = await anthropic.beta.messages.toolRunner({
model: "claude-opus-5",
max_tokens: 1000,
messages: [{ role: "user", content: "What is the weather in San Francisco?" }],
tools: [weatherTool]
});
console.log(finalMessage.content);
```
### Tool errors
To report an error from a tool back to the model, throw a `ToolError` from the `run` function. Unlike a plain `Error`, `ToolError` accepts content blocks, allowing you to include images or other structured content in the error response:
```typescript
import { ToolError } from "@anthropic-ai/sdk/lib/tools/BetaRunnableTool";
const screenshotTool = betaZodTool({
name: "take_screenshot",
inputSchema: z.object({ url: z.string() }),
run: async (input) => {
if (!isValidUrl(input.url)) {
throw new ToolError(`Invalid URL: ${input.url}`);
}
const result = await takeScreenshot(input.url);
if (result.error) {
// Include the error screenshot so the model can see what went wrong
throw new ToolError([
{ type: "text", text: `Failed to load page: ${result.error}` },
{
type: "image",
source: { type: "base64", data: result.screenshot, media_type: "image/png" }
}
]);
}
return {
type: "image",
source: { type: "base64", data: result.screenshot, media_type: "image/png" }
};
}
});
```
If a plain `Error` is thrown, the message will be converted to a text content block.
## Tool use
This SDK provides support for tool use, also known as function calling. For more details, see [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).
## MCP helpers
This SDK provides helpers for integrating with [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers. These helpers convert MCP types to Claude API types, reducing boilerplate when working with MCP tools, prompts, and resources.
<Tip>
The Claude API also supports an [`mcp_servers` parameter](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector) that lets Claude connect directly to remote MCP servers. Use `mcp_servers` when you have remote servers accessible by URL and only need tool support. Use the MCP helpers when you need local MCP servers, prompts, resources, or more control over the MCP connection.
</Tip>
```typescript
import {
mcpTools,
mcpMessages,
mcpResourceToContent,
mcpResourceToFile
} from "@anthropic-ai/sdk/helpers/beta/mcp";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const anthropic = new Anthropic();
// Connect to an MCP server
const transport = new StdioClientTransport({ command: "mcp-server", args: [] });
const mcpClient = new Client({ name: "my-client", version: "1.0.0" });
await mcpClient.connect(transport);
// Use MCP prompts
const { messages } = await mcpClient.getPrompt({ name: "my-prompt" });
const response = await anthropic.beta.messages.create({
model: "claude-opus-5",
max_tokens: 1024,
messages: mcpMessages(messages)
});
console.log(response.content);
// Use MCP tools with toolRunner
const { tools } = await mcpClient.listTools();
const finalMessage = await anthropic.beta.messages.toolRunner({
model: "claude-opus-5",
max_tokens: 1024,
messages: [{ role: "user", content: "Use the available tools" }],
tools: mcpTools(tools, mcpClient)
});
console.log(finalMessage.content);
// Use MCP resources as content
const resource = await mcpClient.readResource({ uri: "file:///path/to/doc.txt" });
await anthropic.beta.messages.create({
model: "claude-opus-5",
max_tokens: 1024,
messages: [
{
role: "user",
content: [
mcpResourceToContent(resource),
{ type: "text", text: "Summarize this document" }
]
}
]
});
// Upload MCP resources as files
const fileResource = await mcpClient.readResource({ uri: "file:///path/to/data.json" });
await anthropic.beta.files.upload({ file: mcpResourceToFile(fileResource) });
```
### MCP error handling
The conversion functions throw `UnsupportedMCPValueError` if an MCP value isn't supported by the Claude API (for example, unsupported content type, unsupported MIME type, non-http/https resource link).
## Message batches
This SDK provides support for [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) under the `client.messages.batches` namespace.
### Creating a batch
Message Batches takes an array of requests, where each object has a `custom_id` identifier, and the exact same request `params` as the standard Messages API:
```typescript
const batch = await client.messages.batches.create({
requests: [
{
custom_id: "my-first-request",
params: {
model: "claude-opus-5",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, world" }]
}
},
{
custom_id: "my-second-request",
Cut at 300 lines. The page has the rest.
get-api-key First recorded · 47 lines, first recorded
## Create an API key ## Use your API key ## API keys and the Admin API
The first capture of this source. The page was already there, and this is what it said.
---
title: Get your Claude API key
url: https://platform.claude.com/docs/en/get-api-key
description: Find, create, and manage your API keys for the Claude API in the Claude Console.
---
API keys for the Claude API (also called Anthropic API keys) live in the Claude Console. To view your existing keys or create a new one, go to [Settings → API keys](https://platform.claude.com/settings/keys).
## Create an API key
<Steps>
<Step title="Sign in to the Claude Console">
Go to [platform.claude.com](https://platform.claude.com/) and sign in, or create an account if you don't have one yet.
</Step>
<Step title="Open the API keys page">
Go to [Settings → API keys](https://platform.claude.com/settings/keys).
</Step>
<Step title="Create a key">
Click **Create key**, then give the key a name. You can also choose a [workspace](https://platform.claude.com/settings/workspaces) to scope the key to, and an expiration.
</Step>
<Step title="Copy and store the key">
The Console shows the full key, which starts with `sk-ant-`, only once, at creation. Copy it and store it somewhere safe, such as a secrets manager. If you lose a key, you can't view it again in the Console. Create a new key instead.
</Step>
</Steps>
If the **Create key** button is disabled, you may not have permission to create keys in that workspace. Ask an organization admin to grant you access or to create a key for you.
## Use your API key
Set the key as an environment variable:
```bash
export ANTHROPIC_API_KEY="sk-ant-api03-..."
```
The [client SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) read `ANTHROPIC_API_KEY` automatically. Direct HTTP requests send the key in the `x-api-key` header. To make your first request, follow the [Quickstart](https://platform.claude.com/docs/en/get-started), and see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication) for the full picture, including short-lived credentials with Workload Identity Federation.
## API keys and the Admin API
The [Admin API](https://platform.claude.com/docs/en/api/admin) includes endpoints for managing your organization's API keys programmatically, such as [Retrieve API Key](https://platform.claude.com/docs/en/api/admin/api_keys/retrieve) and [List API Keys](https://platform.claude.com/docs/en/api/admin/api_keys/list). These endpoints are for organization admins automating key management. They require a separate [Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys), and they never return a key's secret value, only a partially redacted hint.
<Note>
The Admin API can't recover a lost key or give you a key to call the Claude API with. To get a usable API key, create one in [Settings → API keys](https://platform.claude.com/settings/keys) in the Claude Console.
</Note>
get-started First recorded · 679 lines, first recorded
## Prerequisites ## Call the API ## Next steps
The first capture of this source. The page was already there, and this is what it said.
---
title: Get started with Claude
url: https://platform.claude.com/docs/en/get-started
description: Make your first API call to Claude and build a simple web search assistant.
---
## Prerequisites
* A [Claude Console account](https://platform.claude.com)
* An [API key](https://platform.claude.com/settings/keys)
## Call the API
<Tabs>
<Tab title="cURL">
<Steps>
<Step title="Set your API key">
Export your API key as an environment variable. The cURL command below reads it from `$ANTHROPIC_API_KEY`.
```bash
export ANTHROPIC_API_KEY="your-api-key-here"
```
</Step>
<Step title="Make your first API call">
Send a `POST` request to the Messages API:
```bash cURL
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5",
"max_tokens": 1000,
"messages": [
{
"role": "user",
"content": "What should I search for to find the latest developments in renewable energy?"
}
]
}'
```
Claude returns a JSON response containing the assistant's message:
```json Output
{
"model": "claude-opus-5",
"id": "msg_013mHbppMPd2PrVJzGMZPt2D",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Here are some effective search strategies to find the latest developments in renewable energy:\n\n## General Search Terms\n- \"Renewable energy news 2025\"\n- ..."
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"stop_details": null,
"usage": {
"input_tokens": 21,
"output_tokens": 305
}
}
```
</Step>
</Steps>
</Tab>
<Tab title="CLI">
<Steps>
<Step title="Install the CLI">
Install the Anthropic CLI with Homebrew:
```bash
brew install anthropics/tap/ant
```
For other installation methods, see [Installation](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart#installation) in the CLI quickstart.
</Step>
<Step title="Authenticate">
Log in with your Anthropic account:
```bash
ant auth login
```
This opens a browser-based OAuth flow. After authorizing, confirm your credential with:
```bash
ant auth status
```
On a remote host without a browser, pass `--no-browser` to get a URL you can open on another device, then paste the returned code back into the terminal. If `ANTHROPIC_API_KEY` is set in your environment, it takes precedence over the login credentials. For non-interactive environments such as CI, see [CLI authentication options](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication).
</Step>
<Step title="Make your first API call">
Run `ant messages create` from your terminal:
```bash CLI
ant messages create \
--model claude-opus-5 \
--max-tokens 1000 \
--message '{
role: user,
content: "What should I search for to find the latest developments in renewable energy?"
}'
```
The CLI prints the JSON response:
```json Output
{
"model": "claude-opus-5",
"id": "msg_01N1ycuCkM5Mzd7WhTU4fwST",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Here are some effective search strategies to find the latest developments in renewable energy:\n\n## General Search Terms\n- \"Renewable energy news 2025\"\n- ..."
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"stop_details": null,
"usage": { "input_tokens": 21, "output_tokens": 305 }
}
```
</Step>
</Steps>
</Tab>
<Tab title="Python">
<Steps>
<Step title="Set your API key">
Export your API key as an environment variable. The SDK reads `ANTHROPIC_API_KEY` automatically.
```bash
export ANTHROPIC_API_KEY="your-api-key-here"
```
</Step>
<Step title="Create a project and install the SDK">
```bash
mkdir claude-quickstart && cd claude-quickstart
python3 -m venv .venv && source .venv/bin/activate
pip install anthropic
```
</Step>
<Step title="Create your code">
Create a file called `quickstart.py`:
```python Python
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-opus-5",
max_tokens=1000,
messages=[
{
"role": "user",
"content": "What should I search for to find the latest developments in renewable energy?",
}
],
)
for block in message.content:
if block.type == "text":
print(block.text)
```
</Step>
<Step title="Run your code">
```bash
python quickstart.py
```
```text Output wrap
Here are some effective search strategies to find the latest developments in renewable energy:
## General Search Terms
- "Renewable energy news 2025"
- ...
```
</Step>
</Steps>
</Tab>
<Tab title="TypeScript">
<Steps>
<Step title="Set your API key">
Export your API key as an environment variable. The SDK reads `ANTHROPIC_API_KEY` automatically.
```bash
export ANTHROPIC_API_KEY="your-api-key-here"
```
</Step>
<Step title="Create a project and install the SDK">
```bash
mkdir claude-quickstart && cd claude-quickstart
npm init -y
npm pkg set type=module
npm install @anthropic-ai/sdk
```
</Step>
<Step title="Create your code">
Create a file called `quickstart.ts`:
```typescript TypeScript
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const message = await client.messages.create({
model: "claude-opus-5",
max_tokens: 1000,
messages: [
{
role: "user",
content: "What should I search for to find the latest developments in renewable energy?"
}
]
});
for (const block of message.content) {
if (block.type === "text") {
console.log(block.text);
}
}
```
</Step>
<Step title="Run your code">
```bash
npx tsx quickstart.ts
```
```text Output wrap
Here are some effective search strategies to find the latest developments in renewable energy:
## General Search Terms
- "Renewable energy news 2025"
- ...
```
</Step>
</Steps>
</Tab>
<Tab title="C#">
<Steps>
<Step title="Set your API key">
Export your API key as an environment variable. The SDK reads `ANTHROPIC_API_KEY` automatically.
```bash
export ANTHROPIC_API_KEY="your-api-key-here"
```
</Step>
<Step title="Create a project and install the SDK">
Create a new console project and add the Anthropic package:
```bash
dotnet new console -n ClaudeQuickstart
cd ClaudeQuickstart
dotnet add package Anthropic
```
</Step>
<Step title="Create your code">
Replace the contents of `Program.cs`:
```csharp C#
using Anthropic;
using Anthropic.Models.Messages;
var client = new AnthropicClient();
var message = await client.Messages.Create(new MessageCreateParams
{
Model = Model.ClaudeOpus5,
MaxTokens = 1000,
Messages =
[
new()
{
Role = Role.User,
Content = "What should I search for to find the latest developments in renewable energy?",
},
],
});
Cut at 300 lines. The page has the rest.
home First recorded · 280 lines, first recorded
The first capture of this source. The page was already there, and this is what it said.
---
title: Documentation
url: https://platform.claude.com/docs/en/home
description: Claude API Documentation
---
<HomePage>
<HomeHero
eyebrow="Claude Platform"
title="Start building
with Claude"
subtitle="Everything you need to integrate Claude into your applications. From first API call to production."
>
<HomeQuickChip icon="Play" href="https://platform.claude.com/docs/en/get-started">
Quickstart
</HomeQuickChip>
<HomeQuickChip icon="Key" href="https://platform.claude.com/settings/keys">
Get API key
</HomeQuickChip>
<HomeQuickChip icon="CodeBrackets" href="https://platform.claude.com/docs/en/api/overview">
API reference
</HomeQuickChip>
</HomeHero>
<HomeSection>
<HomeSectionHeader label="Platform" title="Choose how you build" description="Pick the developer surface that matches your approach, and the infrastructure that fits your stack." />
<HomePlatformCards>
<HomePlatformCard title="Messages" description="Direct model access. You construct every turn, manage conversation state, and write your own tool loop." pictogram="code-terminal">
<HomeCardLink icon="play" href="https://platform.claude.com/docs/en/get-started">
Quickstart
</HomeCardLink>
<HomeCardLink icon="book" href="https://platform.claude.com/docs/en/api/messages/create">
API reference
</HomeCardLink>
<HomeCardLink icon="code-brackets" href="https://platform.claude.com/docs/en/api/client-sdks">
Client SDKs
</HomeCardLink>
</HomePlatformCard>
<HomePlatformCard title="Managed Agents" description="Fully managed agent infrastructure. Deploy and manage autonomous agents in stateful sessions with persistent event history." pictogram="clouds">
<HomeCardLink icon="play" href="https://platform.claude.com/docs/en/managed-agents/quickstart">
Quickstart
</HomeCardLink>
<HomeCardLink icon="book" href="https://platform.claude.com/docs/en/api/beta/sessions">
API reference
</HomeCardLink>
<HomeCardLink icon="brain" href="https://platform.claude.com/docs/en/managed-agents/agent-setup">
Define your agent
</HomeCardLink>
</HomePlatformCard>
</HomePlatformCards>
<HomePartnerLinks label="Claude is also available on these cloud platforms:">
<HomeCloudPartnerLink icon="cloud" href="https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock">
Amazon Bedrock
</HomeCloudPartnerLink>
<HomeCloudPartnerLink icon="cloud" href="https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai">
Google Cloud
</HomeCloudPartnerLink>
<HomeCloudPartnerLink icon="cloud" href="https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry">
Microsoft Foundry
</HomeCloudPartnerLink>
</HomePartnerLinks>
</HomeSection>
<HomeSection>
<HomeSectionHeader label="Developer journey" title="From idea to production" description="Follow the lifecycle or jump to what you need." />
<HomeJourney>
<HomeJourneyTab label="Messages">
<HomeJourneyStep title="Get started">
<HomeJourneyLink icon="play" href="https://platform.claude.com/docs/en/get-started">
Quickstart
</HomeJourneyLink>
<HomeJourneyLink icon="lock" href="https://platform.claude.com/settings/keys">
Get API key
</HomeJourneyLink>
<HomeJourneyLink icon="settings" href="https://platform.claude.com/docs/en/about-claude/models/overview">
Choose a model
</HomeJourneyLink>
<HomeJourneyLink icon="code-brackets" href="https://platform.claude.com/docs/en/api/client-sdks">
Install an SDK
</HomeJourneyLink>
<HomeJourneyLink icon="message" href="https://platform.claude.com/playground">
Try the Workbench
</HomeJourneyLink>
</HomeJourneyStep>
<HomeJourneyStep title="Build">
<HomeJourneyLink icon="message" href="https://platform.claude.com/docs/en/api/messages/create">
Messages API
</HomeJourneyLink>
<HomeJourneyLink icon="brain" href="https://platform.claude.com/docs/en/build-with-claude/thinking">
Thinking
</HomeJourneyLink>
<HomeJourneyLink icon="image" href="https://platform.claude.com/docs/en/build-with-claude/vision">
Vision
</HomeJourneyLink>
<HomeJourneyLink icon="tool" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview">
Tool use
</HomeJourneyLink>
<HomeJourneyLink icon="compass" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool">
Web search
</HomeJourneyLink>
<HomeJourneyLink icon="code" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool">
Code execution
</HomeJourneyLink>
<HomeJourneyLink icon="database" href="https://platform.claude.com/docs/en/build-with-claude/structured-outputs">
Structured outputs
</HomeJourneyLink>
<HomeJourneyLink icon="lightning" href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">
Prompt caching
</HomeJourneyLink>
<HomeJourneyLink icon="wifi-high" href="https://platform.claude.com/docs/en/build-with-claude/streaming">
Streaming
</HomeJourneyLink>
</HomeJourneyStep>
<HomeJourneyStep title="Evaluate and ship">
<HomeJourneyLink icon="lightbulb" href="https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview">
Prompting best practices
</HomeJourneyLink>
<HomeJourneyLink icon="chart" href="https://platform.claude.com/docs/en/test-and-evaluate/develop-tests">
Run evals
</HomeJourneyLink>
<HomeJourneyLink icon="stack" href="https://platform.claude.com/docs/en/build-with-claude/batch-processing">
Batch testing
</HomeJourneyLink>
<HomeJourneyLink icon="verified" href="https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/increase-consistency">
Safety and guardrails
</HomeJourneyLink>
<HomeJourneyLink icon="bolt" href="https://platform.claude.com/docs/en/api/rate-limits">
Rate limits and errors
</HomeJourneyLink>
<HomeJourneyLink icon="calculator" href="https://platform.claude.com/docs/en/about-claude/pricing">
Cost optimization
</HomeJourneyLink>
</HomeJourneyStep>
<HomeJourneyStep title="Operate">
<HomeJourneyLink icon="settings" href="https://platform.claude.com/docs/en/build-with-claude/workspaces">
Workspaces and admin
</HomeJourneyLink>
<HomeJourneyLink icon="lock" href="https://platform.claude.com/settings/keys">
API key management
</HomeJourneyLink>
<HomeJourneyLink icon="chart" href="https://platform.claude.com/docs/en/build-with-claude/usage-cost-api">
Usage monitoring
</HomeJourneyLink>
<HomeJourneyLink icon="settings" href="https://platform.claude.com/docs/en/about-claude/models/migration-guide">
Model migration
</HomeJourneyLink>
</HomeJourneyStep>
</HomeJourneyTab>
<HomeJourneyTab label="Managed Agents">
<HomeJourneyStep title="Get started">
<HomeJourneyLink icon="play" href="https://platform.claude.com/docs/en/managed-agents/quickstart">
Quickstart
</HomeJourneyLink>
<HomeJourneyLink icon="lock" href="https://platform.claude.com/settings/keys">
Get API key
</HomeJourneyLink>
<HomeJourneyLink icon="message" href="https://platform.claude.com/docs/en/managed-agents/onboarding">
Build in Console
</HomeJourneyLink>
</HomeJourneyStep>
<HomeJourneyStep title="Define your agent">
<HomeJourneyLink icon="brain" href="https://platform.claude.com/docs/en/managed-agents/agent-setup">
Agent setup
</HomeJourneyLink>
<HomeJourneyLink icon="tool" href="https://platform.claude.com/docs/en/managed-agents/tools">
Tools
</HomeJourneyLink>
<HomeJourneyLink icon="lock" href="https://platform.claude.com/docs/en/managed-agents/permission-policies">
Tool permissions
</HomeJourneyLink>
</HomeJourneyStep>
<HomeJourneyStep title="Run sessions">
<HomeJourneyLink icon="wifi-high" href="https://platform.claude.com/docs/en/managed-agents/events-and-streaming">
Streaming and events
</HomeJourneyLink>
<HomeJourneyLink icon="code-brackets" href="https://platform.claude.com/docs/en/api/beta/sessions">
Sessions API reference
</HomeJourneyLink>
</HomeJourneyStep>
<HomeJourneyStep title="Operate">
<HomeJourneyLink icon="settings" href="https://platform.claude.com/docs/en/build-with-claude/workspaces">
Workspaces and admin
</HomeJourneyLink>
<HomeJourneyLink icon="lock" href="https://platform.claude.com/settings/keys">
API key management
</HomeJourneyLink>
<HomeJourneyLink icon="chart" href="https://platform.claude.com/docs/en/build-with-claude/usage-cost-api">
Usage monitoring
</HomeJourneyLink>
</HomeJourneyStep>
</HomeJourneyTab>
</HomeJourney>
</HomeSection>
<HomeSection>
<HomeSectionHeader label="Models" title="The Claude model family" description="Choose the right model for your use case." />
<HomeModelCards>
<HomeModelCard name="Fable 5" badge="Most capable" modelId="claude-fable-5" description="Highest capability for the most demanding reasoning and long-horizon agentic work." href="https://platform.claude.com/docs/en/about-claude/models/overview" />
<HomeModelCard name="Opus 5" badge="Advanced" modelId="claude-opus-5" description="Excellent for complex analysis, coding, and creative tasks requiring deep reasoning." href="https://platform.claude.com/docs/en/about-claude/models/overview" />
<HomeModelCard name="Sonnet 5" badge="Best balance" modelId="claude-sonnet-5" description="Ideal balance of intelligence and speed for most production workloads." href="https://platform.claude.com/docs/en/about-claude/models/overview" />
<HomeModelCard name="Haiku 4.5" badge="Fastest" modelId="claude-haiku-4-5" description="Lightning-fast responses for high-volume, latency-sensitive applications." href="https://platform.claude.com/docs/en/about-claude/models/overview" />
</HomeModelCards>
</HomeSection>
<HomeSection last>
<HomeSectionHeader label="Resources" title="Keep learning" />
<CardGroup cols={3}>
<Card icon="graduation-cap" title="Courses" href="https://anthropic.skilljar.com/">
Interactive courses to master Claude.
</Card>
<Card icon="book" title="Cookbook" href="https://platform.claude.com/cookbook">
Code samples and patterns.
</Card>
<Card icon="play" title="Quickstarts" href="https://github.com/anthropics/anthropic-quickstarts">
Deployable starter apps.
</Card>
<Card icon="star" title="What's new" href="https://platform.claude.com/docs/en/release-notes/overview">
Latest features and updates.
</Card>
<Card icon="terminal" title="Claude Code" href="https://code.claude.com/docs">
An agentic coding assistant in your terminal.
</Card>
</CardGroup>
</HomeSection>
</HomePage>
intro First recorded · 118 lines, first recorded
## Recommended path for new developers ## Develop with Claude ## Key capabilities ## Support
The first capture of this source. The page was already there, and this is what it said.
---
title: Intro to Claude
url: https://platform.claude.com/docs/en/intro
description: Claude is a highly performant, trustworthy, and intelligent AI platform built by Anthropic. Claude excels at tasks involving language, reasoning, analysis, coding, and more.
---
<Tip>
The latest generation of Claude models:
**Claude Fable 5** - Next-generation intelligence for long-running agents. Read the [Claude Fable 5 and Claude Mythos 5 announcement](https://www.anthropic.com/news/claude-fable-5-mythos-5).
**Claude Mythos 5** - Shares Claude Fable 5's capabilities without the safety classifiers. Available in limited release through [Project Glasswing](https://anthropic.com/glasswing).
**Claude Opus 5** - For complex agentic coding and enterprise work. Read the [Claude Opus 5 announcement](https://www.anthropic.com/news/claude-opus-5).
**Claude Sonnet 5** - Frontier intelligence at scale, built for coding, agents, and enterprise workflows. Read the [Claude Sonnet 5 announcement](https://www.anthropic.com/news/claude-sonnet-5).
**Claude Haiku 4.5** - Fastest model with near-frontier intelligence. Read the [Claude Haiku 4.5 announcement](https://www.anthropic.com/news/claude-haiku-4-5).
</Tip>
<Note>
Looking to chat with Claude? Visit [claude.ai](https://claude.ai).
</Note>
Anthropic offers two ways to build with Claude, each suited to different use cases:
| | Messages API | Claude Managed Agents |
| -------------- | ------------------------------------------- | ------------------------------------------------------------------------- |
| **What it is** | Direct model prompting access | Pre-built, configurable agent harness that runs in managed infrastructure |
| **Best for** | Custom agent loops and fine-grained control | Long-running tasks and asynchronous work |
To learn more about each, see [Using the Messages API](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) and the [Claude Managed Agents overview](https://platform.claude.com/docs/en/managed-agents/overview).
## Recommended path for new developers
Follow these steps to go from zero to a working Claude integration.
<Steps>
<Step title="Make your first API call">
Set up your environment, install an SDK, and send your first message to Claude.
[Go to the quickstart](https://platform.claude.com/docs/en/get-started)
</Step>
<Step title="Secure your credentials">
Set an expiration when you create your API key. Keep the key out of source control, client-side code, and prompts. Check whether your workload can use Workload Identity Federation instead of a static key.
[Read the authentication guide](https://platform.claude.com/docs/en/manage-claude/authentication)
</Step>
<Step title="Understand the Messages API">
Learn the core request and response structure, including multi-turn conversations, system prompts, and stop reasons.
[Read the Messages API guide](https://platform.claude.com/docs/en/build-with-claude/working-with-messages)
</Step>
<Step title="Choose the right model">
Compare Claude models by capability and cost to pick the best fit for your use case.
[See the models overview](https://platform.claude.com/docs/en/about-claude/models/overview)
</Step>
<Step title="Explore features and tools">
Discover what Claude can do: extended thinking, web search, file handling, structured outputs, and more.
[Browse the features overview](https://platform.claude.com/docs/en/build-with-claude/overview)
</Step>
</Steps>
***
## Develop with Claude
Anthropic provides developer tools to help you build and scale applications with Claude.
<CardGroup cols={3}>
<Card title="Developer Console" icon="computer" href="https://platform.claude.com/">
Prototype and test prompts in your browser with the Workbench.
</Card>
<Card title="API Reference" icon="code" href="https://platform.claude.com/docs/en/api/overview">
Explore the full Claude API and client SDK documentation.
</Card>
<Card title="Claude Cookbook" icon="chef-hat" href="https://platform.claude.com/cookbook">
Learn with interactive Jupyter notebooks covering PDFs, embeddings, and more.
</Card>
</CardGroup>
***
## Key capabilities
Claude can assist with many tasks that involve text, code, and images.
<CardGroup cols={2}>
<Card title="Text and code generation" icon="text-aa" href="https://platform.claude.com/docs/en/build-with-claude/overview">
Summarize text, answer questions, extract data, translate text, and explain and generate code.
</Card>
<Card title="Vision" icon="image" href="https://platform.claude.com/docs/en/build-with-claude/vision">
Process and analyze visual input and generate text and code from images.
</Card>
</CardGroup>
***
## Support
<CardGroup cols={2}>
<Card title="Help Center" icon="help" href="https://support.claude.com/en/">
Find answers to frequently asked account and billing questions.
</Card>
<Card title="Service Status" icon="chart" href="https://status.claude.com">
Check the status of Anthropic services.
</Card>
</CardGroup>
manage-claude/access-transparency First recorded · 243 lines, first recorded
## How Access Transparency works ## What Access Transparency covers ## What Access Transparency does not cover ## Getting started ## Receiving Access Transparency events ## CMEK content preservation ## Reason codes ## Surface eligibility ## Limitations and exclusions ### Coverage timing ### Notification timing ### Automated processing does not generate access events ### Access Transparency does not change what Anthropic can access ### CMEK key-use logs are not a per-read record ## Frequently asked questions ## Related resources
The first capture of this source. The page was already there, and this is what it said.
---
title: Access Transparency
url: https://platform.claude.com/docs/en/manage-claude/access-transparency
description: Receive an audit record of human access to your organization's data by Anthropic personnel through the Compliance API.
---
Learn how Access Transparency creates a record of human access to your organization's data by Anthropic personnel, what it covers, and how to receive events through the Compliance API.
<Note>
When Access Transparency is enabled for your organization:
* Each human view of your retained data (see [covered content](https://platform.claude.com/docs/en/manage-claude/access-transparency#what-access-transparency-covers)) by an Anthropic employee writes an `anthropic_access` activity to your [Compliance API Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed).
* Access occurs only for safety review or incident response. See [Reason codes](https://platform.claude.com/docs/en/manage-claude/access-transparency#reason-codes).
Access Transparency is available to eligible customers on request and is not self-serve. For eligibility, refer to your contract terms or contact your Anthropic account representative.
</Note>
## How Access Transparency works
Anthropic personnel access customer content only under defined conditions. Access Transparency is designed to make such access visible to you. The design rests on the following principles:
* **Human access happens only under a published reason code.**
* **Human views of your covered content are recorded.** Anthropic's internal tooling that can reach your covered content is instrumented to emit an event on each view.
* **Events represent human access, not automated processing.** Anthropic's automated safety systems process your content in a secured pipeline with no interactive human access; that processing does not generate `anthropic_access` events. The one event automated processing can initiate is a `cmek_preserve` preservation record (see [CMEK content preservation](https://platform.claude.com/docs/en/manage-claude/access-transparency#cmek-content-preservation)).
* **Events arrive on your existing feed.** Activities are accessible through your [Compliance API Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed). Existing credentials, audit, export, and SIEM integrations for the Compliance API will still apply.
## What Access Transparency covers
* **Covered content:** Access Transparency covers prompt and response content sent through the Claude Messages API or Claude Code sessions. Anthropic's [general ZDR documentation](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention) and [ZDR for Claude Code documentation](https://code.claude.com/docs/en/zero-data-retention) explain which APIs and features are covered by ZDR. The same APIs and features are covered by Access Transparency.
* **Manual views by Anthropic personnel:** Manual views of your covered content by Anthropic reviewers generate events.
## What Access Transparency does not cover
* **Automated processing:** Model serving, safety classifiers, and abuse-detection pipelines process your content as part of normal operation and do not generate `anthropic_access` events. Preservation initiated by automated processing does generate a `cmek_preserve` event (see [CMEK content preservation](https://platform.claude.com/docs/en/manage-claude/access-transparency#cmek-content-preservation)).
* **Your own organization's activity:** Your API calls, admin actions, and Compliance API reads are covered by standard [Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed) event types.
* **Claude for Enterprise and Claude Apps:** claude.ai Enterprise seats, Claude for Work, Cowork, and Claude in Chrome are not covered.
* **Claude consumer products:** Claude Free, Pro, or Max plans.
* **Partner-operated platforms:** Amazon Bedrock and Google Cloud; refer to those platforms' transparency controls.
* **Anything ZDR does not cover:** Products that are not covered by ZDR (for example, the Files API, Anthropic-hosted stateful applications, and the Batch API) are not covered by Access Transparency. See [ZDR documentation](https://code.claude.com/docs/en/zero-data-retention#what-zdr-does-not-cover) for additional details.
## Getting started
To enable Access Transparency:
<Steps>
<Step title="Request Access Transparency">
Contact your Anthropic account representative.
</Step>
<Step title="Anthropic reviews eligibility">
Anthropic confirms your organization meets the eligibility criteria and enables the capability at the organization level.
</Step>
<Step title="Receive events through the Compliance API">
`anthropic_access` activities appear in your existing Activity Feed under your existing Compliance Access Key; no new endpoint or credentials are required.
</Step>
</Steps>
Access Transparency is enabled at the organization level and covers all workspaces. Per-workspace enrollment is not currently available.
## Receiving Access Transparency events
Access Transparency events are delivered as the `anthropic_access` activity type on the Compliance API Activity Feed. Filter with `activity_types[]`:
```bash
curl --fail-with-body -sS -G \
"https://api.anthropic.com/v1/compliance/activities" \
--data-urlencode "activity_types[]=anthropic_access" \
--data-urlencode "limit=50" \
--header "x-api-key: $ANTHROPIC_COMPLIANCE_ACCESS_KEY"
```
Pagination, date-range filtering (`created_at.gte` / `.lt`), and the response envelope (`has_more`, `first_id`, `last_id`) are shared with the rest of the Activity Feed. See [Query the Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed).
Each `anthropic_access` activity carries the standard Activity fields plus the following:
| Field | Type | Description |
| ------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | string | Unique identifier for this activity |
| `accessed_at` | RFC 3339 string | When the access occurred. Might be earlier than when the activity becomes visible in your feed |
| `created_at` | RFC 3339 string | When the activity became visible in your feed |
| `actor` | object | Always `{ "type": "anthropic_actor", "email_address": null }`. Individual employee identity is not disclosed |
| `accessor_department` | string | The Anthropic team that performed the access (for example, `Safeguards`) |
| `reason_code` | enum | See [Reason codes](https://platform.claude.com/docs/en/manage-claude/access-transparency#reason-codes) |
| `resource_details.type` | enum | A resource type, currently only `message`. Extensible for future resource types |
| `resource_details.id` | string or null | Identifier of the content accessed |
| `resource_details.parent` | string or null | Identifier of the content's parent, for example the conversation ID containing a message. Currently `null` or omitted until resources with parents are supported |
| `organization_id` | string | The organization the content belongs to. Tagged ID format (`org_...`) |
| `organization_uuid` | string | The organization the content belongs to. UUID format |
| `workspace_id` | string or null | The workspace the content belongs to |
Example JSON message:
```json
{
"id": "activity_013b013744txqZtFHLUaRqLr",
"type": "anthropic_access",
"created_at": "2026-06-08T17:12:09.812446Z",
"accessed_at": "2026-06-08T17:12:06.478035Z",
"organization_id": "org_0910d9133038914eta7i3vt",
"actor": { "type": "anthropic_actor", "email_address": null },
"resource_details": { "type": "message", "id": "msg_1234ABCD" },
"accessor_department": "Safeguards",
"reason_code": "safety_review",
"organization_uuid": "5b236db4-3fb4-4bf3-a560-b5e266038a15"
}
```
## CMEK content preservation
In rare cases, Anthropic preserves specific content beyond the standard retention window (for example, when a safety review confirms severely harmful content that must be retained for an ongoing investigation). Preservation is itself a logged, customer-visible action:
* **A preservation event is written to your feed.** When content is preserved, an event with type `cmek_preserve` is written to your Compliance API Activity Feed. Preservation events carry the same fields as an `anthropic_access` event; only the event type differs, so a parser that handles one handles both. See [Reason codes](https://platform.claude.com/docs/en/manage-claude/access-transparency#reason-codes).
* **A preservation event is written regardless of how the preservation was initiated.** Preservation ordinarily follows human review of the content, but the event is written whether the preservation was initiated by a human reviewer or by an automated safety pipeline: the record reflects that your content's retention state changed, independent of who changed it.
* **For CMEK organizations, preservation is a visible key movement.** Preserved content is re-encrypted outside your customer-managed key so that the investigation can continue independent of your key. The preservation event is your record that this occurred. All other retained content remains under your key.
Filter for preservation events the same way as access events:
```bash
curl --fail-with-body -sS -G \
"https://api.anthropic.com/v1/compliance/activities" \
--data-urlencode "activity_types[]=cmek_preserve" \
--data-urlencode "limit=50" \
--header "x-api-key: $ANTHROPIC_COMPLIANCE_ACCESS_KEY"
```
Example JSON message:
```json
{
"id": "activity_01AbCdEfGhJkMnPqRsTuVwXy",
"type": "cmek_preserve",
"created_at": "2026-07-02T09:41:53.204118Z",
"accessed_at": "2026-07-02T09:41:50.118764Z",
"organization_id": "org_0123456789abcdefghijklmn",
"actor": { "type": "anthropic_actor", "email_address": null },
"resource_details": { "type": "message", "id": "msg_0ExampleExampleExample" },
"accessor_department": "Safeguards",
"reason_code": "policy_violation_investigation",
"organization_uuid": "00000000-1111-2222-3333-444444444444"
}
```
For preservation events, `accessed_at` records when the content was preserved.
## Reason codes
The set of reason codes is closed. Anthropic will update this page in the event it introduces a new code.
| Code | Meaning |
| -------------------------------- | ------------------------------------------------------------------------------ |
| `safety_review` | Content was viewed as part of a usage-policy or safety investigation |
| `incident_response` | Content was viewed while investigating an incident affecting your organization |
| `policy_violation_investigation` | Content was preserved during a Trust and Safety policy-violation investigation |
| `csae_report` | Content was preserved as evidence for a child safety (CSAE) report |
## Surface eligibility
The following table lists which surfaces are covered by Access Transparency. Coverage means human access to content from that surface generates `anthropic_access` events.
| Surface | Covered | Details |
| ----------------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------- |
| Claude API (`api.anthropic.com`) | Yes | Prompts, completions, and data directly embedded in the API inputs |
| Claude Code (using an API key) | Yes | API traffic from Claude Code is covered as Claude API traffic |
| Claude Platform on AWS | Yes | Claude Platform on AWS generates Access Transparency events within the Compliance API (not AWS CloudTrail) |
| Claude API (`api.anthropic.com`) (Batch, Files) | No | The Claude API Batch and Files APIs are not covered, just like they are not covered by ZDR |
| Claude for Enterprise (claude.ai seats) | No | Not covered |
| Claude for Work | No | Not covered |
| Claude Free, Pro, Max | No | Consumer plans are not eligible |
| Anthropic Workbench | No | The Workbench stores data in data stores that are not covered by Access Transparency |
| Microsoft Foundry | No | Not available |
| Amazon Bedrock, Google Cloud | No | Partner-operated platforms; refer to those platforms' transparency controls |
## Limitations and exclusions
### Coverage timing
Access Transparency applies from the time it is enabled for your organization. Content already in your retention window at enablement might also generate events when accessed, but Anthropic does not guarantee coverage for content written before enablement. Treat your enablement date as the start of reliable coverage. There might be a delay of up to two hours between enabling Access Transparency and your content being covered.
### Notification timing
`anthropic_access` and `cmek_preserve` events are delivered to your Compliance API feed within two business days of the access or preservation they record. This feed should not be treated as a real-time alerting channel, and the `accessed_at` timestamp reflects when the access occurred, which might be up to two business days before the activity becomes visible in your feed. The `created_at` field reflects the time that the event became visible.
### Automated processing does not generate access events
`anthropic_access` events record human access only. Anthropic's automated safety systems and classifiers continue to process your content as part of normal operation, and that processing does not generate `anthropic_access` events. The one event automated processing can initiate is a `cmek_preserve` preservation record (see [CMEK content preservation](https://platform.claude.com/docs/en/manage-claude/access-transparency#cmek-content-preservation)). An empty feed means no human at Anthropic has viewed your content; it does not mean your content was not processed by automated systems.
### Access Transparency does not change what Anthropic can access
Access Transparency records access; it does not grant or restrict it. The purposes for which Anthropic personnel may access your content are governed by your agreement with Anthropic and the [Usage Policies](https://www.anthropic.com/legal/aup), and are the same regardless of whether Access Transparency is enabled.
### CMEK key-use logs are not a per-read record
For organizations that also enable CMEK, your cloud KMS audit log (CloudTrail, Cloud Audit Logs, or Azure Monitor) records Anthropic's use of your key. Because keys are cached for short periods during operation, an individual human read does not necessarily produce a distinct KMS decryption entry. Use the Access Transparency feed as the per-access record; your KMS log independently confirms key usage patterns.
## Frequently asked questions
<AccordionGroup>
<Accordion title="How do I know if my organization has Access Transparency enabled?">
Contact your Anthropic account representative.
</Accordion>
<Accordion title="Will I see an event each time a safety classifier runs on my traffic?">
No. Automated processing does not generate `anthropic_access` events; you will see an `anthropic_access` event only if a human reviewer subsequently views the content. Separately, a `cmek_preserve` event is written when content is preserved, whether the preservation was initiated by a human reviewer or an automated safety pipeline.
</Accordion>
<Accordion title="We are a platform that serves Claude to our own end users. Can we enable Access Transparency?">
Access Transparency is not available for platform deployments. Contact your Anthropic account representative to discuss your use case.
</Accordion>
<Accordion title="Will I see events for access that happened before we enrolled, or for our older data?">
Access Transparency is not guaranteed to be retroactive. It covers human access to content written to the Claude API on or after your enrollment date. You might see events for access to content that was written before enrollment.
</Accordion>
<Accordion title="How soon after an access will I see the event?">
Within two business days of the access. Configure any SIEM alerting or scheduled exports with a matching lookback window rather than assuming real-time arrival.
</Accordion>
<Accordion title="How do I know which request an anthropic_access event refers to?">
Use the `resource_details.id` field. It contains the same message ID (`msg_...`) that the [Messages API](https://platform.claude.com/docs/en/api/messages/create) returns in the `id` field of every response body. To make this useful, log `id` in your own systems alongside your internal metadata, such as the application, end user, or conversation that produced the request. When an event arrives, join its `resource_details.id` against your logs to identify exactly which request was viewed.
</Accordion>
<Accordion title="Can I enable Access Transparency for a single workspace?">
Access Transparency is enabled at the organization level and covers all workspaces.
</Accordion>
<Accordion title="How does Access Transparency relate to CMEK?">
They are independent. With CMEK, safety preservation outside your key emits a separate `cmek_preserve` event on the same feed. See [CMEK content preservation](https://platform.claude.com/docs/en/manage-claude/access-transparency#cmek-content-preservation) and [CMEK](https://platform.claude.com/docs/en/manage-claude/cmek).
</Accordion>
<Accordion title="How do I request Access Transparency?">
Contact your Anthropic account representative.
</Accordion>
</AccordionGroup>
## Related resources
* [Compliance API overview](https://platform.claude.com/docs/en/manage-claude/compliance-api)
* [Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed)
* [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention)
* [Customer-Managed Encryption Keys (CMEK)](https://platform.claude.com/docs/en/manage-claude/cmek)
* [Claude Code data usage](https://code.claude.com/docs/en/data-usage)
* [Trust Center](https://trust.anthropic.com/resources)
manage-claude/admin-api First recorded · 306 lines, first recorded
## Authentication ### OAuth bearer token ### Admin API key ## How the Admin API works ## Organization roles and permissions ## Key concepts ### Organization members ### Organization invites ### Workspaces ### Workspace members ### API keys ### Service accounts ### Federation issuers ### Federation rules ## Accessing organization info ## Usage and cost reports ## Claude Code analytics ## Rate limits ## Compliance API ## Best practices ## FAQ
The first capture of this source. The page was already there, and this is what it said.
---
title: Admin API
url: https://platform.claude.com/docs/en/manage-claude/admin-api
description: Manage organization members, workspaces, invites, and API keys programmatically with the Admin API, using an Admin API key or an `org:admin` OAuth token.
---
<Tip>
**The Admin API is unavailable for individual accounts.** To collaborate with teammates and add members, set up your organization in **Console → Settings → Organization**.
</Tip>
The [Admin API](https://platform.claude.com/docs/en/api/admin) allows you to programmatically manage your organization's resources, including organization members, workspaces, and API keys. This provides programmatic control over administrative tasks that would otherwise require manual configuration in the [Claude Console](https://platform.claude.com/).
<Check>
**The Admin API requires special access**
The Admin API accepts two credentials:
* An **Admin API key** (starting with `sk-ant-admin...`) sent in the `x-api-key` header. Only organization members with the admin role can provision one. See [Create an Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys).
* An **OAuth bearer token** with the `org:admin` scope sent in the `authorization: Bearer` header. Only members with the admin, owner, or primary owner role can obtain one. See [Obtain an OAuth bearer token](https://platform.claude.com/docs/en/manage-claude/admin-api#oauth-bearer-token).
</Check>
<Note>
**Claude Enterprise:** Claude Enterprise (claude.ai) organizations use the Admin API too, with a scoped API key created in claude.ai. Of the endpoints on this page, only members and invites are available to them (in beta), alongside Claude-Enterprise-only endpoints: groups and custom-role reads (beta), and [spend limits](https://platform.claude.com/docs/en/manage-claude/spend-limits-api). See [User management](https://platform.claude.com/docs/en/manage-claude/user-management) for Claude Enterprise.
</Note>
<Note>
**Claude Platform on AWS:** Most of the Admin API is not available on Claude Platform on AWS. Workspace endpoints (create, get, list, update, and archive on `/v1/organizations/workspaces`) are available. Other endpoints including organization members, workspace members, invites, API keys, usage reports, cost reports, and rate limit reports are not available. See [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws) for details.
</Note>
## Authentication
Authenticate with either credential. An Admin API key covers most endpoints; the service-account, federation-issuer, and federation-rule endpoints accept only an `org:admin` OAuth token. The following examples call the [organization info endpoint](https://platform.claude.com/docs/en/manage-claude/admin-api#accessing-organization-info) both ways.
### OAuth bearer token
Log in with the [`ant` CLI](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart) under a dedicated profile, requesting the `org:admin` scope (see [Admin access](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#admin-access)), then export the bearer token. A dedicated profile keeps your routine commands from running with elevated access:
```bash CLI
ant auth login --profile admin --scope "org:admin"
export ANTHROPIC_OAUTH_TOKEN=$(ant auth print-credentials --profile admin --access-token)
```
Interactive tokens are short-lived; if requests start returning 401, re-run the `export` command, which refreshes the token automatically.
Call the Admin API with the exported token:
```bash cURL
curl --fail-with-body -sS "https://api.anthropic.com/v1/organizations/me" \
--header "anthropic-version: 2023-06-01" \
--header "authorization: Bearer $ANTHROPIC_OAUTH_TOKEN"
```
An `org:admin` token grants access to the whole organization, regardless of the workspace the underlying profile or [federation rule](https://platform.claude.com/docs/en/manage-claude/admin-api#federation-rules) is bound to.
For CI and other non-interactive workloads, mint the token with Workload Identity Federation instead of logging in interactively. See [Manage WIF with the Admin API](https://platform.claude.com/docs/en/manage-claude/wif-admin-api#workload-ci-and-automation).
### Admin API key
To create an Admin API key for your organization type, see [Create an Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys).
```bash cURL
curl --fail-with-body -sS "https://api.anthropic.com/v1/organizations/me" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
## How the Admin API works
When you use the Admin API:
1. You make requests using either credential from the [Authentication](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication) section
2. The API allows you to manage:
* Organization members and their roles
* Organization member invites
* Workspaces and their members
* API keys
* Service accounts, federation issuers, and federation rules (these endpoints require an `org:admin` OAuth token; Admin API keys are not accepted)
This is useful for:
* Automating user onboarding/offboarding
* Programmatically managing workspace access
* Monitoring and managing API key usage
## Organization roles and permissions
There are five organization-level roles. See more details in the [API Console roles and permissions](https://support.claude.com/en/articles/10186004-api-console-roles-and-permissions) article.
| Role | Permissions |
| ------------------ | ----------------------------------------------------------------------------- |
| user | Can use Workbench |
| claude\_code\_user | Can use Workbench and [Claude Code](https://code.claude.com/docs/en/overview) |
| developer | Can use Workbench and manage API keys |
| billing | Can use Workbench and manage billing details |
| admin | Can do all of the preceding, plus manage users |
Organization owners and primary owners have all admin permissions and can additionally manage admins. All references to the admin role on this page also apply to owners and primary owners.
## Key concepts
### Organization members
You can list [organization members](https://platform.claude.com/docs/en/api/admin-api/users/get-user), update member roles, and remove members.
<CodeGroup>
```bash cURL
# List organization members
curl "https://api.anthropic.com/v1/organizations/users?limit=10" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Update member role
curl "https://api.anthropic.com/v1/organizations/users/{user_id}" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{"role": "developer"}'
# Remove member
curl --request DELETE "https://api.anthropic.com/v1/organizations/users/{user_id}" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
</CodeGroup>
### Organization invites
You can invite users to organizations and manage those [invites](https://platform.claude.com/docs/en/api/admin-api/invites/get-invite).
<CodeGroup>
```bash cURL
# Create invite
curl --request POST "https://api.anthropic.com/v1/organizations/invites" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{
"email": "[email protected]",
"role": "developer"
}'
# List invites
curl "https://api.anthropic.com/v1/organizations/invites?limit=10" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Delete invite
curl --request DELETE "https://api.anthropic.com/v1/organizations/invites/{invite_id}" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
</CodeGroup>
### Workspaces
For a comprehensive guide to workspaces, including Console and API examples, see [Workspaces](https://platform.claude.com/docs/en/manage-claude/workspaces).
### Workspace members
Manage [user access to specific workspaces](https://platform.claude.com/docs/en/api/admin-api/workspace_members/get-workspace-member):
<CodeGroup>
```bash cURL
# Add member to workspace
curl --request POST "https://api.anthropic.com/v1/organizations/workspaces/{workspace_id}/members" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{
"user_id": "user_xxx",
"workspace_role": "workspace_developer"
}'
# List workspace members
curl "https://api.anthropic.com/v1/organizations/workspaces/{workspace_id}/members?limit=10" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Update member role
curl --request POST "https://api.anthropic.com/v1/organizations/workspaces/{workspace_id}/members/{user_id}" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{
"workspace_role": "workspace_admin"
}'
# Remove member from workspace
curl --request DELETE "https://api.anthropic.com/v1/organizations/workspaces/{workspace_id}/members/{user_id}" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
</CodeGroup>
### API keys
Monitor and manage [API keys](https://platform.claude.com/docs/en/api/admin/api_keys/list). Each key in the response includes its `expires_at` timestamp (`null` for keys without an [expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration)):
<CodeGroup>
```bash cURL
# List API keys
curl "https://api.anthropic.com/v1/organizations/api_keys?limit=10&status=active&workspace_id=wrkspc_xxx" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Update API key
curl --request POST "https://api.anthropic.com/v1/organizations/api_keys/{api_key_id}" \
--header "anthropic-version: 2023-06-01" \
--header "content-type: application/json" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY" \
--data '{
"status": "inactive",
"name": "New Key Name"
}'
```
</CodeGroup>
### Service accounts
Create and manage service accounts (`svac_...`), the non-human identities that [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) tokens act as. Admin API keys are not accepted on the service-account, federation-issuer, or federation-rule endpoints; use an `org:admin` OAuth token. See [Manage WIF with the Admin API](https://platform.claude.com/docs/en/manage-claude/wif-admin-api#service-accounts).
### Federation issuers
Register the OIDC identity providers (`fdis_...`) whose tokens may assert workload identity for your organization. See [Manage WIF with the Admin API](https://platform.claude.com/docs/en/manage-claude/wif-admin-api#federation-issuers).
### Federation rules
Manage the rules (`fdrl_...`) that map issuer tokens to service accounts and scopes. See [Manage WIF with the Admin API](https://platform.claude.com/docs/en/manage-claude/wif-admin-api#federation-rules).
## Accessing organization info
Get information about your organization programmatically with the `/v1/organizations/me` endpoint.
For example:
```bash cURL
curl "https://api.anthropic.com/v1/organizations/me" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
```json
{
"id": "12345678-1234-5678-1234-567812345678",
"type": "organization",
"name": "Organization Name"
}
```
This endpoint is useful for programmatically determining which organization an Admin API key belongs to.
For complete parameter details and response schemas, see the [Organization Info API reference](https://platform.claude.com/docs/en/api/admin-api/organization/get-me).
## Usage and cost reports
Track your organization's usage and costs with the [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api).
## Claude Code analytics
Monitor developer productivity and Claude Code adoption with the [Claude Code Analytics API](https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api).
## Rate limits
Read the rate limits configured for your organization and its workspaces with the [Rate Limits API](https://platform.claude.com/docs/en/manage-claude/rate-limits-api).
## Compliance API
Retrieve audit and activity data for your organization with the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api). Admin API keys can read the Activity Feed only; for full access, see [Set up the Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api-access).
## Best practices
To effectively use the Admin API:
* Use meaningful names and descriptions for workspaces and API keys
* Implement proper error handling for failed operations
* Regularly audit member roles and permissions
* Clean up unused workspaces and expired invites
* Monitor API key usage, audit each key's [`expires_at`](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration), and rotate keys periodically
## FAQ
<AccordionGroup>
<Accordion title="What permissions are needed to use the Admin API?">
The Admin API accepts either an Admin API key (starting with `sk-ant-admin`) or an OAuth bearer token with the `org:admin` scope. Only organization members with the admin role can provision Admin API keys, and only members with the admin, owner, or primary owner role can obtain `org:admin` tokens. See [Authentication](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication).
</Accordion>
<Accordion title="Can I create new API keys through the Admin API?">
No, new API keys can only be created through the Claude Console for security reasons. The Admin API can only manage existing API keys.
</Accordion>
<Accordion title="What happens to API keys when removing a user?">
API keys persist in their current state as they are scoped to the organization, not to individual users.
</Accordion>
<Accordion title="Can organization admins be removed through the API?">
No, organization members with the admin role cannot be removed through the API for security reasons.
</Accordion>
Cut at 300 lines. The page has the rest.
manage-claude/admin-api-keys First recorded · 105 lines, first recorded
## Which key do you need? ## Create a key for a Claude Console organization ## Create a key for a Claude Enterprise organization ## Choose scopes for a Claude Enterprise key ## Use the key ## Next steps
The first capture of this source. The page was already there, and this is what it said.
---
title: Create an Admin API key
url: https://platform.claude.com/docs/en/manage-claude/admin-api-keys
description: Create an Admin API key for your Claude Console or Claude Enterprise organization.
---
An Admin API key authenticates every API in the **Admin** section of this guide: the [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api), [Analytics APIs](https://platform.claude.com/docs/en/manage-claude/analytics-api), [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api), [Spend Limits API](https://platform.claude.com/docs/en/manage-claude/spend-limits-api), [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api), and [Rate Limits API](https://platform.claude.com/docs/en/manage-claude/rate-limits-api). You do not need a separate key for each API. The one exception is the Admin API's service-account, federation-issuer, and federation-rule endpoints, which accept only an OAuth bearer token with the `org:admin` scope. See [Obtain an OAuth bearer token](https://platform.claude.com/docs/en/manage-claude/admin-api#oauth-bearer-token).
Where you create the key depends on which Claude product your organization uses.
## Which key do you need?
| Your organization | Create the key in | Key prefix | Who can create it | Works with |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Claude Console** (Claude Platform, `platform.claude.com`) | [Claude Console > Settings > Admin keys](https://platform.claude.com/settings/admin-keys) | `sk-ant-admin01-...` | Organization members with the **admin** role | [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api), [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api), [Rate Limits API](https://platform.claude.com/docs/en/manage-claude/rate-limits-api), [Claude Code Analytics API](https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api), and the Compliance API [Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed) |
| **Claude Enterprise** (`claude.ai`) | [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access) | `sk-ant-api01-...` | The parent organization's **primary owner** (all linked organizations). An **organization owner** can create one carrying Compliance API scopes only, restricted to their own organization | [User management](https://platform.claude.com/docs/en/manage-claude/user-management) (the Admin API's member, invite, and group endpoints, in beta), [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api), [Claude Enterprise Analytics API](https://platform.claude.com/docs/en/manage-claude/analytics-api), and [Spend Limits API](https://platform.claude.com/docs/en/manage-claude/spend-limits-api), according to the [scopes](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#choose-scopes-for-a-claude-enterprise-key) you select |
A key created in one organization cannot be used to manage a different organization. If your company uses both Claude Console and Claude Enterprise, create one key in each.
## Create a key for a Claude Console organization
<Steps>
<Step title="Sign in as an organization admin">
Only organization members with the **admin** role can create Admin API keys. See [Organization roles and permissions](https://platform.claude.com/docs/en/manage-claude/admin-api#organization-roles-and-permissions).
</Step>
<Step title="Open Admin keys settings">
Go to [Claude Console > Settings > Admin keys](https://platform.claude.com/settings/admin-keys).
</Step>
<Step title="Create the key">
Click **Create key**, give it a name, choose a [key expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration), and click **Create**. Claude Console keys do not have selectable scopes; every key carries full access to all endpoints that accept Admin API keys (the service-account and federation endpoints noted at the top of this page do not accept Admin API keys).
</Step>
<Step title="Copy and store the secret">
Copy the displayed secret (starting with `sk-ant-admin01-`) and store it in your secrets manager. The full secret is shown only once.
</Step>
</Steps>
## Create a key for a Claude Enterprise organization
<Steps>
<Step title="Sign in as the primary owner or an organization owner">
The **primary owner** of the Claude Enterprise parent organization can create a key that can access every linked organization, or one restricted to a single organization. An **organization owner** can create a key with Compliance API scopes only, restricted to their own organization.
</Step>
<Step title="Open API settings">
Go to [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access) and find the **Keys** section.
</Step>
<Step title="Click + Create key">
Name the key and select the scopes you need from the [scopes table](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#choose-scopes-for-a-claude-enterprise-key). The primary owner can combine scopes from different APIs (for example, `read:analytics` and `read:spend_limits`) on a single key.
</Step>
<Step title="Copy and store the secret">
Copy the displayed secret (starting with `sk-ant-api01-`) and store it in your secrets manager. The full secret is shown only once.
</Step>
</Steps>
## Choose scopes for a Claude Enterprise key
When you create a Claude Enterprise key, select every scope that the APIs you plan to call require. Scopes are fixed at creation; to add a scope later, create a new key.
| To call... | Select these scopes |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management): list and look up members and invites; read custom roles and their permissions | `read:members` |
| Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management): change member roles, remove members, create and withdraw invites | `write:members` |
| Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management): read groups and their members | `read:rbac_groups` |
| Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management): create, rename, and delete groups; add and remove group members; assign groups on invite creation | `write:rbac_groups` |
| [Spend Limits API](https://platform.claude.com/docs/en/manage-claude/spend-limits-api): read members' effective spend limits and increase requests | `read:spend_limits` |
| [Spend Limits API](https://platform.claude.com/docs/en/manage-claude/spend-limits-api): set or clear per-user spend limits; approve or deny increase requests | `write:spend_limits` |
| [Claude Enterprise Analytics API](https://platform.claude.com/docs/en/manage-claude/analytics-api): engagement, adoption, cost, and usage reports | `read:analytics` |
| [Compliance API Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed): organization-wide activity events | `read:compliance_activities` |
| [Compliance API chat, file, and project endpoints](https://platform.claude.com/docs/en/manage-claude/compliance-content-data) and [Compliance API session endpoints](https://platform.claude.com/docs/en/manage-claude/compliance-sessions): read chats, files, projects, Cowork and Claude Code session transcripts, and [organization users](https://platform.claude.com/docs/en/manage-claude/compliance-org-data#list-organization-users) | `read:compliance_user_data` |
| [Compliance API chat, file, and project endpoints](https://platform.claude.com/docs/en/manage-claude/compliance-content-data): delete chats, files, and projects | `delete:compliance_user_data` |
| [Compliance API organization endpoints](https://platform.claude.com/docs/en/manage-claude/compliance-org-data): read organization metadata and effective settings | `read:compliance_org_data` |
| Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management) read endpoints and every Compliance API read endpoint, with a single read-only scope (for security-audit integrations; does not include the Spend Limits or Analytics APIs) | `read:org_audit` |
The Compliance and Analytics APIs must be enabled for your organization before keys with those scopes can be used. See [Set up the Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api-access#set-up-the-compliance-api) and [Get access to the Claude Enterprise Analytics API](https://platform.claude.com/docs/en/manage-claude/analytics-api#get-access-to-the-claude-enterprise-analytics-api).
## Use the key
Pass the key in the `x-api-key` header on every request. See each API's documentation for complete request examples.
A call that exceeds the key's scopes returns `403 Forbidden` with a message listing the scopes the key has and the scopes the endpoint needs.
## Next steps
<CardGroup cols={2}>
<Card title="Admin API" href="https://platform.claude.com/docs/en/manage-claude/admin-api">
Manage organization members, workspaces, and API keys.
</Card>
<Card title="Spend Limits API" href="https://platform.claude.com/docs/en/manage-claude/spend-limits-api">
Set per-member spend limits and review increase requests for your Claude Enterprise organization.
</Card>
<Card title="Analytics APIs" href="https://platform.claude.com/docs/en/manage-claude/analytics-api">
Report on Claude Code productivity or Claude Enterprise engagement and adoption.
</Card>
<Card title="Compliance API" href="https://platform.claude.com/docs/en/manage-claude/compliance-api">
Audit activity and retrieve or delete user content across your organization.
</Card>
</CardGroup>
manage-claude/analytics-api First recorded · 132 lines, first recorded
## Which API do you need? ## Get access to the Claude Code Analytics API ## Get access to the Claude Enterprise Analytics API ## Data availability and freshness ## How metrics are defined ## Working with the API ## Known limitations ## Next steps
The first capture of this source. The page was already there, and this is what it said.
---
title: Analytics APIs
url: https://platform.claude.com/docs/en/manage-claude/analytics-api
description: Understand which analytics API and API key your organization needs, then provision access to Claude Code productivity metrics or Claude Enterprise engagement and adoption data.
---
Anthropic provides two analytics APIs, and which one you use depends on which Claude product your organization manages:
* The **Claude Code Analytics API** reports daily Claude Code productivity metrics for organizations that use the Claude Platform. It is part of the [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api) and uses an Admin API key.
* The **Claude Enterprise Analytics API** reports organization-wide engagement, adoption, and cost data across Claude products (chat, projects, Claude Code, and more) for Claude Enterprise organizations. It uses an Analytics API key created in claude.ai.
The two APIs use different key types, created in different places by different roles. This page describes which API fits your organization and how to create the right key.
## Which API do you need?
| API | Key type | Created in | Who can create it | What it covers |
| ----------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Claude Code Analytics API** | Admin API key (`sk-ant-admin01-...`) | [Claude Console > Settings > Admin keys](https://platform.claude.com/settings/admin-keys) | Organization admin | Daily Claude Code metrics per user: sessions, lines of code, commits, pull requests, tool acceptance, and estimated cost by model |
| **Claude Enterprise Analytics API** | Analytics API key | [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access) | Primary owner | Organization-wide engagement and adoption (user activity, active-user summaries, project, skill, and connector usage), plus cost and usage reports |
The key types are not interchangeable: an Admin API key cannot call the Claude Enterprise Analytics API, and an Analytics API key cannot call the Admin API. Both APIs appear under the [Admin API reference](https://platform.claude.com/docs/en/api/admin), but they are separate APIs with separate key types. If your organization uses both the Claude Platform and Claude Enterprise, you can provision both keys and use each API for its own data.
<Note>
Looking for API usage and cost data rather than product analytics? See the [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api), which explains the right path for both Claude Console and Claude Enterprise organizations.
</Note>
<Note>
If you want to view engagement and adoption data in the product rather than programmatically, use the [Analytics dashboard](https://claude.ai/analytics/activity) in claude.ai. For governance and auditing use cases (individual user actions, raw activity events, conversation content), see the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api-access).
</Note>
## Get access to the Claude Code Analytics API
The Claude Code Analytics API is available to every organization with access to the [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api), and is free to use.
<Steps>
<Step title="Create an Admin API key">
Follow the steps in [Create an Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#create-a-key-for-a-claude-console-organization).
</Step>
<Step title="Call the API">
Pass the key in the `x-api-key` header:
```bash
curl "https://api.anthropic.com/v1/organizations/usage_report/claude_code?starting_at=2025-09-08" \
--header "anthropic-version: 2023-06-01" \
--header "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
</Step>
</Steps>
For the available metrics, request parameters, and response schema, see the [Claude Code Analytics API guide](https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api) and the [API reference](https://platform.claude.com/docs/en/api/admin/usage_report/retrieve_claude_code).
## Get access to the Claude Enterprise Analytics API
The Claude Enterprise Analytics API is available to Claude Enterprise organizations. Engagement and adoption data is available on all Enterprise plans. The cost and usage endpoints apply to usage-based Enterprise plans; for seat-based Enterprise plans, they reflect usage credits only.
<Steps>
<Step title="Sign in as the primary owner">
Only the primary owner of the organization can enable API access and create Analytics API keys.
</Step>
<Step title="Enable API access and create a key">
Go to [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access) and enable public API access, then create an Analytics API key. Keys carry the `read:analytics` scope. Copy the displayed secret and store it in your secrets manager.
</Step>
<Step title="Call the API">
Pass the key in the `x-api-key` header. Endpoints live under `https://api.anthropic.com/v1/organizations/analytics/`. For request examples, parameters, and response schemas, see the [Claude Enterprise Analytics API reference](https://platform.claude.com/docs/en/api/admin/analytics).
</Step>
</Steps>
The Claude Enterprise Analytics API provides:
* **User activity:** per-user daily metrics across chat (conversations, messages, projects, files, artifacts), Claude Code (sessions, commits, pull requests, lines of code, tool actions), and other Claude products
* **Activity summaries:** organization-level daily, weekly, and monthly active users, seat counts, and pending invites
* **Project, skill, and connector usage:** adoption breakdowns for chat projects, skills, and connectors
* **Cost and usage reports:** per-user and organization-level token usage and cost over time (usage-based Enterprise plans)
For endpoint details, parameters, and response schemas, see the [Claude Enterprise Analytics API reference](https://platform.claude.com/docs/en/api/admin/analytics). The following sections cover data freshness, metric definitions, and operational guidance that apply across those endpoints.
## Data availability and freshness
Claude Enterprise Analytics API data is available for dates on or after January 1, 2026.
**Engagement and adoption endpoints** (user activity, summaries, projects, skills, connectors) return a per-day snapshot for the date you specify. Data for a given day is aggregated at 10UTC the following day and is typically available with a 1-day lag. Exact freshness varies by query, so rather than assuming a fixed lag, check the error response: requesting a date that is not yet available returns a 400 error naming the most recent available day. If data is not available well past the typical lag, it usually indicates a data pipeline failure on Anthropic's side; contact support if the gap persists.
**Cost and usage endpoints** follow a different freshness model. Data is typically available within four hours of the underlying usage but may take up to 24 hours. Values for a given date can be revised for up to 30 days as late events arrive and reconciliation runs. For invoicing-grade totals, query dates at least 30 days in the past.
<Note>
Cost and usage responses include a `data_refreshed_at` timestamp. When `ending_at` is omitted (the default is the current time), the response includes a tail of data after `data_refreshed_at` that is incomplete. For stable results across repeated calls, set `ending_at` to a value at or before a previously returned `data_refreshed_at`.
</Note>
## How metrics are defined
**Active users.** A user counts as active for a day if any of the following is true: they sent at least one chat message in Claude, they had at least one Claude Code session (local or remote) associated with your Claude Enterprise organization that included tool use or git activity, or they had at least one Cowork session with tool use or message activity.
**Per-product metric blocks.** Per-product metric objects (for example, Office Agent or Cowork metrics on a user-activity record) are always present on every record. Organizations without usage of that product see all-zero values rather than `null`.
**Connector names.** Connector names are normalized across sources. For example, `Atlassian MCP server`, `mcp-atlassian`, and `atlassian_MCP` all appear as `atlassian` in the connector usage endpoint.
## Working with the API
**Pagination cursors are bound to the query that issued them.** On the cost and usage endpoints, do not change query parameters mid-sequence: if you change `products[]`, `group_by[]`, `order_by`, the date range, or any filter and pass an old cursor, the request returns a 400 error. To change parameters, restart from the first page without a cursor.
**List parameters use bracket notation.** Repeat the parameter for each value, for example `products[]=chat&products[]=claude_code`.
**Amount fields are decimal strings in cents.** Currency amounts are returned as decimal strings such as `"41280.000000"` (which represents $412.80). To convert to dollars, parse as a decimal and divide by 100. Avoid binary floating-point parsing for values that may exceed several million dollars.
**Rate limits apply at the organization level**, not per key, with a default of 60 requests per minute across all endpoints in this API. If that is not sufficient for your use case, contact your Anthropic account team to discuss adjusting the limit.
## Known limitations
If your organization uses Claude Code through Amazon Bedrock, the Claude Enterprise Analytics API does not return Claude Code activity for that usage.
## Next steps
<CardGroup cols={2}>
<Card title="Claude Code Analytics API" href="https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api">
Track Claude Code sessions, code changes, and tool usage with an Admin API key.
</Card>
<Card title="Usage and Cost API" href="https://platform.claude.com/docs/en/manage-claude/usage-cost-api">
Track API token usage and costs for your organization.
</Card>
<Card title="Claude Enterprise Analytics API reference" href="https://platform.claude.com/docs/en/api/admin/analytics">
Endpoint reference for engagement, adoption, and cost data.
</Card>
<Card title="Set up the Compliance API" href="https://platform.claude.com/docs/en/manage-claude/compliance-api-access">
Audit and compliance data uses its own key types.
</Card>
</CardGroup>
manage-claude/api-and-data-retention First recorded · 285 lines, first recorded
## How Anthropic approaches data retention ## Zero data retention (ZDR) ### What ZDR covers ### What ZDR does not cover ## HIPAA readiness ### What HIPAA readiness covers ### What HIPAA readiness does not cover ### PHI handling guidelines ### HIPAA error handling ### Getting started with HIPAA readiness #### Enable in the Console (standard BAA) #### Contact sales (custom BAA) #### Build with eligible features ## Model-specific data retention requirements ### Enable 30-day retention for a workspace ## Feature eligibility ## Retention regardless of arrangement ## Frequently asked questions ## Related resources
The first capture of this source. The page was already there, and this is what it said.
---
title: API and data retention
url: https://platform.claude.com/docs/en/manage-claude/api-and-data-retention
description: Learn about how Anthropic's APIs and associated features retain data, including information about zero data retention (ZDR) and HIPAA-ready API access.
---
This page covers the Claude API (`api.anthropic.com`), Claude Platform on AWS, and [Claude in Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry), where Anthropic is the data processor. On Amazon Bedrock and Google Cloud's Agent Platform, the cloud provider is the data processor; refer to those platforms' data retention and compliance documentation for their equivalent controls.
Anthropic offers two data handling arrangements for the Claude API: [zero data retention (ZDR)](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#zero-data-retention-zdr-scope) and [HIPAA readiness](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#hipaa-readiness). The [feature eligibility table](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#feature-eligibility) lists which API features each arrangement covers. For Anthropic's standard retention policies outside these arrangements, see the [commercial data retention policy](https://privacy.claude.com/en/articles/7996866-how-long-do-you-store-my-organization-s-data) and the [consumer data retention policy](https://privacy.claude.com/en/articles/10023548-how-long-do-you-store-my-data).
## How Anthropic approaches data retention
Different APIs and features have different storage needs. Where a feature does not require storage of customer prompts or responses, it may be eligible for ZDR. Where a feature necessarily requires storage, Anthropic designs for the smallest possible retention footprint under the following commitments:
* Retained data is never used for model training without your express permission.
* Only what is technically necessary for the feature to work is retained. Conversation content (your prompts and Claude's outputs) is not retained by default; the exception is [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements), which require 30-day retention.
* Retained data is purged on the shortest practical time to live (TTL), and Anthropic aims to give customers control over how long data is retained. What is held, and the retention duration where a specific TTL applies, is documented on each feature's page.
Several retention models sit outside the ZDR and HIPAA arrangements described on this page. Data accessible through the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api) follows its own retention model. The [Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed) retains data for 6 years. Chat, file, and project content from claude.ai follows your organization's retention policy set in [claude.ai > Organization settings > Data and privacy](https://claude.ai/admin-settings/data-privacy-controls). [Local session transcripts](https://platform.claude.com/docs/en/manage-claude/compliance-sessions#retrieve-local-sessions) (Cowork and Claude Code on users' machines) are stored for 6 years by default, or for your organization's custom conversation retention period when a finite one is set (the same claude.ai setting). [Remote session transcripts](https://platform.claude.com/docs/en/manage-claude/compliance-sessions#retrieve-remote-sessions) (Cowork in the cloud) are retained for 6 years. The Compliance API does not capture local sessions for which ZDR is in effect, or any local sessions from organizations with HIPAA readiness enabled.
## Zero data retention (ZDR)
Under a ZDR arrangement, Anthropic does not store customer prompts or responses at rest after the API response is returned. To request ZDR for your organization, contact the [Anthropic sales team](https://claude.com/contact-sales). ZDR is enabled per organization; each new organization requires ZDR to be enabled separately by your account team, and enablement does not automatically extend to other organizations under the same account.
### What ZDR covers
* **Claude Messages and Token Counting APIs:** ZDR applies to these endpoints for eligible features listed in the [feature eligibility table](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#feature-eligibility). Features that ride on `/v1/messages` but are marked "No" in the table (such as code execution) are not covered.
* **Claude Code:** ZDR applies when Claude Code is used with API keys from a Commercial organization (an organization under Anthropic's Commercial Terms of Service, as distinct from a consumer Claude account) or through Claude Enterprise with ZDR enabled. If metrics logging is enabled in Claude Code, productivity data such as usage statistics is exempted from ZDR and may be retained. See the [Claude Code ZDR documentation](https://code.claude.com/docs/en/zero-data-retention) for full details.
* **Claude Platform on AWS:** [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws) follows the same data retention policy as the first-party Claude API. ZDR is available on request; contact your Anthropic account representative to enable it.
### What ZDR does not cover
* **Console and Workbench:** Any usage on Claude Console or the Workbench prompt-testing interface.
* **Claude Managed Agents:** Claude Managed Agents is a stateful resource; session transcripts persist until you delete them.
* **Claude consumer products:** Claude Free, Pro, and Max plans, including when customers on those plans use Claude's web, desktop, or mobile apps or Claude Code.
* **Claude Teams and Claude Enterprise product interfaces:** These interfaces are not ZDR-eligible. The exception is Claude Code used through Claude Enterprise with ZDR enabled; see [What ZDR covers](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#what-zdr-covers).
* **Claude for Excel:** Not currently ZDR-eligible.
* **Claude Fable 5 and Claude Mythos 5:** These models require 30-day data retention and are not available under ZDR. See [Model-specific data retention requirements](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements).
* **Third-party integrations:** Data processed by third-party websites, tools, or other integrations is not covered, though some may have similar offerings. Review each service's data handling practices.
* **Cross-Origin Resource Sharing (CORS):** CORS is not supported for organizations with ZDR arrangements. To make API calls from browser-based applications, route requests through a backend proxy server. See the [API security guidance](https://platform.claude.com/docs/en/api/overview) for proxy patterns and API-key handling.
* **Flagged content and legal holds:** See [Retention regardless of arrangement](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#retention-regardless-of-arrangement).
<Note>
For the most up-to-date information on which products and features are ZDR-eligible, refer to your contract terms or contact your Anthropic account representative.
</Note>
## HIPAA readiness
The Claude API supports HIPAA-ready integrations for organizations that handle protected health information (PHI). With a signed BAA and a HIPAA-enabled organization, you can use supported API features to process PHI while supporting your organization's HIPAA compliance. Eligible organizations can review and execute the BAA and enable HIPAA readiness directly from the Claude Console. HIPAA readiness applies a broader set of privacy and security safeguards than ZDR (encryption, access controls, and audit logging that protect PHI throughout its lifecycle) rather than requiring immediate deletion. If your organization handles PHI, HIPAA readiness is the arrangement to use; you do not also need ZDR. See the [feature eligibility table](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#feature-eligibility) for which features each arrangement covers.
<Note>
This page covers HIPAA readiness for the Claude API. For the full HIPAA Implementation Guide covering Claude Enterprise and configuration requirements, see the [Anthropic Trust Center](https://trust.anthropic.com/resources).
</Note>
### What HIPAA readiness covers
* **Claude API:** HIPAA readiness applies to the Claude API (`api.anthropic.com`) for eligible features listed in the [feature eligibility table](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#feature-eligibility).
### What HIPAA readiness does not cover
* **Claude consumer products:** Claude Free, Pro, and Max plans.
* **Console and Workbench:** Usage through the Claude Console interface (enabling HIPAA readiness from Console settings is supported; processing PHI through the Console is not covered).
* **Partner-operated platforms:** Amazon Bedrock and Google Cloud's Agent Platform. Refer to those platforms' compliance documentation.
* **Claude Platform on AWS and Microsoft Foundry:** HIPAA readiness is not available on these platforms.
* **Third-party integrations:** Data processed by external tools or services connected to your application.
* **Claude Code:** Claude Code is not covered under HIPAA readiness.
* **Beta features:** Features in beta are generally not covered under the BAA unless explicitly listed as eligible in the [feature eligibility table](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#feature-eligibility).
* **Flagged content and legal holds:** See [Retention regardless of arrangement](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#retention-regardless-of-arrangement).
### PHI handling guidelines
Protected health information (PHI) includes any individually identifiable health information. In the context of the Claude API, PHI typically appears in message content (prompts and Claude's responses), attached files (images, PDFs), and file names or metadata associated with message content. The following fields are not expected to contain PHI under the BAA: workspace names, user information (name, email, phone number), billing data, and support tickets.
When using [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) or tools with `strict: true`, the API compiles JSON schemas into grammars that are cached separately from message content. These cached schemas do not receive the same PHI protections as prompts and responses. **Do not include PHI in JSON schema definitions.** This restriction applies to schema property names, `enum` values, `const` values, and `pattern` regular expressions. Patient-specific information should appear only in message content, where it is protected under HIPAA safeguards.
### HIPAA error handling
Your signed BAA is the official source of truth for which features are covered. The API also enforces these restrictions automatically. When a HIPAA-enabled organization sends a request that includes a non-eligible feature, the API returns a `400` error to prevent accidental use of features not covered by your BAA:
```json
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "The requested features are not available for HIPAA-regulated organizations without Zero Data Retention: code_execution."
}
}
```
The error message lists the non-eligible features detected in the request; remove them and retry. The phrase "without Zero Data Retention" is the API's own wording and does not change the resolution.
### Getting started with HIPAA readiness
There are two ways to set up HIPAA-ready API access. Most organizations can enable it directly in the Claude Console with Anthropic's standard BAA; organizations that require a negotiated BAA should work with their account team.
#### Enable in the Console (standard BAA)
<Steps>
<Step title="Open your organization's privacy settings">
In [Claude Console > Settings > Privacy](https://platform.claude.com/settings/privacy), organization admins with the HIPAA management permission see a **HIPAA compliance** card. If your organization is eligible but you don't see the option to enable, ask an organization admin to complete these steps.
</Step>
<Step title="Review and execute the BAA">
Download the Business Associate Agreement and the HIPAA Implementation Guide, then accept the agreement as an authorized legal representative of your organization. Each step becomes available after you download the prior document, and your enablement is bound to the exact BAA version you downloaded.
</Step>
<Step title="Enablement takes effect immediately">
HIPAA readiness controls are applied to your organization as soon as you accept. Once HIPAA readiness is enabled for your organization, the configuration is permanent and cannot be disabled by an administrator. The API automatically enforces feature restrictions, returning an error for requests that use non-eligible features. See [HIPAA error handling](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#hipaa-error-handling).
</Step>
</Steps>
#### Contact sales (custom BAA)
If your organization requires a negotiated or custom BAA, or if self-serve enablement isn't available for your organization, contact the [Anthropic sales team](https://claude.com/contact-sales). Anthropic will execute the BAA and enable HIPAA readiness for your organization.
#### Build with eligible features
Whichever path you use, confirm which features are supported in the [feature eligibility table](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#feature-eligibility) and review the [PHI handling guidelines](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#phi-handling-guidelines) for features that restrict where PHI can appear. For detailed configuration and compliance requirements, refer to the [HIPAA Implementation Guide](https://trust.anthropic.com/resources).
<Warning>
HIPAA readiness is enforced at the organization level. If you need both HIPAA-ready and general-purpose API access, use separate organizations for each.
</Warning>
## Model-specific data retention requirements
Claude Fable 5 and Claude Mythos 5 are designated Covered Models (see the [Covered Models support article](https://support.claude.com/en/articles/15425695)) and require 30-day data retention; ZDR is therefore not available for either model. On the Claude API, requests to Claude Fable 5 from an organization whose data retention configuration does not meet this requirement return a `400 invalid_request_error`:
```json
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "In order to access this model, your organization or workspace must have data retention enabled."
}
}
```
The 30-day data retention requirement applies wherever Covered Models are offered. On the Claude API (including Claude Platform on AWS), Anthropic handles retained data. On Amazon Bedrock and Google Cloud's Agent Platform, retained data stays within your cloud provider's environment; review each platform's documentation for enablement steps.
### Enable 30-day retention for a workspace
Organizations with a ZDR arrangement can make Claude Fable 5 and Claude Mythos 5 available in a specific workspace by enabling 30-day retention for that workspace only. Other workspaces in the organization keep zero data retention.
<Steps>
<Step title="Open the workspace's privacy controls">
In [Claude Console > Settings > Workspaces](https://platform.claude.com/settings/workspaces), select the workspace and open its **Privacy controls** tab.
</Step>
<Step title="Turn on 30-day data retention">
Enable the 30-day data retention setting for the workspace.
</Step>
<Step title="Verify">
Requests to Claude Fable 5 and Claude Mythos 5 from this workspace now succeed. Workspaces without an override continue to follow the organization default.
</Step>
</Steps>
## Feature eligibility
The following table lists which Claude API features are eligible for ZDR and HIPAA readiness arrangements.
Each eligibility column uses three values:
* **Yes:** The feature is fully eligible under the arrangement. For ZDR, "Yes" also assumes you are using a model that does not require 30-day data retention; [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements) are not available under ZDR regardless of feature eligibility.
* **Yes (qualified):** Your prompts and Claude's outputs are not stored, but a bounded technical artifact (named in the Details column) is retained briefly for the feature to function. See [How Anthropic approaches data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#how-anthropic-approaches-data-retention) for the commitments that govern these features.
* **No:** The feature is not eligible. Under HIPAA readiness, the API blocks requests that include a "No" feature and returns a `400` error. Under ZDR, the API does **not** block these features; using one is a choice to step outside your ZDR arrangement for that specific data, and the feature's own documented retention policy applies. Features marked "No" for ZDR are typically stateful (they store jobs, files, or container state), which is why they cannot be zero-retention.
| Feature | Endpoint | ZDR eligible | HIPAA eligible | Details |
| -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------ | ------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [1M token context window](https://platform.claude.com/docs/en/build-with-claude/context-windows) | `/v1/messages` | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | |
| [Adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) | `/v1/messages` | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | |
| [Advisor tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/advisor-tool) | `/v1/messages` (with `advisor` tool) | <Eligible>Yes</Eligible> | <Eligible status="no">No</Eligible> | Advisor model output is returned in the API response; nothing is stored server-side after the response. |
| [Agent skills](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview) | `/v1/messages` (with `skills`) / `/v1/skills` | <Eligible status="no">No</Eligible> | <Eligible status="no">No</Eligible> | Skill data retained per standard policy. See [Agent skills](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview#data-retention). |
| [Bash tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/bash-tool) | `/v1/messages` (with `bash` tool) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Client-side tool executed in your environment. |
| [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) | `/v1/messages/batches` | <Eligible status="no">No</Eligible> | <Eligible status="no">No</Eligible> | 29-day retention; async storage required. See [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing#data-retention). |
| [Cache diagnostics](https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics) | `/v1/messages` (with `diagnostics`) | <Eligible status="qualified">Yes (qualified)</Eligible> | <Eligible status="no">No</Eligible> | Your prompts and Claude's outputs are not stored. A fingerprint of cryptographic hashes and token-count estimates is retained briefly to enable comparison against the next request. See [Cache diagnostics](https://platform.claude.com/docs/en/build-with-claude/cache-diagnostics#data-retention). |
| [Citations](https://platform.claude.com/docs/en/build-with-claude/citations) | `/v1/messages` | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | |
| [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) | `/v1/agents`, `/v1/sessions`, `/v1/environments` | <Eligible status="no">No</Eligible> | <Eligible status="no">No</Eligible> | Sessions are stateful resources; transcripts persist until you delete them. Applies to all Managed Agents sub-features, including [Self-hosted sandboxes](https://platform.claude.com/docs/en/managed-agents/self-hosted-sandboxes). |
| [Code execution](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) | `/v1/messages` (with `code_execution` tool) | <Eligible status="no">No</Eligible> | <Eligible status="no">No</Eligible> | Container data retained up to 30 days. See [Code execution](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#data-retention). |
| [Computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool) | `/v1/messages` (with `computer` tool) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Client-side tool where screenshots and files are captured and stored in your environment, not by Anthropic. See [Computer use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool#data-retention). |
| [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) | `/v1/messages` (with `context_management`) | <Eligible>Yes</Eligible> | <Eligible status="no">No</Eligible> | Context edits (tool use clearing and thinking clearing) are applied in real time. |
| [Context management (compaction)](https://platform.claude.com/docs/en/build-with-claude/compaction) | `/v1/messages` (with `context_management`) | <Eligible>Yes</Eligible> | <Eligible status="no">No</Eligible> | Server-side compaction results are returned and round-tripped statelessly through the API response. |
| [Data residency](https://platform.claude.com/docs/en/manage-claude/data-residency) | `/v1/messages` (with `inference_geo`) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | |
| [Effort](https://platform.claude.com/docs/en/build-with-claude/effort) | `/v1/messages` (with `effort`) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | |
| [Fast mode](https://platform.claude.com/docs/en/build-with-claude/fast-mode) | `/v1/messages` (with `speed: "fast"`) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Same Messages API endpoint with faster inference. ZDR applies regardless of speed setting. |
| [Files API](https://platform.claude.com/docs/en/build-with-claude/files) | `/v1/files` | <Eligible status="no">No</Eligible> | <Eligible status="no">No</Eligible> | Files retained until explicitly deleted. See [Files API](https://platform.claude.com/docs/en/build-with-claude/files#data-retention). |
| [Fine-grained tool streaming](https://platform.claude.com/docs/en/agents-and-tools/tool-use/fine-grained-tool-streaming) | `/v1/messages` | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | |
| [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector) | `/v1/messages` (with `mcp_servers`) | <Eligible status="no">No</Eligible> | <Eligible status="no">No</Eligible> | Data retained per standard policy. See [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector#data-retention). |
| [MCP tunnels](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/overview) | `/v1/tunnels` | <Eligible status="no">No</Eligible> | <Eligible status="no">No</Eligible> | Research preview. See [MCP tunnels security](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/security) for the data-flow boundary and subprocessor details. |
| [Memory tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool) | `/v1/messages` (with `memory` tool) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Client-side memory storage where you control data retention. |
| [Messages API](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) | `/v1/messages` | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Standard API calls for generating Claude responses. |
| [Mid-conversation system messages](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages) | `/v1/messages` (with `role: "system"` messages) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Request-shape capability of the Messages API; mid-conversation system messages flow through the standard inference path and nothing is stored server-side after the response. |
| [PDF support](https://platform.claude.com/docs/en/build-with-claude/pdf-support) | `/v1/messages` | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | HIPAA eligibility applies to PDFs sent inline through the Messages API, not through the Files API. |
| [Programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling) | `/v1/messages` (with `code_execution` tool) | <Eligible status="no">No</Eligible> | <Eligible status="no">No</Eligible> | Built on code execution containers; data retained up to 30 days. See [Programmatic tool calling](https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling#data-retention). |
| [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching) | `/v1/messages` | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Your prompts and Claude's outputs are not stored. KV cache representations and cryptographic hashes are held in memory for the cache TTL and promptly deleted after expiry. See [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#data-retention). |
| [Search results](https://platform.claude.com/docs/en/build-with-claude/search-results) | `/v1/messages` (with `search_results` source) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | |
| [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) | `/v1/messages` | <Eligible status="qualified">Yes (qualified)</Eligible> | <Eligible>Yes</Eligible> | Your prompts and Claude's outputs are not stored. Only the JSON schema is cached, for up to 24 hours since last use. This also covers [strict tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use) (`strict: true` on tools), which uses the same grammar pipeline. PHI must not be included in JSON schema definitions; see [PHI handling guidelines](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#phi-handling-guidelines). See [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#data-retention). |
| [Text editor tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/text-editor-tool) | `/v1/messages` (with `text_editor` tool) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Client-side tool executed in your environment. |
| [Thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) | `/v1/messages` (with `thinking`) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | |
| [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting) | `/v1/messages/count_tokens` | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Count tokens before sending requests. |
| [Tool search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool) | `/v1/messages` (with `tool_search` tool) | <Eligible>Yes</Eligible> | <Eligible status="no">No</Eligible> | Server-side tool executed by Anthropic; the tool definitions in the request are searched in memory per call and nothing is stored after the response. |
| [Web fetch](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool) | `/v1/messages` (with `web_fetch` tool) | <Eligible>Yes</Eligible> | <Eligible status="no">No</Eligible> | Fetched web content returned in the API response. [Dynamic filtering](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#dynamic-filtering) is not eligible for ZDR or HIPAA. Website publishers may retain request data (such as fetched URLs and request metadata) according to their own policies. |
| [Web search](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool) | `/v1/messages` (with `web_search` tool) | <Eligible>Yes</Eligible> | <Eligible>Yes</Eligible> | Real-time web search results returned in the API response. [Dynamic filtering](https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool#dynamic-filtering) is not eligible for ZDR or HIPAA. |
## Retention regardless of arrangement
Even with ZDR or HIPAA arrangements in place, Anthropic may retain data where required by law or where it has been flagged by Anthropic's automated trust and safety systems. As a result, if a chat or session is flagged, Anthropic may retain inputs and outputs for up to 2 years.
## Frequently asked questions
<AccordionGroup>
<Accordion title="How do I know if my organization has ZDR arrangements?">
Check your contract terms or contact your Anthropic account representative to confirm whether your organization has ZDR arrangements in place.
</Accordion>
<Accordion title="Can I use ZDR-eligible (qualified) features under my ZDR arrangement?">
Yes. These features retain a minimal, documented set of technical data, not your prompts or Claude's outputs. See the [feature eligibility table](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#feature-eligibility) legend for what "Yes (qualified)" means and [How Anthropic approaches data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#how-anthropic-approaches-data-retention) for the commitments that govern these features.
</Accordion>
<Accordion title="What happens if I use a feature marked "No" under ZDR?">
Nothing blocks the request. Features marked "No" for ZDR are fundamentally stateful: the Batch API stores your jobs, the Files API stores your files, and code execution runs in persistent containers. Data for these features is retained per the feature's documented policy. Using them is a choice to step outside your ZDR arrangement for that specific data.
</Accordion>
<Accordion title="Can I request deletion of data from features that are not ZDR-eligible?">
Contact your Anthropic account representative to discuss deletion options for non-ZDR features.
</Accordion>
<Accordion title="How does HIPAA readiness differ from ZDR?">
ZDR prevents customer data from being stored at rest after the API response is returned. HIPAA readiness involves a broader set of privacy and security safeguards that protect PHI throughout its lifecycle, including encryption, access controls, and audit logging. Under HIPAA readiness, data can be retained with these safeguards in place rather than requiring immediate deletion. The two arrangements cover different feature sets; see the [feature eligibility table](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#feature-eligibility).
</Accordion>
<Accordion title="Do I still need ZDR if I have HIPAA readiness?">
No. HIPAA-ready API access is designed as an alternative to ZDR for organizations handling PHI. With HIPAA readiness enabled, you get access to supported API features while maintaining the privacy and security protections that HIPAA requires.
</Accordion>
<Accordion title="What happens if I use a non-eligible feature under HIPAA?">
The API returns a `400` error with an `invalid_request_error` type. The error message identifies which features are not available. Remove the non-eligible features from your request and retry. See [HIPAA error handling](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#hipaa-error-handling).
</Accordion>
<Accordion title="Can I use the same organization for HIPAA and non-HIPAA workloads?">
No. HIPAA readiness is enforced at the organization level and automatically blocks all non-eligible features. Use a separate organization for workloads that do not require HIPAA readiness.
</Accordion>
<Accordion title="How do I request HIPAA-ready API access?">
Eligible organizations can enable HIPAA readiness directly in [Claude Console > Settings > Privacy](https://platform.claude.com/settings/privacy) by reviewing and executing Anthropic's standard BAA; see [Getting started with HIPAA readiness](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#getting-started-with-hipaa-readiness). If your organization requires a negotiated BAA, or self-serve enablement isn't available for your organization, contact the [Anthropic sales team](https://claude.com/contact-sales).
</Accordion>
<Accordion title="Does this apply to Amazon Bedrock or Google Cloud?">
No. The ZDR and HIPAA arrangements described on this page apply to the Claude API, where Anthropic is the data processor. On Bedrock and Google Cloud, the cloud provider is the data processor; refer to those platforms' data retention and compliance policies for their equivalent controls.
</Accordion>
<Accordion title="Is Claude Platform on AWS eligible for ZDR or HIPAA readiness?">
Claude Platform on AWS follows the same data retention policy as the first-party Claude API. ZDR is available on request; contact your Anthropic account representative to enable it. HIPAA readiness is not available on Claude Platform on AWS. See [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws) for details.
</Accordion>
<Accordion title="Is Claude Code eligible for ZDR?">
Claude Code is eligible for ZDR through two paths:
* **API keys:** Claude Code used with pay-as-you-go API keys from a Commercial organization
* **Claude Enterprise:** Claude Code used through Claude Enterprise with ZDR enabled for the organization
ZDR is enabled on a per-organization basis. Each new organization requires ZDR to be enabled separately by your account team. ZDR does not automatically apply to new organizations created under the same account.
Additionally, if you have metrics logging enabled in Claude Code, productivity data (such as usage statistics) is exempted from ZDR and may be retained.
For full details on ZDR for Claude Code on Claude Enterprise, including disabled features and how to request enablement, see the [Claude Code ZDR documentation](https://code.claude.com/docs/en/zero-data-retention).
</Accordion>
<Accordion title="Does Claude for Excel support ZDR?">
No, Claude for Excel is not currently ZDR-eligible.
</Accordion>
<Accordion title="How do I request ZDR?">
To request a ZDR arrangement, contact the [Anthropic sales team](https://claude.com/contact-sales).
</Accordion>
</AccordionGroup>
## Related resources
* [Privacy Policy](https://www.anthropic.com/legal/privacy)
* [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
* [Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
* [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing)
* [Files API reference](https://platform.claude.com/docs/en/api/beta/files/upload)
* [Trust Center](https://trust.anthropic.com/resources)
manage-claude/app-attest First recorded · 48 lines, first recorded
## How App Attest works ## Set up App Attest ## Revoke an app integration ## Next steps
The first capture of this source. The page was already there, and this is what it said.
---
title: App Attest for iOS and macOS apps
url: https://platform.claude.com/docs/en/manage-claude/app-attest
description: Let genuine installations of your iOS or macOS app call the Claude API without shipping an API key or running a proxy, using Apple's App Attest service.
---
App Attest authenticates iOS and macOS apps that call the Claude API directly from the device, with usage billed to your workspace. This page explains how App Attest works, how to register your app in the Claude Console, and how to revoke an app integration.
Apps use App Attest through the [Claude for Foundation Models](https://github.com/anthropics/ClaudeForFoundationModels) Swift package, which is in beta: it requires the OS 27 betas, and APIs might change before general availability. For the Swift configuration, see [Apple Foundation Models](https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/apple-foundation-models#app-attest-production).
## How App Attest works
Each installation of your app uses Apple's [App Attest](https://developer.apple.com/documentation/devicecheck/establishing-your-app-s-integrity) service to prove that it is a genuine, unmodified build of the app you registered. Anthropic then issues the device a short-lived access token that bills usage to your workspace. The app ships no API key, and there is no proxy for you to operate.
App Attest authentication is available only when your app calls the Claude API directly. It is not available through Amazon Bedrock, Google Cloud, or Microsoft Foundry.
The first time your app uses Claude on a device, the app requests a challenge from Anthropic, attests the device with Apple's `DCAppAttestService`, and exchanges the verified attestation for an access token. The Claude for Foundation Models package runs this flow automatically and requests new tokens as they expire; there is no attestation code for you to write.
Tokens are scoped to your workspace, expire after one hour, and authorize only [Messages API](https://platform.claude.com/docs/en/api/messages/create) calls. They carry no end-user identity: App Attest identifies your app, not the person using it, so handle any per-user logic in your app.
## Set up App Attest
<Note>
App Attest requires a physical device. The Simulator, and hardware without a Secure Enclave, cannot perform App Attest. While developing in the Simulator, authenticate with an [API key](https://platform.claude.com/docs/en/manage-claude/authentication#api-keys) instead.
</Note>
To set up App Attest, you need your Apple Developer Team ID and the admin, owner, or primary owner role in your organization. Configure your Xcode project and register your app in the [Claude Console](https://platform.claude.com/):
1. In Xcode, add the **App Attest** capability to your app target under **Signing & Capabilities**.
2. In your workspace's settings in the Claude Console, open **App integrations**.
3. Click **Create app integration** and enter a name, your Apple Developer Team ID, and one or more bundle IDs (up to 32).
4. Copy the client ID (`clid_...`) from the integration's **Overview** tab and pass it to your app's Claude configuration.
## Revoke an app integration
To stop a compromised or retired app, revoke its integration: in your workspace's settings in the Claude Console, open **App integrations**, select the integration, and click **Revoke**, then confirm. Revoking an integration revokes its outstanding tokens, and its registered devices can no longer request new ones. Revocation is permanent, so create a new app integration to restore access.
## Next steps
<CardGroup cols={2}>
<Card title="Apple Foundation Models" icon="code" href="https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/apple-foundation-models#app-attest-production">
Configure App Attest in the Claude for Foundation Models Swift package
</Card>
<Card title="Authentication" icon="lock" href="https://platform.claude.com/docs/en/manage-claude/authentication">
Compare API keys, Workload Identity Federation, and App Attest
</Card>
</CardGroup>
manage-claude/authentication First recorded · 152 lines, first recorded
## API keys ### Key expiration ## Workload Identity Federation ## App Attest ## Next steps
The first capture of this source. The page was already there, and this is what it said.
---
title: Authentication
url: https://platform.claude.com/docs/en/manage-claude/authentication
description: Authenticate to the Claude API with API keys, Workload Identity Federation, or App Attest.
---
The Claude API supports three ways to authenticate requests:
| Method | Credential | Best for |
| ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| [API key](https://platform.claude.com/docs/en/manage-claude/authentication#api-keys) | Static `sk-ant-api...` secret in the `x-api-key` header | Local development, prototyping, scripts, and single-tenant servers where you control secret storage |
| [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/authentication#workload-identity-federation) | Short-lived bearer token exchanged from your identity provider's identity token | Production workloads on cloud platforms (AWS, Google Cloud, Azure), CI/CD pipelines, and Kubernetes, where you want to eliminate static secrets |
| [App Attest](https://platform.claude.com/docs/en/manage-claude/authentication#app-attest) | Short-lived access token issued to a genuine, attested installation of your registered iOS or macOS app | iOS and macOS apps distributed to end users, where the app calls the Claude API directly with no back end or proxy |
API keys and Workload Identity Federation grant the same access to Claude API endpoints. Choose API keys to get started quickly, and move to Workload Identity Federation when your workload already has a platform-issued identity you can federate. Use App Attest for iOS and macOS apps you distribute to end users.
## API keys
API keys are static secrets that you generate in the Claude Console and pass on every request.
* **Create a key:** Go to [Settings → API keys](https://platform.claude.com/settings/keys) in the Claude Console. You choose an [expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration) as part of creation. Use [workspaces](https://platform.claude.com/settings/workspaces) to scope keys by project or environment.
* **Send the key:** Set the `x-api-key` header on direct HTTP requests, or set the `ANTHROPIC_API_KEY` environment variable and the [client SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) pick it up automatically.
```http
POST /v1/messages
x-api-key: YOUR_API_KEY
anthropic-version: 2023-06-01
content-type: application/json
```
Store API keys in a secrets manager, rotate them periodically, and revoke any key you suspect has leaked. You can also set an [expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration) when you create a key to limit how long a leaked credential stays usable.
<CodeGroup>
```bash cURL
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-opus-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello, Claude"}]
}'
```
```python Python
client = Anthropic(api_key="my-anthropic-api-key")
# or, with ANTHROPIC_API_KEY set in the environment:
client = Anthropic()
```
```typescript TypeScript
const client = new Anthropic({ apiKey: "my-anthropic-api-key" });
// or, with ANTHROPIC_API_KEY set in the environment:
// const client = new Anthropic();
```
```go Go
client := anthropic.NewClient(
option.WithAPIKey("sk-ant-api03-..."), // defaults to os.LookupEnv("ANTHROPIC_API_KEY")
)
```
```java Java
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
// Explicit
AnthropicClient client = AnthropicOkHttpClient.builder()
.apiKey("my-anthropic-api-key")
.build();
// From ANTHROPIC_API_KEY (or anthropic.apiKey system property)
AnthropicClient clientFromEnv = AnthropicOkHttpClient.fromEnv();
```
```csharp C#
using Anthropic;
AnthropicClient client = new() { ApiKey = "my-anthropic-api-key" };
// Or, with ANTHROPIC_API_KEY set in the environment:
// AnthropicClient client = new();
```
```php PHP
// Reads ANTHROPIC_API_KEY from the environment
$client = new Client();
// Or pass the key explicitly:
$client = new Client(apiKey: 'my-anthropic-api-key');
```
```ruby Ruby
anthropic = Anthropic::Client.new(api_key: "my-anthropic-api-key")
# or, with ANTHROPIC_API_KEY set in the environment:
anthropic = Anthropic::Client.new
```
```bash CLI
# See /docs/en/cli-sdks-libraries/cli/authentication#api-key for zsh, bash, and Windows variants
export ANTHROPIC_API_KEY=sk-ant-api03-...
```
</CodeGroup>
### Key expiration
When you create an API key from the [API keys page](https://platform.claude.com/settings/keys) in the Claude Console, you choose an expiration: a preset (3 hours, 1 day, 7 days, or 30 days), a custom duration, or **Never** for keys you store in a secrets manager and rotate yourself. If your organization has a maximum expiration policy, the Console limits presets and custom durations to the policy maximum, and **Never** is unavailable. Existing keys keep their current behavior; expiration is set at creation time and cannot be changed afterward. The same expiration choice applies when you [create an Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) in the Claude Console.
Anthropic emails the key's creator as the expiration approaches: 7 days before expiration for keys created with a lifetime of at least 14 days, and 1 day before for keys with a lifetime of at least 7 days. Keys with shorter lifetimes expire without a warning email.
After a key expires, requests made with it return a `401 authentication_error`. Create a new key to restore access; expired keys cannot be reactivated.
The Console API keys table shows each key's expiration, and the Admin API reports each key's `expires_at` timestamp on the [List API Keys](https://platform.claude.com/docs/en/api/admin/api_keys/list) and [Retrieve API Key](https://platform.claude.com/docs/en/api/admin/api_keys/retrieve) endpoints, so you can audit and rotate keys before they expire. The field is `null` for keys without an expiration.
Expiration limits the lifetime of a leaked credential, but it is not a substitute for secret hygiene. Regardless of expiration, store keys in a secrets manager and revoke any key you suspect has leaked.
## Workload Identity Federation
Workload Identity Federation (WIF) lets a workload authenticate with a short-lived identity token issued by an identity provider (IdP) you already trust, such as AWS IAM, Google Cloud, or any standards-compliant OIDC issuer (such as GitHub Actions, Kubernetes service accounts, SPIFFE, Microsoft Entra ID, or Okta). The workload exchanges its IdP-issued JWT at `POST /v1/oauth/token` for a short-lived Claude API access token, and the SDK refreshes that token automatically before it expires. There is no `sk-ant-api...` string to mint, distribute, or rotate.
Federation removes long-lived Claude API keys from your environment, which shrinks the blast radius of a leaked credential and lets you manage access with the same IdP controls you already use for cloud resources. It does not, on its own, guarantee end-to-end security: the trust chain is only as strong as your identity provider's configuration, and a long-lived secret one hop upstream (for example, a static cloud credential that can mint IdP tokens) can still undermine it. Pair federation with your provider's controls, such as IP allowlists, MFA, and audit logging.
To configure federation, you create three resources in the Claude Console (a service account, a federation issuer, and a federation rule) and then point your SDK at the rule. See [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) for the full setup walkthrough.
## App Attest
App Attest authenticates iOS and macOS apps that call the Claude API directly from the device. Each installation proves that it is a genuine, unmodified build of an app you registered in the Claude Console, using Apple's App Attest service. Anthropic then issues the device a short-lived access token that bills usage to your workspace. Tokens are scoped to your workspace, expire after one hour, and authorize only [Messages API](https://platform.claude.com/docs/en/api/messages/create) calls.
To register your app and get a client ID, see [App Attest for iOS and macOS apps](https://platform.claude.com/docs/en/manage-claude/app-attest).
## Next steps
<CardGroup cols={2}>
<Card title="Set up Workload Identity Federation" icon="lock" href="https://platform.claude.com/docs/en/manage-claude/workload-identity-federation">
Configure issuers, rules, and service accounts, then exchange tokens
</Card>
<Card title="Identity provider guides" icon="cloud" href="https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#identity-providers">
Step-by-step guides for AWS, Google Cloud, Azure, GitHub Actions, Kubernetes, SPIFFE, and Okta
</Card>
<Card title="WIF reference" icon="book" href="https://platform.claude.com/docs/en/manage-claude/wif-reference">
Environment variables, validation rules, profile configuration, and error reference
</Card>
<Card title="App Attest for iOS and macOS apps" icon="fingerprint" href="https://platform.claude.com/docs/en/manage-claude/app-attest">
Let genuine installations of your app call the Claude API without shipping an API key
</Card>
<Card title="Client SDKs" icon="code" href="https://platform.claude.com/docs/en/cli-sdks-libraries/overview">
Python, TypeScript, C#, Go, Java, PHP, Ruby, and the CLI
</Card>
</CardGroup>
manage-claude/claude-code-analytics-api First recorded · 279 lines, first recorded
## Quick start ## Claude Code Analytics API ### Key concepts ### Basic examples #### Get analytics for a specific day #### Get analytics with pagination ### Request parameters ### Available metrics #### Dimensions #### Core metrics #### Tool action metrics #### Model breakdown ### Response structure ## Pagination ## Common use cases ## Frequently asked questions ### How fresh is the analytics data? ### Can I get real-time metrics? ### How are users identified in the data? ### What's the data retention period? ### Which Claude Code deployments are supported? ### What does it cost to use this API? ### How do I calculate tool acceptance rates? ### What time zone is used for the date parameter? ## See also
The first capture of this source. The page was already there, and this is what it said.
---
title: Claude Code Analytics API
url: https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api
description: Programmatically access your organization's Claude Code usage analytics and productivity metrics with the Claude Code Analytics Admin API.
---
<Tip>
**The Admin API is unavailable for individual accounts.** To collaborate with teammates and add members, set up your organization in **Console → Settings → Organization**.
</Tip>
The Claude Code Analytics Admin API provides programmatic access to daily aggregated usage metrics for Claude Code users, enabling organizations to analyze developer productivity and build custom dashboards. This API provides more detail than the basic [Analytics dashboard](https://platform.claude.com/claude-code) without the complexity of the OpenTelemetry integration.
This API enables you to better monitor, analyze, and optimize your Claude Code adoption:
* **Developer productivity analysis:** Track sessions, lines of code added/removed, commits, and pull requests created using Claude Code
* **Tool usage metrics:** Monitor acceptance and rejection rates for different Claude Code tools (Edit, MultiEdit, Write, NotebookEdit)
* **Cost analysis:** View estimated costs and token usage broken down by Claude model
* **Custom reporting:** Export data to build executive dashboards and reports for management teams
* **Usage justification:** Provide metrics to justify and expand Claude Code adoption internally
<Check>
**Admin API key required.** These endpoints require an Admin API key, which is different from a standard Claude API key. See [Create an Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) to find where to create one for your organization type and which scopes to select.
</Check>
<Note>
**Claude Platform on AWS:** The Claude Code Analytics API is not currently available. View Claude Code usage on the **Usage** page in the Claude Console instead.
</Note>
<Note>
**Claude Enterprise organizations:** Claude Code activity for claude.ai users is reported by the Claude Enterprise Analytics API, which uses an Analytics API key instead of an Admin API key. See [Analytics APIs](https://platform.claude.com/docs/en/manage-claude/analytics-api) to find which API and key type your organization needs.
</Note>
## Quick start
Get your organization's Claude Code analytics for a specific day:
```bash cURL
curl "https://api.anthropic.com/v1/organizations/usage_report/claude_code?\
starting_at=2025-09-08&\
limit=20" \
-H "anthropic-version: 2023-06-01" \
-H "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
<Tip>
**Set a User-Agent header for integrations**
If you're building an integration, set your User-Agent header to help Anthropic understand usage patterns:
```text wrap
User-Agent: YourApp/1.0.0 (https://yourapp.com)
```
</Tip>
## Claude Code Analytics API
Track Claude Code usage, productivity metrics, and developer activity across your organization with the `/v1/organizations/usage_report/claude_code` endpoint.
### Key concepts
* **Daily aggregation:** Returns metrics for a single day specified by the `starting_at` parameter
* **User-level data:** Each record represents one user's activity for the specified day
* **Productivity metrics:** Track sessions, lines of code, commits, pull requests, and tool usage
* **Token and cost data:** Monitor usage and estimated costs broken down by Claude model
* **Cursor-based pagination:** Handle large datasets with stable pagination using opaque cursors
* **Data freshness:** Metrics are available with up to 1-hour delay for consistency
For complete parameter details and response schemas, see the [Claude Code Analytics API reference](https://platform.claude.com/docs/en/api/admin/usage_report/retrieve_claude_code).
### Basic examples
#### Get analytics for a specific day
```bash cURL
curl "https://api.anthropic.com/v1/organizations/usage_report/claude_code?\
starting_at=2025-09-08" \
-H "anthropic-version: 2023-06-01" \
-H "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
#### Get analytics with pagination
```bash cURL
# First request
curl "https://api.anthropic.com/v1/organizations/usage_report/claude_code?\
starting_at=2025-09-08&\
limit=20" \
-H "anthropic-version: 2023-06-01" \
-H "x-api-key: $ANTHROPIC_ADMIN_KEY"
# Subsequent request using cursor from response
curl "https://api.anthropic.com/v1/organizations/usage_report/claude_code?\
starting_at=2025-09-08&\
page=page_MjAyNS0wNS0xNFQwMDowMDowMFo=" \
-H "anthropic-version: 2023-06-01" \
-H "x-api-key: $ANTHROPIC_ADMIN_KEY"
```
### Request parameters
| Parameter | Type | Required | Description |
| ------------- | ------- | -------- | ----------------------------------------------------------------------- |
| `starting_at` | string | Yes | UTC date in YYYY-MM-DD format; returns metrics for this single day only |
| `limit` | integer | No | Number of records per page (default: 20, max: 1000) |
| `page` | string | No | Opaque cursor token from previous response's `next_page` field |
### Available metrics
Each response record contains the following metrics for a single user on a single day:
#### Dimensions
* **date:** Date in RFC 3339 format (UTC timestamp)
* **actor:** The user or API key that performed the Claude Code actions (either `user_actor` with `email_address` or `api_actor` with `api_key_name`)
* **organization\_id:** Organization UUID
* **customer\_type:** Type of customer account (`api` for API customers, `subscription` for Pro/Team customers)
* **terminal\_type:** Type of terminal or environment where Claude Code was used (for example, `vscode`, `iTerm.app`, `tmux`)
#### Core metrics
* **num\_sessions:** Number of distinct Claude Code sessions initiated by this actor
* **lines\_of\_code.added:** Total number of lines of code added across all files by Claude Code
* **lines\_of\_code.removed:** Total number of lines of code removed across all files by Claude Code
* **commits\_by\_claude\_code:** Number of git commits created through Claude Code's commit functionality
* **pull\_requests\_by\_claude\_code:** Number of pull requests created through Claude Code's PR functionality
#### Tool action metrics
Breakdown of tool action acceptance and rejection rates by tool type:
* **edit\_tool.accepted/rejected:** Number of Edit tool proposals that the user accepted/rejected
* **multi\_edit\_tool.accepted/rejected:** Number of MultiEdit tool proposals that the user accepted/rejected
* **write\_tool.accepted/rejected:** Number of Write tool proposals that the user accepted/rejected
* **notebook\_edit\_tool.accepted/rejected:** Number of NotebookEdit tool proposals that the user accepted/rejected
#### Model breakdown
For each Claude model used:
* **model:** Claude model identifier (for example, `claude-opus-5`)
* **tokens.input/output:** Input and output token counts for this model
* **tokens.cache\_read/cache\_creation:** Cache-related token usage for this model
* **estimated\_cost.amount:** Estimated cost in cents USD for this model
* **estimated\_cost.currency:** Currency code for the cost amount (currently always `USD`)
### Response structure
The API returns data in the following format:
```json
{
"data": [
{
"date": "2025-09-08T00:00:00Z",
"actor": {
"type": "user_actor",
"email_address": "[email protected]"
},
"organization_id": "dc9f6c26-b22c-4831-8d01-0446bada88f1",
"customer_type": "api",
"terminal_type": "vscode",
"core_metrics": {
"num_sessions": 5,
"lines_of_code": {
"added": 1543,
"removed": 892
},
"commits_by_claude_code": 12,
"pull_requests_by_claude_code": 2
},
"tool_actions": {
"edit_tool": {
"accepted": 45,
"rejected": 5
},
"multi_edit_tool": {
"accepted": 12,
"rejected": 2
},
"write_tool": {
"accepted": 8,
"rejected": 1
},
"notebook_edit_tool": {
"accepted": 3,
"rejected": 0
}
},
"model_breakdown": [
{
"model": "claude-opus-5",
"tokens": {
"input": 100000,
"output": 35000,
"cache_read": 10000,
"cache_creation": 5000
},
"estimated_cost": {
"currency": "USD",
"amount": 141
}
}
]
}
],
"has_more": false,
"next_page": null
}
```
## Pagination
The API supports cursor-based pagination for organizations with large numbers of users:
1. Make your initial request with optional `limit` parameter.
2. If `has_more` is `true` in the response, use the `next_page` value in your next request.
3. Continue until `has_more` is `false`.
The cursor encodes the position of the last record and ensures stable pagination even as new data arrives. Each pagination session maintains a consistent data boundary to ensure you don't miss or duplicate records.
## Common use cases
* **Executive dashboards:** Create high-level reports showing Claude Code impact on development velocity
* **AI tool comparison:** Export metrics to compare Claude Code with other AI coding tools such as Copilot and Cursor
* **Developer productivity analysis:** Track individual and team productivity metrics over time
* **Cost tracking and allocation:** Monitor spending patterns and allocate costs by team or project
* **Adoption monitoring:** Identify which teams and users are getting the most value from Claude Code
* **ROI justification:** Provide concrete metrics to justify and expand Claude Code adoption internally
## Frequently asked questions
### How fresh is the analytics data?
Claude Code analytics data typically appears within 1 hour of user activity completion. To ensure consistent pagination results, only data older than 1 hour is included in responses.
### Can I get real-time metrics?
No, this API provides daily aggregated metrics only. For real-time monitoring, consider using the [OpenTelemetry integration](https://code.claude.com/docs/en/monitoring-usage).
### How are users identified in the data?
Users are identified through the `actor` field in two ways:
* **`user_actor`:** Contains `email_address` for users who authenticate through OAuth (most common)
* **`api_actor`:** Contains `api_key_name` for users who authenticate with an API key
The `customer_type` field indicates whether the usage is from `api` customers (pay-as-you-go API) or `subscription` customers (Pro/Team plans).
### What's the data retention period?
Historical Claude Code analytics data is retained and accessible through the API. There is no specified deletion period for this data.
### Which Claude Code deployments are supported?
This API only tracks Claude Code usage on the Claude API. Usage through [Claude in Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock), [Claude in Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry), [Claude on Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai), or [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws) is not included.
### What does it cost to use this API?
The Claude Code Analytics API is free to use for all organizations with access to the Admin API.
### How do I calculate tool acceptance rates?
Tool acceptance rate = `accepted / (accepted + rejected)` for each tool type. For example, if the edit tool shows 45 accepted and 5 rejected, the acceptance rate is 90%.
### What time zone is used for the date parameter?
All dates are in UTC. The `starting_at` parameter should be in YYYY-MM-DD format and represents UTC midnight for that day.
## See also
The Claude Code Analytics API helps you understand and optimize your team's development workflow. Learn more about related features:
* [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api)
* [Admin API reference](https://platform.claude.com/docs/en/api/admin)
* [Claude Code Analytics dashboard](https://platform.claude.com/claude-code)
* [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api) - Track API usage across all Anthropic services
* [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api) - Retrieve audit and activity data
* [Identity and access management](https://code.claude.com/docs/en/iam)
* [Monitoring usage with OpenTelemetry](https://code.claude.com/docs/en/monitoring-usage) for custom metrics and alerting
manage-claude/cmek First recorded · 165 lines, first recorded
## How it works ## Prerequisites ## Availability and regions ## What CMEK protects ### Encrypted ### Disabled or modified ### Not encrypted ### Feature support ## Limited preservation outside your key ## Limitations ## Configure your provider
The first capture of this source. The page was already there, and this is what it said.
---
title: Customer-managed encryption keys
url: https://platform.claude.com/docs/en/manage-claude/cmek
description: Encrypt Claude workspace data at rest with a key you control.
---
```bash Learn more with the /claude-api skill in Claude Code
claude "/claude-api tell me about customer-managed encryption keys"
```
A customer-managed encryption key (CMEK) lets you provision an encryption key in your own [AWS KMS](https://aws.amazon.com/kms/), [Google Cloud KMS](https://cloud.google.com/security/products/security-key-management), or [Azure Key Vault](https://azure.microsoft.com/en-us/products/key-vault) and have Anthropic use it to encrypt certain workspace data at rest. You retain full control of the key, including rotation, audit, and revocation, and the key operations Anthropic performs against your key are recorded in your cloud provider's audit logs.
The use of CMEK is optional. Eligible organizations can **opt in** to use customer-managed encryption keys instead of the default encryption that Anthropic provides. To activate CMEK, contact your Anthropic account team.
<Warning>
**Enabling CMEK is permanent and can cause irreversible data loss**
Enabling CMEK is permanent. Anthropic keeps no copy of your key, so misconfiguration or key loss can permanently destroy your CMEK-protected data. If you are uncertain about any step, contact your Anthropic representative before applying changes.
* **Permanent data loss:** If your encryption key is deleted, scheduled for deletion, or has its key material destroyed, Anthropic cannot recover your data.
* **Identifier verification is mandatory:** Granting key access to an incorrect or spoofed principal can expose your data to an unauthorized party. Always verify the Anthropic identifier against the published production identities in each configuration guide. Never trust an identifier provided over email, chat, or any onboarding channel.
</Warning>
## How it works
Only Organization Admins (on Claude Platform) or Owners and the Primary Owner (on Claude Enterprise) can configure CMEK. On Claude Platform, CMEK is scoped per workspace and configured with the Admin API. On Claude Enterprise, CMEK is scoped per organization and configured in [claude.ai > Organization settings > Data and privacy](https://claude.ai/admin-settings/data-privacy-controls). On either product, CMEK protects data written after the key is enabled. Existing data (prior chats, files, and sessions) remains encrypted with Anthropic-managed keys and is not re-encrypted under your key.
CMEK configuration events appear in the [Compliance API Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed). The key operations Anthropic performs against your key (such as wrapping and unwrapping data keys) do not appear in the Compliance API; they appear in your cloud provider's audit logs.
Anthropic calls your key management service from its standard public IP range. If you restrict access to your key management service by IP, allow the addresses listed in [IP addresses](https://platform.claude.com/docs/en/api/ip-addresses).
## Prerequisites
* Permissions to create encryption keys and manage key access in the account, project, or subscription that will host the encryption key.
* An Organization Admin role in the Claude Console on Claude Platform, or an Owner or Primary Owner role on Claude Enterprise.
* Data retention configuration: CMEK is allowed with [Zero data retention (ZDR)](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention) for both Claude Platform and Claude Enterprise.
## Availability and regions
CMEK is currently available in US regions only, and all encryption operations are processed in US regions.
On [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws), CMEK is available with AWS KMS keys only; Google Cloud KMS and Azure Key Vault keys cannot be registered. Create, validate, and attach keys in the Claude Console; the `external_keys` API endpoints are not currently available on Claude Platform on AWS. The key must be in the same AWS region as the workspace it is attached to.
For minimal latency, choose a region close to Anthropic's US infrastructure:
| Provider | Recommended regions |
| ------------ | --------------------------- |
| AWS | `us-east-2` |
| Google Cloud | `us-central1`, `us-east5` |
| Azure | `northcentralus`, `eastus2` |
## What CMEK protects
What CMEK covers depends on which product you use.
### Encrypted
**Claude Platform**
* Message content, files and attachments (both inline attachments sent with a request and Files API uploads), and MCP and tool configuration.
* [Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) data, including agent configurations, environments, webhooks, and sessions and their events.
**Claude Enterprise**
* Chat content, including skills, plugins, and artifacts.
* Chat attachments and project attachments.
* Claude Code on the CLI, including message content.
* Cowork in Claude Desktop.
* Office agents.
* Claude in Chrome.
On both products, backups and snapshots inherit the key.
### Disabled or modified
Some features are turned off or substantially modified when CMEK is enabled. This list is not exhaustive; review it with your team before enabling CMEK.
**Claude Platform**
* Workbench in the Claude Console is disabled.
* Portions of the Compliance API that return raw content, such as prompts, responses, and files, are disabled.
* In Claude Managed Agents, [memory stores](https://platform.claude.com/docs/en/managed-agents/memory) and [dreams](https://platform.claude.com/docs/en/managed-agents/dreams) are disabled. Requests to these endpoints from a CMEK-protected workspace return an `invalid_request_error` (HTTP 400). To use memory stores or dreams, send requests from a workspace without CMEK.
* Other beta and research preview features may not be covered by CMEK.
**Claude Enterprise**
* Conversation history search is disabled. Conversation titles are encrypted, so searching by title or content returns no results.
* Search across large numbers of files is slower.
* Certain analytics are degraded: admin analytics for claude.ai skills and connectors (under claude.ai/analytics/usage and through the [Claude Enterprise Analytics API](https://platform.claude.com/docs/en/manage-claude/analytics-api)), Claude smart reports (under claude.ai/analytics/insights), and Claude Code contribution metrics (under claude.ai/analytics/claude-code).
* Audit log exports are disabled.
* Signed URLs for temporary file exchanges are disabled. These back organization data exports in claude.ai and Claude Code Remote file flows such as screenshot updates.
* Personal preferences are disabled for users who belong to a CMEK-protected organization, across all organizations under the same parent. Users who do not belong to a CMEK-protected organization can still use them across all organizations.
* Compliance API [local session transcripts](https://platform.claude.com/docs/en/manage-claude/compliance-sessions#retrieve-local-sessions) (Cowork and Claude Code on users' machines) currently return no message content. Session metadata is listed as usual, and the local session messages endpoint (`GET /v1/compliance/apps/sessions/local/{session_id}/messages`) returns each message with its content marked unavailable; see [Retrieve a local session transcript](https://platform.claude.com/docs/en/manage-claude/compliance-sessions#retrieve-a-local-session-transcript) for the response shape.
### Not encrypted
These features remain available, but their data is not encrypted under your key. You can disable any feature that is not appropriate for your use case in **Settings**.
**Claude Platform**
* Data that is not at rest (such as cache) and data with a TTL shorter than 24 hours.
* Activity Feed, audit logs, and telemetry network traffic such as OTEL, so customers can maintain compliance even if a key is revoked.
* Claude Managed Agents [vault credential](https://platform.claude.com/docs/en/managed-agents/vaults) values, such as OAuth tokens and client secrets. These are stored under Anthropic-managed encryption, are write-only, and are never returned in API responses.
* [User profiles](https://platform.claude.com/docs/en/api/beta/user_profiles): the `name`, `external_id`, and `metadata` fields are stored under Anthropic-managed encryption, not your key. Do not store sensitive personal data in profile `metadata`.
**Claude Enterprise**
* Claude Code Desktop, Claude Code on the web, and Claude in Slack. Anthropic recommends disabling any of these that are not appropriate for your use case in the admin console.
* Beta and research preview features may not be covered by CMEK and can break in CMEK organizations, for example, Claude Security and Claude Design.
* On-demand data export under **Settings** > **Privacy**.
On both products, account data for users in your organization (such as names, email addresses, and profile pictures) is not encrypted under your key.
### Feature support
The following Claude Platform APIs and tools store data at rest under your key when CMEK is enabled:
| APIs | Tools and features |
| -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| Messages | Web search |
| Models | Web fetch |
| Files | Code execution |
| Batch | Bash tool |
| Skills | Text editor tool |
| Claude Managed Agents (memory stores and dreams not available) | MCP connector |
| | Structured outputs (not available for Claude Fable 5 or Claude Mythos models in CMEK organizations) |
| | Advisor tool |
| | Computer use |
| | Context management |
## Limited preservation outside your key
In three narrow cases, Anthropic may preserve specific records under Anthropic-managed encryption:
* Where Anthropic is required by law to retain records (for example, material reported to NCMEC under 18 U.S.C. § 2258A).
* Exigent risk of serious harm (for example, CBRNE weapons development, offensive cyberattacks, or imminent threats of violence).
* Violations of Section D.4 of Anthropic's [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) or equivalent terms in a customer's other applicable agreement with Anthropic.
Outside of [CSAM screening](https://support.claude.com/en/articles/9020328-csam-detection-and-reporting), preservation requires a human reviewer's explicit decision and follows Anthropic's [retention policy for commercial data](https://privacy.claude.com/en/articles/10023548-how-long-do-you-store-my-data). For every instance of preservation, a corresponding [Compliance API Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed) event is generated with a reason code conveying the purpose of the preservation. See [CMEK content preservation](https://platform.claude.com/docs/en/manage-claude/access-transparency#cmek-content-preservation) for details. Safety screening metadata (records derived from Anthropic's automated safety scans, such as pattern identifiers and match indicators, not conversation content) is retained under Anthropic-managed encryption and remains readable after key revocation.
## Limitations
* **Irreversible action:** Once a key is attached to a workspace, it cannot be detached or swapped. On Claude Platform, attaching a key also locks the workspace's data retention setting: you cannot turn off 30-day data retention for that workspace, and returning to zero data retention requires creating a new workspace and moving your traffic to it. Rotating the key material within the same key (for example, AWS KMS automatic rotation, a Cloud KMS rotation schedule, or an Azure Key Vault rotation policy) is supported transparently and requires no change in Anthropic. Switching to a *different* key requires creating a new workspace with the new key and migrating your data. Revoking or disabling the key makes all CMEK-protected data in that workspace permanently inaccessible, with no backout path.
* **No retroactive encryption:** CMEK only protects data written after the key is enabled.
* **Latency:** Operations that wrap or unwrap data keys make a round-trip to your key management service, which can add a small amount of latency to actions that read or write data at rest.
* **Revocation delay:** Key revocation can take up to 1 hour (the cache TTL). Requests already in flight during that window may continue to succeed.
* **KMS costs:** CMEK requires a key in a third-party key management service (AWS KMS, Google Cloud KMS, or Azure Key Vault), which may incur separate charges billed by your KMS provider.
## Configure your provider
Follow the guide for the key management service you use.
<CardGroup cols={3}>
<Card href="https://platform.claude.com/docs/en/manage-claude/cmek-aws-kms" title="AWS KMS">
Create an AWS KMS key with a cross-account key policy, then register and validate it.
</Card>
<Card href="https://platform.claude.com/docs/en/manage-claude/cmek-google-cloud-kms" title="Google Cloud KMS">
Create a Cloud KMS crypto key, grant Anthropic's service account access, then register it.
</Card>
<Card href="https://platform.claude.com/docs/en/manage-claude/cmek-azure-key-vault" title="Azure Key Vault">
Create an RSA key, grant the Anthropic service principal access, then register and validate it.
</Card>
</CardGroup>
manage-claude/cmek-aws-kms First recorded · 217 lines, first recorded
## Prerequisites ## Amazon Resource Name (ARN) for Anthropic ## Encryption key setup ## Register the key with Anthropic ## Terraform
The first capture of this source. The page was already there, and this is what it said.
---
title: Configure AWS KMS for CMEK
url: https://platform.claude.com/docs/en/manage-claude/cmek-aws-kms
description: Use AWS KMS to provide an encryption key for your organization.
---
```bash Configure with the /claude-api skill in Claude Code
claude "/claude-api help me configure a customer-managed encryption key with AWS KMS"
```
This guide walks through configuring an [AWS KMS](https://aws.amazon.com/kms/) key as a [customer-managed encryption key (CMEK)](https://platform.claude.com/docs/en/manage-claude/cmek) for your Anthropic organization.
<Warning>
Enabling CMEK is permanent. If your KMS key is deleted or disabled, Anthropic cannot recover the data encrypted under it. Review the [warnings and limitations](https://platform.claude.com/docs/en/manage-claude/cmek) before you begin.
</Warning>
## Prerequisites
* An AWS account with permissions to create KMS keys and set key policies (`kms:CreateKey` and `kms:PutKeyPolicy`).
* An Anthropic Admin API key for your organization.
* The [AWS CLI](https://aws.amazon.com/cli/) installed and authenticated.
## Amazon Resource Name (ARN) for Anthropic
To have Anthropic use your encryption key, you must give Anthropic's IAM role a KMS key it can use for encrypting data. The ARN for Anthropic CMEK is:
```text wrap
arn:aws:iam::915198916910:role/anthropic-cmek-client-us
```
<Warning>
Use only this published ARN. Never trust an identifier provided over email, chat, or any onboarding channel.
</Warning>
## Encryption key setup
<Steps>
<Step title="Create the KMS key with a cross-account key policy">
The key policy grants Anthropic's IAM role cross-account access. Three statements are required:
1. **Account root admin:** the standard KMS pattern. Your account retains full admin control.
2. **Anthropic encrypt and decrypt:** the `kms:Encrypt` and `kms:Decrypt` actions, which Anthropic uses to encrypt and decrypt the data keys that protect your workspace data (envelope encryption).
3. **Anthropic describe:** the metadata read Anthropic performs at startup. It is granted separately because `DescribeKey` has no `EncryptionContext` parameter, so an `EncryptionContext` condition on this action would always deny.
```bash
export YOUR_ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
aws kms create-key \
--region <region> \
--description "Anthropic CMEK" \
--key-usage ENCRYPT_DECRYPT \
--policy "{
\"Version\": \"2012-10-17\",
\"Statement\": [
{
\"Sid\": \"AccountRootAdmin\",
\"Effect\": \"Allow\",
\"Principal\": {\"AWS\": \"arn:aws:iam::${YOUR_ACCOUNT}:root\"},
\"Action\": \"kms:*\",
\"Resource\": \"*\"
},
{
\"Sid\": \"AllowAnthropicCMEKCrypto\",
\"Effect\": \"Allow\",
\"Principal\": {\"AWS\": \"arn:aws:iam::915198916910:role/anthropic-cmek-client-us\"},
\"Action\": [\"kms:Encrypt\", \"kms:Decrypt\"],
\"Resource\": \"*\",
\"Condition\": {
\"StringEquals\": {
\"kms:EncryptionContext:anthropic:compartment_uuid\": [
\"00000000-0000-0000-0000-000000000000\",
\"<compartment-uuid>\"
]
}
}
},
{
\"Sid\": \"AllowAnthropicCMEKDescribe\",
\"Effect\": \"Allow\",
\"Principal\": {\"AWS\": \"arn:aws:iam::915198916910:role/anthropic-cmek-client-us\"},
\"Action\": \"kms:DescribeKey\",
\"Resource\": \"*\"
}
]
}"
```
Capture `KeyMetadata.Arn` from the output. You need it when you register the key in the next step.
The `EncryptionContext` condition is recommended but optional. Anthropic always includes your workspace's compartment ID in the encryption context, so ciphertext is cryptographically bound to that compartment regardless. Adding the condition provides defense-in-depth at the IAM layer. To start without it, omit the `Condition` block from the `AllowAnthropicCMEKCrypto` statement and add it later with `kms:PutKeyPolicy`.
<Note>
**Finding your compartment ID:** Where to find your compartment ID differs between Claude Platform and Claude Enterprise. See the **Claude Platform** and **Claude Enterprise** tabs under **Register the key with Anthropic**.
</Note>
You can also create the key from the AWS Console. Choose a symmetric key with the encrypt and decrypt key usage, a single-region key, and KMS key material origin. The Create-key wizard commits a key policy at its **Review** step: If you add Anthropic's account ID `915198916910` under key usage permissions there, the generated policy grants the whole Anthropic account broader actions (such as `kms:ReEncrypt*` and `kms:GenerateDataKey*`) with no `EncryptionContext` condition, and validation would still succeed against it. To avoid leaving an over-permissive key, finish the wizard with administrative permissions only, then open the key's **Key policy** tab and replace the JSON with the role-scoped policy shown earlier (the three statements scoped to the `anthropic-cmek-client-us` role, with the `EncryptionContext` condition).
<Frame caption="Configure key: symmetric, encrypt and decrypt, single-region key.">

</Frame>
<Frame caption="Add an alias and description for the key.">

</Frame>
<Frame caption="Define key administrative permissions (optional). Your account retains full admin control.">

</Frame>
<Frame caption="Do not add Anthropic's account ID here. This wizard step produces an over-permissive policy. Leave usage permissions empty and edit the Key policy JSON after creation (see the preceding key policy).">

</Frame>
</Step>
</Steps>
## Register the key with Anthropic
How you register the key depends on which product you use.
<Tabs>
<Tab title="Claude Platform">
<Note>
**Finding your compartment ID:** Each workspace has a compartment ID that scopes its CMEK data. Find it in the Claude Console under **Workspace > Security > Encryption keys** (the **Compartment ID** field), or read the `compartment_id` field returned by the [Get Workspace](https://platform.claude.com/docs/en/api/admin-api/workspaces/get-workspace) endpoint. Substitute that value for `<compartment-uuid>` in the preceding key policy.
Key validation always sends the all-zeros compartment UUID (`00000000-0000-0000-0000-000000000000`) as the encryption context, because validation runs before the key is attached to any workspace. Live traffic sends the compartment ID of each attached workspace.
Any `EncryptionContext` condition must allow the all-zeros value plus the compartment ID of every workspace the key is attached to. Validation also runs again whenever key setup is re-run, so keep the all-zeros entry in place permanently.
To attach the key to an additional workspace, add that workspace's compartment ID to the condition with `kms:PutKeyPolicy` before attaching.
</Note>
<Steps>
<Step title="Register the key with Anthropic">
Create an external key configuration through the Admin API.
<Note>
For organizations on [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws), the external key endpoints are not yet available. Register, validate, and attach your key in the Claude Console instead.
</Note>
```bash
curl -sS https://api.anthropic.com/v1/organizations/external_keys \
-H "x-api-key: <anthropic-admin-api-key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"display_name": "<friendly-name>",
"geo": "us",
"provider_config": {
"type": "aws",
"kms_arn": "<key-arn-from-create-key-step>",
"role_arn": "arn:aws:iam::915198916910:role/anthropic-cmek-client-us"
}
}'
```
The response contains the external key ID:
```json
{
"type": "external_key",
"id": "ekey_<id>",
"display_name": "<friendly-name>"
}
```
</Step>
<Step title="Validate the key">
Trigger an encrypt and decrypt round-trip against your key.
```bash
curl -sS -X POST https://api.anthropic.com/v1/organizations/external_keys/ekey_<id>/validate \
-H "x-api-key: <anthropic-admin-api-key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{}'
```
A successful response looks like this:
```json
{ "type": "external_key_validation", "status": "success", "error": null }
```
If validation fails, common causes are:
* **Encryption context mismatch:** Validation fails while data traffic works (or the reverse) with an opaque `AccessDeniedException` when a `kms:EncryptionContext:anthropic:compartment_uuid` condition allows only one of the two values Anthropic sends. Validation sends the all-zeros UUID (`00000000-0000-0000-0000-000000000000`); live traffic sends the attached workspace's compartment ID. Confirm the condition lists both. To rule the condition out entirely, temporarily remove the `Condition` block from the `AllowAnthropicCMEKCrypto` statement and re-validate.
* **Resource control policies (RCPs):** If your AWS organization has an RCP that denies KMS operations when `aws:PrincipalOrgID` does not match your org, it blocks Anthropic's cross-account role. The RCP needs a carve-out for this key or for Anthropic's role ARN. Service control policies do not apply here, because they do not evaluate for external principals calling through resource-based policies.
* **Access granted through IAM instead of the key policy:** Cross-account KMS access must be granted in the key policy itself, not through an IAM policy in your account. Check with `aws kms get-key-policy --key-id <id> --policy-name default`.
* **Region mismatch:** Confirm the key's region is one Anthropic operates in for the geo tier you configured.
</Step>
<Step title="Attach the key to a workspace">
```bash
curl -sS -X POST https://api.anthropic.com/v1/organizations/workspaces/<workspace-id> \
-H "x-api-key: <anthropic-admin-api-key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"external_key_id": "ekey_<id>"
}'
```
</Step>
</Steps>
</Tab>
<Tab title="Claude Enterprise">
In [claude.ai > Organization settings > Data and privacy](https://claude.ai/admin-settings/data-privacy-controls), open **Encryption keys**, then click **Add key**. Choose **AWS** and click **Continue**, then paste the Key ARN from the previous step and click **Add**. Anthropic validates the key with an encrypt and decrypt round-trip. Once it shows as verified, your organization is CMEK-protected from that point forward.
The key details step of this flow displays your organization's **Compartment ID** with a copy button. Substitute that value for `<compartment-uuid>` in the key policy (see the Create the KMS key step under Encryption key setup); you can open the flow to copy the ID before you create the key. After setup, the ID remains visible on the key under **Encryption keys**.
On Claude Enterprise, CMEK applies to the whole organization, so there is no separate workspace attach step, and an organization can have only one key.
</Tab>
</Tabs>
## Terraform
For infrastructure-as-code deployments, the same steps map to the `aws` provider with the `aws_kms_key` and `aws_kms_alias` resources.
manage-claude/cmek-azure-key-vault First recorded · 226 lines, first recorded
## Prerequisites ## Anthropic app information ## Encryption key setup ## Register the key with Anthropic ## Terraform
The first capture of this source. The page was already there, and this is what it said.
---
title: Configure Azure Key Vault for CMEK
url: https://platform.claude.com/docs/en/manage-claude/cmek-azure-key-vault
description: Use Azure Key Vault to provide an encryption key for your organization.
---
```bash Configure with the /claude-api skill in Claude Code
claude "/claude-api help me configure a customer-managed encryption key with Azure Key Vault"
```
This guide walks through configuring an Azure Key Vault key as a [customer-managed encryption key (CMEK)](https://platform.claude.com/docs/en/manage-claude/cmek) for your Anthropic organization.
<Warning>
Enabling CMEK is permanent. If your Key Vault key is deleted or disabled, Anthropic cannot recover the data encrypted under it. Review the [warnings and limitations](https://platform.claude.com/docs/en/manage-claude/cmek) before you start.
</Warning>
## Prerequisites
* An Azure Key Vault with **RBAC authorization enabled** (`enableRbacAuthorization: true`) and **public network access allowed**. Anthropic calls your vault over the public data-plane endpoint; private endpoints are not supported.
* **Purge protection enabled** (`enablePurgeProtection: true`) on the vault. Without it, a deleted key can be permanently purged during the soft-delete retention window, causing irreversible loss of your CMEK-protected data. Purge protection cannot be disabled once enabled.
* Permissions to create keys in the vault and to assign RBAC roles on it.
* Permissions to create service principals in your Entra tenant (`Application Administrator`, `Cloud Application Administrator`, or an equivalent custom role).
* An Anthropic Admin API key for your organization.
* The [`az` CLI](https://learn.microsoft.com/en-us/cli/azure/?view=azure-cli-latest) installed and authenticated.
* **Diagnostic Settings** configured on the vault to route the `AuditEvent` log category to Log Analytics, a storage account, or an event hub. Azure Key Vault does not emit data-plane audit logs (such as `KeyWrap`, `KeyUnwrap`, and `KeyGet`) by default, so without this you get no audit trail for Anthropic's key operations.
## Anthropic app information
To have Anthropic use your encryption key, you must configure an Anthropic multitenant application ID and display name. Those values are:
| Field | Value |
| ------------------------------ | -------------------------------------- |
| Multitenant app client ID (US) | `8635ae1a-3e5d-44e8-a4ed-e0f614466f87` |
| App display name | `anthropic-cmek-client-us` |
<Warning>
Use only this published client ID and display name. Never trust an identifier provided over email, chat, or any onboarding channel.
</Warning>
## Encryption key setup
<Steps>
<Step title="Consent to the Anthropic multitenant application">
This creates a service principal in your Entra tenant for Anthropic's CMEK client application. The application requests no Microsoft Graph permissions; it exists solely as a federation target for Key Vault data-plane access.
```bash
az ad sp create --id 8635ae1a-3e5d-44e8-a4ed-e0f614466f87
```
From the output, capture the `id` field. This is the service principal's object ID in your tenant, which you use when you assign the RBAC role.
```json
{
"appId": "8635ae1a-3e5d-44e8-a4ed-e0f614466f87",
"displayName": "anthropic-cmek-client-us",
"id": "<sp-object-id>"
}
```
If the service principal already exists in your tenant (from a prior attempt or another integration), `az ad sp create` exits with an "already exists" error. Fetch its object ID instead:
```bash
az ad sp show --id 8635ae1a-3e5d-44e8-a4ed-e0f614466f87 --query id -o tsv
```
This step has no Portal equivalent. If you do not have the Azure CLI installed locally, open Cloud Shell from the Portal's top navigation bar. After the command succeeds, you can find the service principal's object ID in **Microsoft Entra ID > Enterprise applications** by clearing the default application-type filter and searching for `anthropic-cmek-client-us`.
<Frame caption="Find the service principal's Object ID on its Entra enterprise application overview.">

</Frame>
</Step>
<Step title="Create an RSA key in your vault">
Azure Key Vault does not support symmetric key wrapping, so the key must be RSA (3072-bit or larger) with `wrapKey` and `unwrapKey` in its allowed operations.
```bash
az keyvault key create \
--vault-name <your-vault-name> \
--name <your-key-name> \
--kty RSA --size 3072 \
--ops wrapKey unwrapKey
```
For HSM-backed keys, use `--kty RSA-HSM` (requires a Premium-SKU vault). Software-protected RSA keys are acceptable for this integration.
From the Portal, open your Key Vault, select **Keys**, then **Generate/Import**. Set the key type to RSA and the size to 3072 or larger. To restrict the key to wrap and unwrap only, open the key version, scroll to **Permitted operations**, and uncheck everything except **Wrap Key** and **Unwrap Key**.
<Frame caption="Create an RSA key sized 3072 or larger.">

</Frame>
<Frame caption="Restrict permitted operations to Wrap Key and Unwrap Key.">

</Frame>
</Step>
<Step title="Grant the Anthropic service principal access to your key">
Assign the `Key Vault Crypto User` role to the service principal from the first step, scoped to the **individual key** rather than the whole vault.
```bash
VAULT_ID=$(az keyvault show --name <your-vault-name> --query id -o tsv)
az role assignment create \
--role "Key Vault Crypto User" \
--assignee-object-id <sp-object-id> \
--assignee-principal-type ServicePrincipal \
--scope "${VAULT_ID}/keys/<your-key-name>"
```
The built-in `Key Vault Crypto User` role grants key cryptographic operations (encrypt, decrypt, wrap, unwrap, sign, verify) plus key read on its assigned scope. The `--ops wrapKey unwrapKey` restriction you set on the key in the previous step further narrows which of those operations can succeed against this key, so in practice Anthropic can only wrap and unwrap.
From the Portal, open the **key** (not the vault), select its **Access control (IAM)** tab, click **Add > Add role assignment**, select **Key Vault Crypto User**, and assign it to the `anthropic-cmek-client-us` service principal.
<Note>
**Dedicated vault alternative:** Microsoft recommends a dedicated vault per application with roles assigned at the vault scope. If you provision a vault that holds only this Anthropic CMEK key, you can assign the role at the vault scope instead and the effect is identical. Scope to the individual key when the key lives in a shared vault.
</Note>
<Frame caption="Assign Key Vault Crypto User to the Anthropic service principal, scoped to the key.">

</Frame>
</Step>
<Step title="Verify your vault configuration">
```bash
az keyvault show --name <your-vault-name> \
--query "{rbac:properties.enableRbacAuthorization, purge:properties.enablePurgeProtection, pub:properties.publicNetworkAccess, net:properties.networkAcls.defaultAction, ipRules:properties.networkAcls.ipRules, uri:properties.vaultUri, tenantId:properties.tenantId}"
```
Confirm that:
* `rbac` is `true`.
* `purge` is `true`. If it is `false` or `null`, enable purge protection on the vault before proceeding. Without it, a soft-deleted key can be permanently purged during the retention window, making your CMEK-protected data unrecoverable.
* `pub` is `"Enabled"`. If it is `"Disabled"`, Anthropic cannot reach the vault over its public data-plane endpoint and validation fails.
* `net` is `"Allow"`, or, if it is `"Deny"`, that `ipRules` include Anthropic's egress ranges (contact Anthropic for the current list).
* `uri` is the vault URI you use when you register the key.
* `tenantId` is the tenant that governs the vault. Use this value as `tenant_id` when you register the key, not the tenant of your currently-active subscription (the two can differ in cross-tenant setups).
</Step>
</Steps>
## Register the key with Anthropic
How you register the key depends on which product you use.
<Tabs>
<Tab title="Claude Platform">
<Steps>
<Step title="Register the key with Anthropic">
Create an external key configuration through the Admin API.
```bash
curl -sS https://api.anthropic.com/v1/organizations/external_keys \
-H "x-api-key: <anthropic-admin-api-key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"display_name": "<friendly-name>",
"geo": "us",
"provider_config": {
"type": "azure",
"vault_uri": "https://<your-vault-name>.vault.azure.net/",
"key_name": "<your-key-name>",
"tenant_id": "<your-tenant-id>"
}
}'
```
The response contains the external key ID:
```json
{
"type": "external_key",
"id": "ekey_<id>",
"display_name": "<friendly-name>"
}
```
</Step>
<Step title="Validate the key">
Trigger an encrypt and decrypt round-trip against your key. This confirms that Anthropic can authenticate to your tenant and perform wrap and unwrap operations.
```bash
curl -sS -X POST https://api.anthropic.com/v1/organizations/external_keys/ekey_<id>/validate \
-H "x-api-key: <anthropic-admin-api-key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" -d '{}'
```
A successful response looks like this:
```json
{ "type": "external_key_validation", "status": "success", "error": null }
```
If validation fails, the `error` field describes the problem. Common causes are:
* **RBAC propagation delay:** role assignments can take a few minutes to take effect. Wait and retry.
* **Network ACLs blocking Anthropic:** confirm public network access and `ipRules` as described in the verification step.
* **Conditional access policies on workload identities:** if your tenant has conditional access policies that target service principals, exclude the Anthropic service principal or add Anthropic's egress ranges to the policy's named locations.
</Step>
<Step title="Attach the key to a workspace">
Once the key is validated, attach it to a workspace to enable CMEK for that workspace's data.
```bash
curl -sS -X POST https://api.anthropic.com/v1/organizations/workspaces/<workspace-id> \
-H "x-api-key: <anthropic-admin-api-key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"external_key_id": "ekey_<id>"
}'
```
</Step>
</Steps>
</Tab>
<Tab title="Claude Enterprise">
In [claude.ai > Organization settings > Data and privacy](https://claude.ai/admin-settings/data-privacy-controls), open **Encryption keys**, then click **Add key**. Choose **Azure**, enter the vault URI, key name, and tenant ID from the verification step, and click **Continue**. Anthropic validates the key with an encrypt and decrypt round-trip. Once it shows as verified, your organization is CMEK-protected from that point forward.
On Claude Enterprise, CMEK applies to the whole organization, so there is no separate workspace attach step, and an organization can have only one key.
</Tab>
</Tabs>
## Terraform
For infrastructure-as-code deployments, the same steps map to the `azurerm` and `azuread` providers.
manage-claude/cmek-google-cloud-kms First recorded · 216 lines, first recorded
## Prerequisites ## Anthropic service account email ## Encryption key setup ## Register the key with Anthropic ## Terraform
The first capture of this source. The page was already there, and this is what it said.
---
title: Configure Google Cloud KMS for CMEK
url: https://platform.claude.com/docs/en/manage-claude/cmek-google-cloud-kms
description: Use Google Cloud KMS to provide an encryption key for your organization.
---
```bash Configure with the /claude-api skill in Claude Code
claude "/claude-api help me configure a customer-managed encryption key with Google Cloud KMS"
```
This guide walks through configuring a Google Cloud KMS key as a [customer-managed encryption key (CMEK)](https://platform.claude.com/docs/en/manage-claude/cmek) for your Anthropic organization.
<Warning>
Enabling CMEK is permanent. If your KMS key is deleted or disabled, Anthropic cannot recover the data encrypted under it. Review the [warnings and limitations](https://platform.claude.com/docs/en/manage-claude/cmek) before you begin.
</Warning>
## Prerequisites
* A Google Cloud project with billing enabled.
* The Cloud KMS API enabled (`cloudkms.googleapis.com`).
* Permissions to create KMS key rings and keys, and to set IAM policy on them (`roles/cloudkms.admin` or equivalent).
* An Anthropic Admin API key for your organization.
* The [`gcloud` CLI](https://cloud.google.com/cli) installed and authenticated.
* Cloud KMS **Data Access audit logs** enabled for the project (IAM & Admin > Audit Logs > Cloud Key Management Service, with `DATA_READ` and `DATA_WRITE`). These are off by default; without them, Anthropic's encrypt and decrypt operations produce no entries in Cloud Logging.
## Anthropic service account email
To have Anthropic use your encryption key, you must give Anthropic's service account a key it can use for encrypting data. The service account email for Anthropic CMEK is:
```text wrap
anthropic-cmek-client-us@gcp-anthropic-cmek-clients.iam.gserviceaccount.com
```
<Warning>
Use only this published service account email. Never trust an identifier provided over email, chat, or any onboarding channel.
</Warning>
<Note>
**Domain restricted sharing:** If your project is under a Google Cloud organization that enforces `constraints/iam.allowedPolicyMemberDomains`, the following IAM bindings are rejected because the Anthropic service account is outside your organization. You need either a project-level carve-out on that constraint, or to add Anthropic's Cloud Identity customer ID (format `C0xxxxxxxx`) to the allowed list. Contact Anthropic for the customer ID if needed.
</Note>
## Encryption key setup
<Steps>
<Step title="Create or choose a key ring">
Skip this step if you already have a key ring to reuse. Key rings are regional. Choose a single-region US location such as `us-east5` that matches the Anthropic geography you are configuring. Multi-region locations like `us` and `global` are not supported.
```bash
gcloud kms keyrings create <your-keyring-name> \
--project=<your-project-id> \
--location=<region>
```
</Step>
<Step title="Create the crypto key">
Create a symmetric key with the `ENCRYPT_DECRYPT` purpose. Anthropic strongly recommends HSM protection: Cloud KMS HSM keys are FIPS 140-2 Level 3 validated, and the cost delta over software keys is small.
```bash
gcloud kms keys create <your-key-name> \
--project=<your-project-id> \
--location=<region> \
--keyring=<your-keyring-name> \
--purpose=encryption \
--protection-level=hsm
```
For software protection instead, omit `--protection-level=hsm`. Nothing else in this guide changes.
You can also create the key from the Google Cloud Console. Open the key ring, click **Create key**, select **Generated key**, set the purpose and algorithm to symmetric encrypt and decrypt, and choose **HSM** under protection level.
<Frame caption="Create an HSM-protected symmetric encrypt/decrypt key.">

</Frame>
</Step>
<Step title="Grant Anthropic's service account access to the key">
Two key-level IAM bindings are required. Both are scoped to the single crypto key, not project-wide or keyring-wide.
Encrypt and decrypt, which Anthropic uses to encrypt and decrypt the data keys that protect your workspace data (envelope encryption):
```bash
gcloud kms keys add-iam-policy-binding <your-key-name> \
--project=<your-project-id> \
--location=<region> \
--keyring=<your-keyring-name> \
--member="serviceAccount:anthropic-cmek-client-us@gcp-anthropic-cmek-clients.iam.gserviceaccount.com" \
--role=roles/cloudkms.cryptoKeyEncrypterDecrypter
```
Viewer, for the metadata read (`cryptoKeys.get`) Anthropic performs at startup to validate the key's purpose and algorithm:
```bash
gcloud kms keys add-iam-policy-binding <your-key-name> \
--project=<your-project-id> \
--location=<region> \
--keyring=<your-keyring-name> \
--member="serviceAccount:anthropic-cmek-client-us@gcp-anthropic-cmek-clients.iam.gserviceaccount.com" \
--role=roles/cloudkms.viewer
```
From the Console, select the key, open the **Permissions** panel, click **Grant access**, and add the service account with both the Cloud KMS CryptoKey Encrypter/Decrypter and Cloud KMS Viewer roles. Make sure you are on the key's permissions page, not the key ring or project, so the grant is scoped to this key only.
<Frame caption="Grant the Anthropic service account both roles, scoped to the key.">

</Frame>
</Step>
<Step title="Note the full key resource name">
You pass this to Anthropic when you register the key. The format is:
```text wrap
projects/<your-project-id>/locations/<region>/keyRings/<your-keyring-name>/cryptoKeys/<your-key-name>
```
Retrieve it with:
```bash
gcloud kms keys describe <your-key-name> \
--project=<your-project-id> \
--location=<region> \
--keyring=<your-keyring-name> \
--format="value(name)"
```
From the Console, open the key's details page and click **Copy resource name**.
<Frame caption="Copy the key's full resource name from the actions menu.">

</Frame>
</Step>
</Steps>
## Register the key with Anthropic
How you register the key depends on which product you use.
<Tabs>
<Tab title="Claude Platform">
<Steps>
<Step title="Register the key with Anthropic">
Create an external key configuration through the Admin API, using the resource name from the Note the full key resource name step under Encryption key setup.
```bash
curl -sS https://api.anthropic.com/v1/organizations/external_keys \
-H "x-api-key: <anthropic-admin-api-key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"display_name": "<friendly-name>",
"geo": "us",
"provider_config": {
"type": "gcp",
"key_name": "projects/<your-project-id>/locations/<region>/keyRings/<your-keyring-name>/cryptoKeys/<your-key-name>"
}
}'
```
The response contains the external key ID:
```json
{
"type": "external_key",
"id": "ekey_<id>",
"display_name": "<friendly-name>"
}
```
</Step>
<Step title="Validate the key">
Trigger an encrypt and decrypt round-trip against your key.
```bash
curl -sS -X POST https://api.anthropic.com/v1/organizations/external_keys/ekey_<id>/validate \
-H "x-api-key: <anthropic-admin-api-key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{}'
```
A successful response looks like this:
```json
{ "type": "external_key_validation", "status": "success", "error": null }
```
If validation fails, common causes are:
* **VPC Service Controls:** if a service perimeter protects Cloud KMS in your project, add Anthropic to an access level on the perimeter (or exclude the key's project) so Anthropic can reach the key.
* **Domain restricted sharing:** the `constraints/iam.allowedPolicyMemberDomains` org policy can strip the Anthropic service account binding (see the earlier note). Confirm the binding is present with `gcloud kms keys get-iam-policy <your-key-name> --project=<your-project-id> --location=<region> --keyring=<your-keyring-name>`.
* **Disabled or destroyed key version:** confirm the key's primary version is enabled, and not disabled, scheduled for destruction, or destroyed.
</Step>
<Step title="Attach the key to a workspace">
```bash
curl -sS -X POST https://api.anthropic.com/v1/organizations/workspaces/<workspace-id> \
-H "x-api-key: <anthropic-admin-api-key>" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"external_key_id": "ekey_<id>"
}'
```
</Step>
</Steps>
</Tab>
<Tab title="Claude Enterprise">
In [claude.ai > Organization settings > Data and privacy](https://claude.ai/admin-settings/data-privacy-controls), open **Encryption keys**, then click **Add key**. Choose **Google Cloud**, paste the full key resource name from the previous step, and click **Continue**. Anthropic validates the key with an encrypt and decrypt round-trip. Once it shows as verified, your organization is CMEK-protected from that point forward.
On Claude Enterprise, CMEK applies to the whole organization, so there is no separate workspace attach step, and an organization can have only one key.
</Tab>
</Tabs>
## Terraform
For infrastructure-as-code deployments, the same steps map to the `google` provider with the `google_kms_key_ring`, `google_kms_crypto_key`, and `google_kms_crypto_key_iam_member` resources.