Follow Discord
Sweep 03 Dec 2026 · 19:13Z Build v2.1.336 553 read Stable v2.1.332 Latest v2.1.336 Next v2.1.336 Feeds RSS JSON llms.txt llms-full.txt Unofficial
One capture · api

One read of Claude Developer Platformapi-20261130T143719Z

71 pages moved out of 972 read.

Pages moved 71 significant first
Pages read 972 in this capture
Captured 14:37 UTC
Corpus hash e4d52e6f03fb corpus-hash

What this read moved

1-25 of 71, page 1 of 3

This capture is too large to show at once. Changes 1-25 of 71 are below, significant first; the rest are on the following screens.

agents-and-tools/agent-skills/quickstart Changed · +15 / -5 lines

from line 18
1818 <Step title="Choose how to authenticate">
1919 Signing in with the CLI is recommended for local development.
2020 
21 For code that runs in CI or on a server with an identity provider, set up [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) instead. For other ways to authenticate, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
22 
2123 Follow the steps for one of the following options.
2224 </Step>
2325</Steps>
from line 66
6466 ```
6567 </Tab>
6668 </Tabs>
69 
70 On Windows, you can install the CLI inside [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/windows/wsl/install) with the Linux steps. If you sign in with the CLI inside WSL, also run your code there so that it finds your sign-in.
6771 </Step>
6872 
6973 <Step title="Sign in" stepNumber={4}>
70 ```bash
74 ```bash CLI
7175 ant auth login
7276 ```
7377 
74 Once login is completed, the SDKs and CLI will pick up your credentials automatically.
78 Your browser opens. The first time you sign in, select an organization if you belong to more than one, and then a workspace.
79 
80 After you sign in, the SDK and the CLI use your credentials automatically unless `ANTHROPIC_API_KEY` is set (see [Which credential is used](https://platform.claude.com/docs/en/manage-claude/authentication#which-credential-is-used)).
7581 </Step>
7682</Steps>
7783 
from line 85
7985 
8086<Steps continued>
8187 <Step title="Create an API key" stepNumber={3}>
82 Create an [API key](https://platform.claude.com/settings/keys) in the Claude Console.
88 Create an API key by following the steps in [Get your Claude API key](https://platform.claude.com/docs/en/get-api-key#create-an-api-key).
8389 </Step>
8490 
8591 <Step title="Set the environment variable" stepNumber={4}>
86 The SDKs and CLI read your key from `ANTHROPIC_API_KEY`:
92 Set the key as an environment variable for your current shell session:
8793 
8894 ```bash
89 export ANTHROPIC_API_KEY="your-api-key-here"
95 export ANTHROPIC_API_KEY="sk-ant-..."
9096 ```
97 
98 The SDK and the CLI read `ANTHROPIC_API_KEY` automatically. To set it for every new shell or on Windows, see [API key](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#api-key) on the CLI authentication options page.
9199 </Step>
92100</Steps>
93101 
from line 141
133141 ```
134142 </Tab>
135143</Tabs>
144 
145On Windows, you can install the CLI inside [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/windows/wsl/install) with the Linux steps. If you sign in with the CLI inside WSL, also run your code there so that it finds your sign-in.
136146 
137147## Agent Skills overview
138148 

agents-and-tools/mcp-tunnels/overview Changed · +10 / -1 lines

from line 167
167167 
168168### Messages API
169169 
170Pass the upstream MCP server’s URL in the `mcp_servers` array, the same way as any other remote MCP server. The request body and `anthropic-beta` header follow the standard [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector) format; only the `url` is tunnel-specific. The following example uses the MCP connector’s `mcp-client` beta header, which is separate from the `mcp-tunnels` beta used by the [Tunnels API](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/reference). Make the request in the workspace the tunnel was created in by using an API key for that workspace or, if your key isn’t scoped to a workspace, by setting the [`anthropic-workspace-id` header](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) to that workspace.
170Pass the upstream MCP server’s URL in the `mcp_servers` array, the same way as any other remote MCP server. The request body and `anthropic-beta` header follow the standard [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector) format; only the `url` is tunnel-specific. The following example uses the MCP connector’s `mcp-client-2025-11-20` beta. The [Tunnels API](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/reference#tunnels-api) uses a separate beta, `mcp-tunnels-2026-06-22`.
171 
172Make the request in the workspace where you created the tunnel. The request accepts any of these credentials:
173 
174* A CLI sign-in token for that workspace (see [Sign in with the CLI](https://platform.claude.com/docs/en/manage-claude/authentication#sign-in-with-the-cli) on the Authentication page)
175* A Workload Identity Federation token for that workspace with the `workspace:inference` or `workspace:developer` scope
176* A Developer API key scoped to that workspace
177* A Developer API key scoped to the organization with the [`anthropic-workspace-id` header](https://platform.claude.com/docs/en/manage-claude/api-keys#select-a-workspace) set to that workspace
178 
179The `workspace:manage_tunnels` scope doesn’t grant access to the Messages API.
171180 
172181The URL’s host is `<subdomain>.<your-tunnel-domain>`. The path depends on your upstream MCP server, not the tunnel: FastMCP’s `streamable-http` transport serves at `/mcp`, and other servers might use `/` or a custom path (check the server’s documentation). The proxy forwards the path untouched.
173182 

api/migration-2026-10-21 Changed · +6 / -3 lines

from line 161
161161 
162162Affects you if your code reads `workspace_id` on API keys.
163163 
164In `2023-06-01`, an API key’s `workspace_id` is the ID of the workspace the key is bound to, or `null` for a key bound to the Default Workspace and for a key that isn’t bound to one workspace (an all-workspaces key).
164In `2023-06-01`, an API key’s `workspace_id` is the ID of the workspace the key is scoped to. It’s `null` for a key scoped to the default workspace and for a key scoped to the organization.
165165 
166In `2026-10-21`, `workspace_id` is removed. Read `scope` instead: for a key bound to a workspace, including the Default Workspace, `scope.workspace_id` is that workspace’s real ID, and an all-workspaces key has a `scope` of `{"type": "organization"}`, with no `workspace_id`.
166In `2026-10-21`, `workspace_id` is removed. Read `scope` instead:
167 
168* For a key scoped to a workspace, including the default workspace, `scope.workspace_id` is that workspace’s real ID.
169* A key scoped to the organization has a `scope` of `{"type": "organization"}`, with no `workspace_id`.
167170 
168171If your code treated a `null` `workspace_id` as the Default Workspace, compare `scope.workspace_id` with your Default Workspace’s ID instead. To find that ID, call [List Workspaces](https://platform.claude.com/docs/en/api/organization/workspaces/list) with `include_default=true` and take the workspace named `"Default"`.
169172 

api/overview Changed · +35 / -27 lines

### Getting API keys

from line 4
44description: Understand the Claude API's available endpoints, authentication headers, client SDKs, pagination, rate limits, and cloud platform access options.
55---
66 
7The Claude API is a RESTful API at `https://api.anthropic.com` that provides programmatic access to Claude models and Claude Managed Agents.
7The Claude API is a RESTful API at `https://api.anthropic.com` that lets your own code use Claude models and Claude Managed Agents. For example, your code can send messages to Claude or run agent sessions in managed cloud sandboxes.
88 
99<Note>
10 **New to Claude?** For direct model access, start with [Get started](https://platform.claude.com/docs/en/get-started) and [Working with Messages](https://platform.claude.com/docs/en/build-with-claude/working-with-messages). For managed agent infrastructure, see the [Claude Managed Agents quickstart](https://platform.claude.com/docs/en/managed-agents/quickstart).
10 **New to Claude?** For direct model access, start with [Get started with Claude](https://platform.claude.com/docs/en/get-started) and [Using the Messages API](https://platform.claude.com/docs/en/build-with-claude/working-with-messages). For managed agent infrastructure, see [Get started with Claude Managed Agents](https://platform.claude.com/docs/en/managed-agents/quickstart).
1111</Note>
1212 
1313## Prerequisites
from line 15
1515To use the Claude API, you need:
1616 
1717* A [Claude Console account](https://platform.claude.com/)
18* An [API key](https://platform.claude.com/settings/keys) from the Console, or a configured [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) rule
18* A way to authenticate (see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication))
1919 
20For step-by-step setup instructions, see [Get started](https://platform.claude.com/docs/en/get-started).
20For step-by-step setup instructions, see [Get started with Claude](https://platform.claude.com/docs/en/get-started). To try the API in your browser first, use [playground in the Claude Console](https://platform.claude.com/playground) (`platform.claude.com/playground`).
2121 
2222## Available APIs
2323 
from line 40
4040 
4141## Authentication
4242 
43For details on each authentication method and when to use it, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). Requests to the Claude API include these headers:
43Choose how to authenticate by where your code runs:
4444 
45* **On your own computer:** [Sign in with the CLI](https://platform.claude.com/docs/en/manage-claude/authentication#sign-in-with-the-cli) by running `ant auth login`. For a direct HTTP request, that section of the Authentication page shows how to get an access token and send it.
46* **In CI or on a server with an identity provider:** Use [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation). For a direct HTTP request, that page’s [Construct the SDK client](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#construct-the-sdk-client) section shows how to get an access token and send it.
47* **Anywhere else:** For other methods, such as App Attest for an iOS or macOS app or a Developer API key, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). To create a key, see [Get your Claude API key](https://platform.claude.com/docs/en/get-api-key).
48 
49To manage an organization through the Admin API or the Compliance API, see [Admin API keys and tokens](https://platform.claude.com/docs/en/manage-claude/admin-api-keys).
50 
51For direct HTTP requests that call Claude, send these headers:
52 
4553| Header | Value | Required |
4654| ----- | ----- | ----- |
47| `Authorization` | `Bearer <token>`, where `<token>` is your API key or a short-lived access token obtained from `POST /v1/oauth/token` through [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) | Yes, unless `x-api-key` is set |
48| `x-api-key` | Your API key from Console. Legacy fallback for `Authorization`, still supported | No |
49| `anthropic-workspace-id` | ID of the [workspace](https://platform.claude.com/docs/en/manage-claude/workspaces) the request runs in (for example, `wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ`). See [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace). | Required with an API key that isn’t scoped to a workspace. Optional for other API keys. A key created for a single workspace runs in that workspace when you omit the header. Not used with Workload Identity Federation tokens, which select a workspace at token exchange. |
55| `Authorization` | `Bearer <token>`, where `<token>` is an access token or a Developer API key | Yes, unless `x-api-key` is set |
56| `x-api-key` | A Developer API key. Legacy fallback for `Authorization`. Access tokens don’t go in this header. | No |
57| `anthropic-workspace-id` | ID of the workspace the request runs in (for example, `wrkspc_01AbCdEfGhJkLmNpQrStUvWx`). See [Select a workspace](https://platform.claude.com/docs/en/manage-claude/api-keys#select-a-workspace) on the Developer API keys page. | With a Developer API key scoped to the organization |
5058| `anthropic-version` | API version (for example, `2026-10-21`) | Yes |
5159| `content-type` | `application/json` | Yes |
5260 
53If you are using the [Client SDKs](https://platform.claude.com/docs/en/api/overview#client-sdks), the SDK sends the authentication, version, and content-type headers automatically; you pass `anthropic-workspace-id` yourself when your key needs it. For API versioning details, see [API versions](https://platform.claude.com/docs/en/api/versioning).
61If you use the [client SDK](https://platform.claude.com/docs/en/api/overview#client-sdks), it sends the authentication, version, and content-type headers for you. With a Developer API key scoped to the organization, pass `anthropic-workspace-id` yourself.
5462 
55When accessing Claude through a [cloud platform](https://platform.claude.com/docs/en/api/overview#claude-api-vs-cloud-platforms), authentication is integrated with the cloud provider’s IAM system. See the platform-specific documentation for supported credential types, required headers, and authentication options.
63For API versioning details, see [API versions](https://platform.claude.com/docs/en/api/versioning).
5664 
57### Getting API keys
65On a [cloud platform](https://platform.claude.com/docs/en/api/overview#claude-api-vs-cloud-platforms), use that platform’s own credentials.
5866 
59The API is made available through the web [Console](https://platform.claude.com/). In the Console, you can use [playground](https://platform.claude.com/playground) (`platform.claude.com/playground`) to try out the API in the browser and then generate API keys on the [API keys](https://platform.claude.com/settings/keys) page (`platform.claude.com/settings/keys`). To learn how, see [Get your Claude API key](https://platform.claude.com/docs/en/get-api-key). You choose each key’s type (see [Key types](https://platform.claude.com/docs/en/manage-claude/authentication#key-types)) and its [expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration) when you create it. Use [workspaces](https://platform.claude.com/settings/workspaces) in the Console to separate environments and [control spend](https://platform.claude.com/docs/en/api/rate-limits) by use case.
60 
6167## Client SDKs
6268 
6369Anthropic provides official SDKs that simplify API integration by handling authentication, request formatting, error handling, and more.
from line 134
128134| Header | Description |
129135| ----- | ----- |
130136| `request-id` | A globally unique identifier for the request, such as `req_018EeWyXxfu5pfWkrYcMdjWG`. Include it when you contact support about a specific request. See [Request ID](https://platform.claude.com/docs/en/api/errors#request-id). |
131| `anthropic-organization-id` | The ID of the organization that the API key or access token used in the request belongs to. |
132| `anthropic-workspace-id` | The `wrkspc_`-prefixed ID of the [workspace](https://platform.claude.com/docs/en/manage-claude/workspaces) that the API key or access token resolved to, such as `wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ`, including when that is your organization’s Default Workspace. Absent when the credential doesn’t resolve to a workspace (for example, on Admin API requests) or the request fails before authentication completes. See [Identify the workspace behind an API response](https://platform.claude.com/docs/en/manage-claude/workspaces#identify-the-workspace-behind-an-api-response). |
137| `anthropic-organization-id` | The ID of the organization that the request’s credential belongs to. |
138| `anthropic-workspace-id` | The ID of the workspace that the request’s credential resolved to, such as `wrkspc_01AbCdEfGhJkLmNpQrStUvWx`. |
133139 
134For the rate limit headers, see [Response headers](https://platform.claude.com/docs/en/api/rate-limits#response-headers) in Rate limits. For examples that read a response header by name with each SDK, see [Identify the workspace behind an API response](https://platform.claude.com/docs/en/manage-claude/workspaces#identify-the-workspace-behind-an-api-response).
140The `anthropic-workspace-id` header is present even when the workspace is your organization’s default workspace.
135141 
142For the rate limit headers, see [Response headers](https://platform.claude.com/docs/en/api/rate-limits#response-headers) in Rate limits. For examples that read a response header by name with each SDK, see [Identify the workspace behind an API response](https://platform.claude.com/docs/en/manage-claude/workspaces#identify-the-workspace-behind-an-api-response) on the Workspaces page.
143 
136144<Note>
137145 Claude Platform on AWS adds an AWS request ID (`x-amzn-requestid`) alongside the standard `request-id` header. See [Request IDs](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws#request-ids) for the dual-ID handling pattern.
138146</Note>
from line 147
139147 
140148## Pagination
141149 
142List endpoints return results in pages. Most newer list endpoints use the `page` and `next_page` cursor scheme described in this section. Some use a different scheme; see the note at the end of this section. Use the `limit` query parameter to control the page size and the `page` query parameter to fetch an adjacent page. Each response includes a `data` array alongside cursor fields for navigating between pages.
150List endpoints return results in pages. Each response holds one page of results in a `data` array. Many list endpoints use the `page` and `next_page` cursors described in the following table.
143151 
144152| Name | Location | Description |
145153| ----- | ----- | ----- |
from line 154
146154| `limit` | Query parameter | Maximum number of items to return per page. |
147155| `page` | Query parameter | Opaque cursor from a previous response. Pass a `next_page` or `prev_page` value here to fetch the adjacent page. |
148156| `order` | Query parameter | Sort direction for the results (`asc` or `desc`), on list endpoints that support sorting. A `page` cursor is only valid with the `order` it was created with. |
149| `next_page` | Response field | Cursor for the next page, or `null` if there are no more results. |
150| `prev_page` | Response field | Cursor for the previous page on endpoints that support backward pagination (currently `GET /v1/sessions`), or `null` if you are on the first page. Other list endpoints omit the field. |
157| `next_page` | Response field | Cursor for the next page or `null` if there are no more results. |
158| `prev_page` | Response field | Cursor for the previous page or `null` on the first page. Only `GET /v1/sessions` returns this field. |
151159 
152To go back a page, pass `prev_page` as the `page` parameter. `prev_page` is `null` when you’re on the first page. Not all list endpoints support `prev_page`. Only `GET /v1/sessions` returns `prev_page`; on list endpoints that do not support backward pagination, the field is absent from the response rather than `null`. For a request walkthrough, see [Listing sessions](https://platform.claude.com/docs/en/managed-agents/session-operations#listing-sessions).
160For an example that pages forward and back through `GET /v1/sessions`, see [Listing sessions](https://platform.claude.com/docs/en/managed-agents/session-operations#listing-sessions).
153161 
154162The SDK provides an auto-paginating iterator that follows `next_page` for you. For example, `for session in client.beta.sessions.list()` (typescript: `for await (const session of client.beta.sessions.list())`; go: `client.Beta.Sessions.ListAutoPaging()`; java: `client.beta().sessions().list().autoPager()`; csharp: `(await client.Beta.Sessions.List()).Paginate()`; php: `$client->beta->sessions->list()->pagingEachItem()`; ruby: `client.beta.sessions.list.auto_paging_each`) walks through every session. SDK auto-pagination is forward-only; to go back a page, read `prev_page` from the response and pass it back as the `page` parameter yourself. See [SDKs, CLI, and libraries](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) for details.
155163 

build-with-claude/compaction-threshold Changed · +63 / -0 lines

### Message threads #### When a thread gets no summary

from line 2339
23392339 
23402340When using server tools (such as web search), the compaction trigger is checked at the start of each sampling iteration. Compaction might occur multiple times within a single request depending on your trigger threshold and the amount of output generated.
23412341 
2342### Message threads
2343 
2344A [message thread](https://platform.claude.com/docs/en/build-with-claude/message-threads) accepts the `compact_20260112` edit in one form: `pause_after_compaction` set to `true` and no `instructions`. You can set `trigger`. This form is available on the Claude API, Claude Platform on AWS, and Claude in Microsoft Foundry. Any other form returns a 400 error.
2345 
2346A thread is append-only, so you can’t replace its earlier turns with a summary. The API doesn’t store the response that contains the `compaction` block, so you can’t append that response and continue the thread. Instead, start a new thread from the summary. For create requests, continue requests, and replay, see [How message threads work](https://platform.claude.com/docs/en/build-with-claude/message-threads#how-message-threads-work).
2347 
2348Follow these steps:
2349 
23501. Send the edit and the beta headers `message-threads-2026-08-12` and `compact-2026-01-12` on every request of the thread, starting with the create request. They are fixed fields, so keep them the same, `trigger` included (see [What to send on each request](https://platform.claude.com/docs/en/build-with-claude/message-threads#what-to-send)). Below the trigger, the thread works as usual.
23512. Look for a `compaction` block in each response. When the input tokens reach the trigger, the API writes the summary and stops. The response contains a `compaction` block, and `stop_reason` is `"compaction"`. It might contain other blocks too, for example those of server tools. The API doesn’t store this response or the request’s messages, so a continue request from this response’s `id` returns a 404 error.
23523. Check the block’s `content`. If it is `null`, there is no summary. Stop here and see [When a thread gets no summary](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#when-a-thread-gets-no-summary).
23534. Send a create request with `system`, `tools`, the edit (still with `pause_after_compaction` set to `true`), and the same beta headers. Make its first message an `assistant` message that contains only the `compaction` block. Leave out the other blocks of that response and every message from before the block. The summary covers the whole conversation, including the new messages of the request that reached the trigger, such as your `tool_result` blocks. You don’t need to send those messages again.
23545. Continue the new thread from its first response `id`. Your copy of the conversation now starts at the `assistant` message that contains the block: replay from there after a 404 error.
2355 
2356The following example shows the body of the create request in step 4:
2357 
2358```json
2359{
2360 "model": "claude-opus-5-5",
2361 "max_tokens": 1024,
2362 "cache_control": { "type": "ephemeral" },
2363 "system": "You are a support agent for Acme. Keep replies short.",
2364 "thread": { "type": "create" },
2365 "context_management": {
2366 "edits": [{ "type": "compact_20260112", "pause_after_compaction": true }]
2367 },
2368 "messages": [
2369 {
2370 "role": "assistant",
2371 "content": [
2372 {
2373 "type": "compaction",
2374 "content": "Summary of the conversation: the user asked about a late order. The agent confirmed that it shipped on Monday. The user then asked how long standard shipping usually takes."
2375 }
2376 ]
2377 }
2378 ]
2379}
2380```
2381 
2382You can also keep recent turns word for word: add them as messages after that `assistant` message, and end with a `user` message. On the models named in [What to send on each request](https://platform.claude.com/docs/en/build-with-claude/message-threads#what-to-send), leave the `thinking` and `redacted_thinking` blocks out of the turns that you add.
2383 
2384These limits apply:
2385 
2386* Put the block in an `assistant` message, with no messages before it, and don’t end the request with an `assistant` message that contains anything besides the block. Otherwise, the API might serve the request but not store it, and the next continue request returns a 404 error.
2387* Don’t send the `task-budgets-2026-03-13` beta header for [task budgets](https://platform.claude.com/docs/en/build-with-claude/task-budgets) on a thread that uses this edit. With that header, the block might contain a value in `encrypted_content`, and the API serves but doesn’t store a create request with such a block. If you need task budgets, send the conversation without `thread`.
2388* Send the edit on every request that contains a `compaction` block. Without it, the request returns a 400 error.
2389* Use a model that supports threshold compaction. Claude Opus 4.5, Claude Sonnet 4.5, and Claude Haiku 4.5 don’t, and a request with the edit returns a 400 error on them. See [API support for threshold compaction](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#availability-feature-support).
2390 
2391#### When a thread gets no summary
2392 
2393The API stops at the trigger even if it writes no summary. The block’s `content` is then `null`, and `stop_reason` is `"compaction"`, or `"refusal"` if safeguards blocked the summary. So look for the block, and don’t test `stop_reason` alone. The API stored nothing from the request that reached the trigger, so [After a refusal](https://platform.claude.com/docs/en/build-with-claude/message-threads#after-a-refusal) doesn’t apply.
2394 
2395Don’t start a thread from a block whose `content` is `null`. The API ignores such a block and returns no error, so the new thread holds none of the conversation. With the `compact-2026-09-04` beta header, the request returns a 400 error instead.
2396 
2397Do one of the following:
2398 
2399* Send the same request again. For a continue request, keep the same `previous_message_id`. The API makes another summary call, which might fail again, for example when the request has `tools` (see [Current limitations](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#current-limitations)). If `stop_reason` is `"refusal"`, the same request might be refused again, so prefer the other two options.
2400* Write your own summary (see [Compact a conversation](https://platform.claude.com/docs/en/build-with-claude/message-threads#compaction)).
2401* Send the full conversation without `thread`. That request accepts `instructions`.
2402 
23422403### Token counting
23432404 
23442405The token counting endpoint (`/v1/messages/count_tokens`) applies existing `compaction` blocks in your prompt but does not trigger new compactions. Use it to check your effective token count after previous compactions:
from line 3538
34773538 ```text wrap
34783539 Summarize the transcript inside <summary></summary> tags. Include relevant information in the summary for continuing the task in the next context window. Do not call any tools while writing this summary; respond with text only.
34793540 ```
3541 
3542 A [message thread](https://platform.claude.com/docs/en/build-with-claude/message-threads) doesn’t accept `instructions`. For threads, see [When a thread gets no summary](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#when-a-thread-gets-no-summary).
34803543 
34813544## Next steps
34823545 

build-with-claude/fast-mode Changed · +17 / -8 lines

from line 23
2323 availability: stable
2424 note: On Microsoft Foundry, fast mode has its own model IDs, which end in `-fast`. Send requests to a deployment of the fast mode model, and leave out `speed`.
2525 details:
26 - Fast mode is in research preview on Claude Opus 5 and deprecated on Claude Opus 4.8, and needs the `fast-mode-2026-02-01` beta header on both models.
26 - Fast mode's status depends on the model. Some models also need the `fast-mode-2026-02-01` beta header in Messages API requests. See [Availability of fast mode](https://platform.claude.com/docs/en/build-with-claude/fast-mode#feature-availability).
2727---
2828 
2929**API support**: Usage differs by product.
from line 31
3131* **Messages API**: Set `speed: "fast"` on the request.
3232* **Managed Agents**: Set `speed` on the agent’s model object, for example `{"id": "claude-opus-5-5", "speed": "fast"}`.
3333 
34Fast mode delivers up to 2.5x higher output tokens per second at premium pricing. Set `speed: "fast"` on your request to opt in. Fast mode is available on Claude Fable 5.2, Claude Mythos 5.2, and Claude Opus 5.5. Fast mode is in research preview on Claude Opus 5 and deprecated on Claude Opus 4.8.
34Fast mode delivers up to 2.5x higher output tokens per second at premium pricing. Set `speed: "fast"` on your request to opt in. Fast mode is available on Claude Fable 5.2, Claude Mythos 5.2, and Claude Opus 5.5. Fast mode is in research preview on Claude Opus 5 and [deprecated on Claude Opus 4.8](https://platform.claude.com/docs/en/build-with-claude/fast-mode#feature-availability).
3535 
3636## How fast mode works
3737 
from line 232
232232 
233233To see your fast mode rate limits, go to the [Rate limits](https://platform.claude.com/usage/limits) page in the Claude Console.
234234 
235Fast mode also has its own [ramp limits](https://platform.claude.com/docs/en/api/rate-limits#ramp-limits). After a sharp increase in fast mode usage, requests can return a `429` error even while you’re under your fast mode rate limit.
236 
235237## Checking which speed was used
236238 
237The response `usage` object includes a `speed` field that indicates which speed was used, either `"fast"` or `"standard"`. Requesting `speed: "fast"` on a [model that doesn’t support fast mode](https://platform.claude.com/docs/en/build-with-claude/fast-mode#feature-availability) returns an error, and so does exceeding fast mode’s rate limits or capacity (a `429` or `529`). When a request with `speed: "fast"` succeeds, `usage.speed` is `"fast"`. Claude Opus 4.6 is an exception: instead of returning an error, a request with `speed: "fast"` and the `fast-mode-2026-02-01` beta header succeeds, but runs at standard speed. In this situation, `usage.speed` shows `"standard"`. On Claude Models on Google Cloud (Anthropic managed), a Claude Opus 4.6 request with `speed: "fast"` returns a `400` error even with the header.
239The response `usage` object includes a `speed` field that shows whether the request ran at `"fast"` or `"standard"` speed:
238240 
239241<CodeGroup>
240242 ```bash cURL
from line 375
373375}
374376```
375377 
378A request with `speed: "fast"` can have these outcomes:
379 
380* **Supported model:** When the request runs at fast speed, `usage.speed` is `"fast"`.
381* **Unsupported model:** A request to a [model that doesn’t support fast mode](https://platform.claude.com/docs/en/build-with-claude/fast-mode#feature-availability) returns an error.
382* **Limits or capacity exceeded:** A request that exceeds fast mode’s rate limits, ramp limits, or capacity returns a `429` or `529` error.
383* **Claude Opus 4.6 with the beta header:** Claude Opus 4.6 doesn’t support fast mode. Instead of returning an error, a request with the `fast-mode-2026-02-01` beta header succeeds but runs at standard speed, and `usage.speed` shows `"standard"`. On Claude Models on Google Cloud (Anthropic managed), the request returns a `400` error even with the header.
384 
376385To track fast mode usage and costs across your organization, see the [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api).
377386 
378387## Retries and fallbacks
from line 388
379388 
380389### Automatic retries
381390 
382The SDK automatically retries fast mode `429` errors up to two times by default (configurable with `max_retries` (typescript, php: `maxRetries`; java: `.maxRetries()`; csharp: `MaxRetries`; go: `option.WithMaxRetries()`)), waiting for the delay in the `retry-after` header before each retry. Because fast mode uses continuous token replenishment, the `retry-after` delay is typically short and requests succeed once capacity is available.
391The SDK automatically retries fast mode `429` errors up to two times by default (configurable with `max_retries` (typescript, php: `maxRetries`; java: `.maxRetries()`; csharp: `MaxRetries`; go: `option.WithMaxRetries()`)). Before each retry, it waits for the delay in the `retry-after` header. Because fast mode rate limits use continuous token replenishment, their `retry-after` delay is typically short, and requests succeed once capacity is available.
383392 
384393### Falling back to standard speed
385394 
from line 717
708717 
709718### API support
710719 
711Fast mode is available only on the following models. If you were using fast mode on an earlier model, [migrate to a model that supports fast mode](https://platform.claude.com/docs/en/models/opus-5-5/migration-guide).
720Fast mode is available only on the following models. If your model doesn’t support fast mode, you can migrate to one that does, such as Claude Opus 5.5. See the [Claude Opus 5.5 migration guide](https://platform.claude.com/docs/en/models/opus-5-5/migration-guide).
712721 
713722To access fast mode on Claude Opus 5, contact your account manager or [join the waitlist](https://claude.com/fast-mode).
714723 
from line 757
748757 
749758Beta headers allow you to access experimental features and new model capabilities before they become part of the standard API.
750759 
751| Header | Models |
752| ----- | ----- |
753| `fast-mode-2026-02-01` | [Claude Opus 5](https://platform.claude.com/docs/en/models/opus-5/overview), [Claude Opus 4.8](https://platform.claude.com/docs/en/models/opus-4-8/overview) |
760| Header | APIs | Models |
761| ----- | ----- | ----- |
762| `fast-mode-2026-02-01` | [Messages API](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) | [Claude Opus 5](https://platform.claude.com/docs/en/models/opus-5/overview), [Claude Opus 4.8](https://platform.claude.com/docs/en/models/opus-4-8/overview) |
754763 
755764### Data handling
756765 

build-with-claude/message-threads Changed · +14 / -4 lines

from line 645
645645* A fallback model wrote the previous response. See [Use fallbacks with a thread](https://platform.claude.com/docs/en/build-with-claude/message-threads#fallbacks).
646646* The previous response is still generating.
647647* The request comes from a different organization or workspace.
648* The request comes from a different user or service account from the one that created the thread. A thread created with a [workspace key (legacy)](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) stays with that key, so use the same key for the whole thread.
648* The request comes from a different user or service account from the one that created the thread. A thread created with a [workspace key (legacy)](https://platform.claude.com/docs/en/manage-claude/api-keys#key-types) stays with that key, so use the same key for the whole thread.
649649* The new messages add something that the stored conversation can’t take. For example, the first image in a conversation that had none can return this error.
650* The previous response contains a `compaction` block, or the new messages contain one that has a summary. See [Message threads in Compaction at a token threshold](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#message-threads).
650651 
651652To recover, follow these steps:
652653 
from line 669
668669 
669670When a response has `stop_reason: "refusal"`, do not continue the thread. The API might already hold the refused turn, and a continue request can’t remove it. Start a new thread with a create request that leaves out or rephrases the turn that led to the refusal. See [Refusals and fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback). The SDK thread helper does this for you: it doesn’t keep the refused turn, and its next turn starts a new thread.
670671 
672If the response contains a `compaction` block, the summary was refused and the API stored nothing, so this section doesn’t apply. See [When a thread gets no summary](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#when-a-thread-gets-no-summary).
673 
671674### Use fallbacks with a thread
672675 
673676[Server-side fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback#server-side-fallback) is available with threads on the Claude API. Decide when you create the thread: send `fallbacks` on every request of the thread or on none. The value of `fallbacks` can change between requests. A continue request that adds or drops `fallbacks` returns a 400 error with the code `thread_fingerprint_mismatch`.
from line 692
689692 
690693## Compact a conversation
691694 
692A thread is append-only, so you can’t replace its earlier turns with a summary. To compact a conversation, start a new thread from the summary. Write the summary in your code and send it as an ordinary message in a new create request with `system` and `tools`. [Compaction on demand](https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand) is not available with threads (see [Features that threads don’t support](https://platform.claude.com/docs/en/build-with-claude/message-threads#unsupported)).
695A thread is append-only, so you can’t replace its earlier turns with a summary. To compact a conversation, start a new thread from the summary. You can write the summary in your code, or the API can write it when the conversation reaches a token threshold:
693696 
697* **Write your own summary.** Write the summary in your code and send it as an ordinary message in a new create request with `system` and `tools`. This approach needs no extra beta header. It works on every model and platform that supports threads.
698* **Use compaction at a token threshold.** On the Claude API, Claude Platform on AWS, and Claude in Microsoft Foundry, a thread accepts one form of the `compact_20260112` edit. For the steps and the limits, see [Message threads in Compaction at a token threshold](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#message-threads).
699 
700[Compaction on demand](https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand) is not available with threads (see [Features that threads don’t support](https://platform.claude.com/docs/en/build-with-claude/message-threads#unsupported)).
701 
694702## How the SDK helper behaves
695703 
696704What the helper does for you:
from line 715
707715 
708716* **Fallbacks.** While the API keeps answering from a fallback model, the helper sends the full conversation in a new create request on every turn because the API stores none of those turns. The helper goes back to continue requests after a response from the model that you requested. To move the conversation to the fallback model instead, start a new thread from the params with that `model` and without `fallbacks` as in [Use fallbacks with a thread](https://platform.claude.com/docs/en/build-with-claude/message-threads#fallbacks).
709717* **Dropped streams.** If a stream ends partway through a response, the helper keeps the finished blocks and any text that arrived, and the next turn sends the full conversation in a new create request. The helper doesn’t retry by itself: to re-send the interrupted turn instead, call `send()` (go, csharp: `Send()`; ruby: `send_message()`) with no messages. If the kept part ends in tool calls, answer them in your next message. If you stop reading a stream after it shows `stop_reason: "refusal"`, the helper treats that turn as a refusal.
718* **Compaction at a token threshold.** After a response with `stop_reason: "compaction"`, the helper’s next turn gets a 404 error. It then replays the full conversation, including the block, in a new create request, or stops using `thread` (see **Other errors**). A replay has messages before the block, so the API might not store it. If it doesn’t, the helper replays on every turn or stops using `thread`. To send only the summary, start a new thread from the params, with `messages` set to an `assistant` message that contains only the block. First, check that the block’s `content` is not `null`. If `stop_reason` is `"refusal"`, the helper takes back the messages that you gave to that call, so include them in your next request. See [Message threads in Compaction at a token threshold](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#message-threads).
710719* **Other errors.** `thread_fingerprint_mismatch` and `thread_unsupported_request` errors reach your code. To carry on without `thread` after a `thread_unsupported_request` error, create the helper with `unsupported_request_behavior` (typescript, java, php: `unsupportedRequestBehavior`; go, csharp: `UnsupportedRequestBehavior`) set to `continue_unthreaded` (ruby: `:continue_unthreaded`; java: `CONTINUE_UNTHREADED`; csharp: `ContinueUnthreaded`; go: `BetaMessageThreadUnsupportedRequestBehaviorContinueUnthreaded`). With that setting, the helper also stops using `thread` when the first continue request after a replay returns `thread_not_found` again. The API might be unable to store that conversation. Without that setting, the helper replays on every turn. A tool runner that creates its own thread uses that setting by default.
711720 
712721The SDK’s beta tool runner also uses a thread by default. You can turn off this default when you create the runner.
from line 800
791800 
792801* [Message Batches](https://platform.claude.com/docs/en/build-with-claude/batch-processing). A request item that includes `thread` ends with an `invalid_request_error` in the batch results.
793802* [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting). A token counting request that includes `thread` returns a 400 error. Count the full conversation instead, with `system` and `tools`.
794* [Compaction](https://platform.claude.com/docs/en/build-with-claude/compaction). [Compaction on demand](https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand) is not available with threads. A request that includes `thread` returns a 400 error if it sets the `compaction` parameter or if it sends a `compaction` block with the `compact-2026-09-04` beta header. See [Compact a conversation](https://platform.claude.com/docs/en/build-with-claude/message-threads#compaction).
795* [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) except `clear_thinking_20251015` with `keep: "all"`.
803* [Compaction on demand](https://platform.claude.com/docs/en/build-with-claude/compaction-on-demand). A request that includes `thread` returns a 400 error if it sets the `compaction` parameter or sends a `compaction` block with a `signature`. Only compaction on demand adds a `signature`. You can still send that feature’s `compact-2026-09-04` beta header on a thread. See [Compact a conversation](https://platform.claude.com/docs/en/build-with-claude/message-threads#compaction).
804* [Compaction at a token threshold](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold), except one form: the `compact_20260112` edit with `pause_after_compaction` set to `true` (the default is `false`) and no `instructions`. That form is available on the Claude API, Claude Platform on AWS, and Claude in Microsoft Foundry. Any other form returns a 400 error. See [Message threads in Compaction at a token threshold](https://platform.claude.com/docs/en/build-with-claude/compaction-threshold#message-threads).
805* [Context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing) except `clear_thinking_20251015` with `keep: "all"`. A request that includes `thread` returns a 400 error if it uses `clear_tool_uses_20250919`, or `clear_thinking_20251015` with another `keep` value or without `keep`.
796806* Organizations that have [HIPAA readiness](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#hipaa-readiness) enabled.
797807* Organizations that have [Inference hooks](https://platform.claude.com/docs/en/manage-claude/inference-hooks) turned on.
798808 

build-with-claude/prompt-engineering/claude-prompting-best-practices Changed · +160 / -76 lines

from line 7
77This is the reference for prompt engineering with current Claude models, including Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5, Claude Opus 5.5, Claude Opus 5, Claude Opus 4.8, Claude Opus 4.7, Claude Opus 4.6, Claude Sonnet 5.5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Haiku 5.5, and Claude Haiku 4.5. The page is organized in three parts:
88 
99* **[Model-specific guidance](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#model-specific-guidance)** first: where a single model behaves differently and what to change in your prompt.
10* **Techniques for all current models** after that: general principles, output and formatting, tool use, thinking, and agentic systems.
10* **General techniques** after that: general principles, output and formatting, tool use, thinking, agentic systems, and capability-specific tips.
1111* **Migration considerations** last, for prompts moving from earlier generations.
1212 
1313<Tip>
from line 32
3232 
3333## General principles
3434 
35The techniques in this section and the sections that follow apply to current Claude models, including Claude Fable 5.2, Claude Mythos 5.2, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, and Claude Mythos 5. Where a technique names a specific model, treat it as measured on that model and re-check it against your own evals before applying it to another.
35The techniques in this section and the sections that follow apply to current Claude models, except where a technique names a model. Treat a technique that names a model as measured on that model. Before you apply it to another model, test it against [your own evaluations](https://platform.claude.com/docs/en/test-and-evaluate/develop-tests).
3636 
3737### Be clear and direct
3838 
from line 332
332332After completing a task that involves tool use, provide a quick summary of the work you've done.
333333```
334334 
335Claude Opus 5 is an exception on verbosity: its default user-facing responses run longer than prior models’, and raising or lowering [effort](https://platform.claude.com/docs/en/build-with-claude/effort) does not reliably change visible response length. Prompt explicitly for conciseness instead. See [Prompting Claude Opus 5](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#response-length-and-verbosity) for a sample instruction. Claude Fable 5.1 has the opposite tendency during agentic work: it writes fewer user-facing updates between tool calls. Ask for progress text explicitly, and remove any instruction telling it to keep that text brief. See [Ask for user-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#ask-for-user-facing-progress-updates). For Claude Fable 5.2, see [Keep users informed during long turns](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-2#keep-users-informed-during-long-turns).
335Some models differ from these defaults. Check your model’s guide in the [Model-specific guidance](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#model-specific-guidance) section. For example:
336336 
337* **Claude Opus 5:** Its default user-facing responses can run long, and lowering the [effort setting](https://platform.claude.com/docs/en/build-with-claude/effort) doesn’t reliably shorten them. Prompt explicitly for conciseness. For a sample instruction, see the [Response length and verbosity](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5#response-length-and-verbosity) section of the Claude Opus 5 guide.
338* **Claude Fable 5.1:** It tends to write few progress updates during long tool-calling turns. Remove any instruction that holds updates back, then ask for them explicitly. See the [Ask for user-facing progress updates](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-1#ask-for-user-facing-progress-updates) section of the Claude Fable 5.1 guide.
339* **Claude Fable 5.2:** It sometimes writes few progress updates during long runs of tool calls. It might also make its first tool call without saying what it’s about to do. Ask for an opening line and for regular updates. See the [Keep users informed during long turns](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-2#keep-users-informed-during-long-turns) section of the Claude Fable 5.2 guide.
340 
337341### Control the format of responses
338342 
339343There are a few particularly effective ways to steer output formatting:
from line 541
537541through. You can always course-correct later if the chosen approach fails.
538542```
539543 
540If you need a hard ceiling on thinking costs, extended thinking with a `budget_tokens` cap is still functional on Opus 4.6 and Sonnet 4.6 but is deprecated. On Claude 4.7 and later models, setting `budget_tokens` returns a 400 error. Prefer lowering the [effort](https://platform.claude.com/docs/en/build-with-claude/effort) setting or using `max_tokens` as a hard limit with [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking).
544The `effort` parameter guides thinking depth, but it doesn’t guarantee a token count. For a hard ceiling on thinking costs, set `max_tokens`, which caps a request’s total output, thinking and response text combined. Set it high enough to leave room for both. At the cap, the response stops with `stop_reason: "max_tokens"`. See the [Cost control](https://platform.claude.com/docs/en/build-with-claude/thinking-steering-and-cost#cost-control) section of the Steering thinking page.
541545 
542546### Leverage thinking and interleaved thinking capabilities
543547 
from line 569
565569 
566570On Claude Fable 5.2, lower the effort level instead. In Anthropic’s testing, an instruction to answer directly without deliberating didn’t stop the model from thinking at `medium` effort and above. See [Calibrate effort](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-fable-5-2#calibrate-effort).
567571 
568If you are migrating from [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) with `budget_tokens`, replace your thinking configuration and move budget control to `effort`. The following examples show the same request before and after the migration (see [effort](https://platform.claude.com/docs/en/build-with-claude/effort) for the available levels and per-model availability):
572The `budget_tokens` field goes with a `thinking.type` of `enabled`. Whether a request can keep it depends on the model:
569573 
574* **Claude 4.7 and later models:** The API returns a 400 error for `budget_tokens`.
575* **Claude Opus 4.6 and Claude Sonnet 4.6:** `budget_tokens` is deprecated but accepted.
576* **Claude 4.5 and earlier models:** `budget_tokens` is the only way to turn thinking on. Keep it until you move to a model that supports adaptive thinking.
577 
578For each model, see the [Configuring thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking) section of the Thinking page.
579 
580To move a request from [extended thinking](https://platform.claude.com/docs/en/build-with-claude/extended-thinking) with `budget_tokens` to adaptive thinking, follow these steps:
581 
5821. Set `thinking` to `{type: "adaptive"}` with no `budget_tokens`. On [models where thinking is always on or on by default](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking), you can omit the field instead.
5832. Set `output_config.effort` to control thinking depth. Choose a starting level from the [Recommended effort levels](https://platform.claude.com/docs/en/build-with-claude/effort#recommended-effort-levels) section of the Effort page.
5843. Check that `max_tokens` leaves room for thinking and the response text.
585 
586Don’t translate your `budget_tokens` value into an effort level. Instead, compare levels on your own evaluations.
587 
588If a response ends with a `stop_reason` of `max_tokens`, raise `max_tokens` or lower the effort level.
589 
590The following request uses a manual budget, which is the form to move away from. It runs on Claude Opus 4.6.
591 
570592<CodeGroup>
571593 ```bash cURL
572594 # Before: extended thinking with a manual budget
from line 604
582604 {"role": "user", "content": "..."}
583605 ]
584606 }'
607 ```
585608 
609 ```bash CLI
610 # Before: extended thinking with a manual budget
611 ant messages create <<'YAML'
612 model: claude-opus-4-6
613 max_tokens: 16000
614 thinking:
615 type: enabled
616 budget_tokens: 10000
617 messages:
618 - role: user
619 content: "..."
620 YAML
621 ```
622 
623 ```python Python
624 client = anthropic.Anthropic()
625 
626 # Before: extended thinking with a manual budget
627 client.messages.create(
628 model="claude-opus-4-6",
629 max_tokens=16000,
630 thinking={"type": "enabled", "budget_tokens": 10000},
631 messages=[{"role": "user", "content": "..."}],
632 )
633 ```
634 
635 ```typescript TypeScript
636 const client = new Anthropic();
637 
638 // Before: extended thinking with a manual budget
639 await client.messages.create({
640 model: "claude-opus-4-6",
641 max_tokens: 16000,
642 thinking: { type: "enabled", budget_tokens: 10000 },
643 messages: [{ role: "user", content: "..." }]
644 });
645 ```
646 
647 ```csharp C#
648 AnthropicClient client = new();
649 
650 // Before: extended thinking with a manual budget
651 await client.Messages.Create(new MessageCreateParams
652 {
653 Model = Model.ClaudeOpus4_6,
654 MaxTokens = 16000,
655 Thinking = new ThinkingConfigEnabled(budgetTokens: 10000),
656 Messages = [new UserMessageParam { Content = "..." }]
657 });
658 ```
659 
660 ```go Go
661 client := anthropic.NewClient()
662 
663 // Before: extended thinking with a manual budget
664 _, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
665 Model: anthropic.ModelClaudeOpus4_6,
666 MaxTokens: 16000,
667 Thinking: anthropic.ThinkingConfigParamUnion{
668 OfEnabled: &anthropic.ThinkingConfigEnabledParam{BudgetTokens: 10000},
669 },
670 Messages: []anthropic.MessageParam{
671 anthropic.NewUserMessage(anthropic.NewTextBlock("...")),
672 },
673 })
674 if err != nil {
675 log.Fatal(err)
676 }
677 ```
678 
679 ```java Java
680 AnthropicClient client = AnthropicOkHttpClient.fromEnv();
681 
682 // Before: extended thinking with a manual budget
683 client.messages().create(MessageCreateParams.builder()
684 .model(Model.CLAUDE_OPUS_4_6)
685 .maxTokens(16000L)
686 .thinking(ThinkingConfigEnabled.builder()
687 .budgetTokens(10000L)
688 .build())
689 .addUserMessage("...")
690 .build());
691 ```
692 
693 ```php PHP
694 $client = new Client();
695 
696 // Before: extended thinking with a manual budget
697 $client->messages->create(
698 model: Model::CLAUDE_OPUS_4_6,
699 maxTokens: 16000,
700 thinking: ['type' => 'enabled', 'budgetTokens' => 10000],
701 messages: [['role' => 'user', 'content' => '...']],
702 );
703 ```
704 
705 ```ruby Ruby
706 client = Anthropic::Client.new
707 
708 # Before: extended thinking with a manual budget
709 client.messages.create(
710 model: Anthropic::Model::CLAUDE_OPUS_4_6,
711 max_tokens: 16000,
712 thinking: { type: "enabled", budget_tokens: 10000 },
713 messages: [{ role: "user", content: "..." }]
714 )
715 ```
716</CodeGroup>
717 
718The following request uses adaptive thinking. It differs from the first request in three fields:
719 
720* **`model`:** The steps don’t change the model, but this request moves to the latest Opus model. To stay on Claude Opus 4.6, which also supports adaptive thinking, keep your `model` value.
721* **`thinking`:** The type is `adaptive`, and the field has no `budget_tokens`.
722* **`output_config.effort`:** The level `high` is an example, not a conversion of the budget.
723 
724Both requests set `max_tokens` to `16000`.
725 
726<CodeGroup>
727 ```bash cURL
586728 # After: adaptive thinking with effort
587729 curl https://api.anthropic.com/v1/messages \
588730 -H "content-type: application/json" \
from line 742
600742 ```
601743 
602744 ```bash CLI
603 # Before: extended thinking with a manual budget
604 ant messages create <<'YAML'
605 model: claude-opus-4-6
606 max_tokens: 16000
607 thinking:
608 type: enabled
609 budget_tokens: 10000
610 messages:
611 - role: user
612 content: "..."
613 YAML
614 
615745 # After: adaptive thinking with effort
616746 ant messages create <<'YAML'
617747 model: claude-opus-5-5
from line 757
627757 ```
628758 
629759 ```python Python
630 # Before: extended thinking with a manual budget
631 client.messages.create(
632 model="claude-opus-4-6",
633 max_tokens=16000,
634 thinking={"type": "enabled", "budget_tokens": 10000},
635 messages=[{"role": "user", "content": "..."}],
636 )
760 client = anthropic.Anthropic()
637761 
638762 # After: adaptive thinking with effort
639763 client.messages.create(
from line 770
646770 ```
647771 
648772 ```typescript TypeScript
649 // Before: extended thinking with a manual budget
650 await client.messages.create({
651 model: "claude-opus-4-6",
652 max_tokens: 16000,
653 thinking: { type: "enabled", budget_tokens: 10000 },
654 messages: [{ role: "user", content: "..." }]
655 });
773 const client = new Anthropic();
656774 
657775 // After: adaptive thinking with effort
658776 await client.messages.create({
from line 783
665783 ```
666784 
667785 ```csharp C#
668 // Before: extended thinking with a manual budget
669 await client.Messages.Create(new MessageCreateParams
670 {
671 Model = Model.ClaudeOpus4_6,
672 MaxTokens = 16000,
673 Thinking = new ThinkingConfigEnabled(budgetTokens: 10000),
674 Messages = [new UserMessageParam { Content = "..." }]
675 });
786 AnthropicClient client = new();
676787 
677788 // After: adaptive thinking with effort
678789 await client.Messages.Create(new MessageCreateParams
from line 797
686797 ```
687798 
688799 ```go Go
689 // Before: extended thinking with a manual budget
690 client.Messages.New(ctx, anthropic.MessageNewParams{
691 Model: anthropic.ModelClaudeOpus4_6,
692 MaxTokens: 16000,
693 Thinking: anthropic.ThinkingConfigParamUnion{
694 OfEnabled: &anthropic.ThinkingConfigEnabledParam{BudgetTokens: 10000},
695 },
696 Messages: []anthropic.MessageParam{
697 anthropic.NewUserMessage(anthropic.NewTextBlock("...")),
698 },
699 })
800 client := anthropic.NewClient()
700801 
701802 // After: adaptive thinking with effort
702 client.Messages.New(ctx, anthropic.MessageNewParams{
803 _, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
703804 Model: anthropic.ModelClaudeOpus5_5,
704805 MaxTokens: 16000,
705806 Thinking: anthropic.ThinkingConfigParamUnion{
from line 813
712813 anthropic.NewUserMessage(anthropic.NewTextBlock("...")),
713814 },
714815 })
816 if err != nil {
817 log.Fatal(err)
818 }
715819 ```
716820 
717821 ```java Java
718 // Before: extended thinking with a manual budget
719 client.messages().create(MessageCreateParams.builder()
720 .model(Model.CLAUDE_OPUS_4_6)
721 .maxTokens(16000L)
722 .thinking(ThinkingConfigEnabled.builder()
723 .budgetTokens(10000L)
724 .build())
725 .addUserMessage("...")
726 .build());
822 AnthropicClient client = AnthropicOkHttpClient.fromEnv();
727823 
728824 // After: adaptive thinking with effort
729825 client.messages().create(MessageCreateParams.builder()
from line 834
738834 ```
739835 
740836 ```php PHP
741 // Before: extended thinking with a manual budget
742 $client->messages->create(
743 model: Model::CLAUDE_OPUS_4_6,
744 maxTokens: 16000,
745 thinking: ['type' => 'enabled', 'budgetTokens' => 10000],
746 messages: [['role' => 'user', 'content' => '...']],
747 );
837 $client = new Client();
748838 
749839 // After: adaptive thinking with effort
750840 $client->messages->create(
from line 847
757847 ```
758848 
759849 ```ruby Ruby
760 # Before: extended thinking with a manual budget
761 client.messages.create(
762 model: Anthropic::Model::CLAUDE_OPUS_4_6,
763 max_tokens: 16000,
764 thinking: { type: "enabled", budget_tokens: 10000 },
765 messages: [{ role: "user", content: "..." }]
766 )
850 client = Anthropic::Client.new
767851 
768852 # After: adaptive thinking with effort
769853 client.messages.create(
from line 1237
11531237 
115412383. **Request specific features explicitly:** Ask explicitly for animations and interactive elements when you want them.
11551239 
11564. **Update thinking configuration:** Claude 4.6 and later models use [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) (`thinking: {type: "adaptive"}`) instead of manual thinking with `budget_tokens`. On Claude 4.7 and later models, setting `budget_tokens` returns a 400 error. Use the [effort parameter](https://platform.claude.com/docs/en/build-with-claude/effort) to control thinking depth.
12404. **Update thinking configuration:** On Claude 4.6 and later models, use [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) (`thinking: {type: "adaptive"}`) and the [effort parameter](https://platform.claude.com/docs/en/build-with-claude/effort) in place of manual thinking with `budget_tokens`. On Claude Opus 4.6 and Claude Sonnet 4.6, `budget_tokens` is deprecated but accepted. Claude 4.7 and later models return a 400 error for it.
11571241 
115812425. **Migrate away from prefilled responses:** Prefilled responses on the last assistant turn are no longer supported starting with Claude 4.6 models and Claude Mythos Preview. See [Migrating away from prefilled responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#migrating-away-from-prefilled-responses) for detailed guidance on alternatives.
11591243 

build-with-claude/working-with-messages Changed · +256 / -23 lines

from line 1
11---
22title: Using the Messages API
33url: https://platform.claude.com/docs/en/build-with-claude/working-with-messages
4description: Practical patterns and examples for using the Messages API effectively
4description: "Request patterns for the Messages API: a basic request, multi-turn conversations, mid-conversation system messages, prefill and its alternatives, and images."
55featureMetadata:
66 status: stable
77 zdr:
from line 37
3737 Microsoft Foundry: stable
3838---
3939 
40This page covers a [basic request](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#basic-request-and-response), [multi-turn conversations](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#multiple-conversational-turns), [mid-conversation system messages](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#system-role-in-messages), [prefilling a response](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#putting-words-in-claudes-mouth), [alternatives to a prefill](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#alternatives-to-a-prefill), and [images in requests](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#vision).
41 
4042Anthropic offers two ways to build with Claude, each suited to different use cases:
4143 
4244| | Messages API | Claude Managed Agents |
from line 46
4446| **What it is** | Direct model prompting access | Pre-built, configurable agent harness that runs in managed infrastructure |
4547| **Best for** | Custom agent loops and fine-grained control | Long-running tasks and asynchronous work |
4648 
47This guide covers common patterns for working with the Messages API, including basic requests, multi-turn conversations, prefill techniques, and vision capabilities. For complete API specifications, see the [Messages API reference](https://platform.claude.com/docs/en/api/messages/create). For the managed agent harness instead, see the [Claude Managed Agents overview](https://platform.claude.com/docs/en/managed-agents/overview).
49For complete API specifications, see the [Messages API reference](https://platform.claude.com/docs/en/api/messages/create). For the managed agent harness instead, see the [Claude Managed Agents overview](https://platform.claude.com/docs/en/managed-agents/overview).
4850 
4951## Basic request and response
5052 
from line 123
121123 if err != nil {
122124 log.Fatal(err)
123125 }
124 fmt.Println(response)
126 fmt.Println(response.RawJSON())
125127 ```
126128 
127129 ```java Java
from line 189
187189 
188190## Multiple conversational turns
189191 
190The Messages API is stateless, which means that you always send the full conversational history to the API. You can use this pattern to build up a conversation over time. Earlier conversational turns don’t necessarily need to actually originate from Claude. You can use synthetic `assistant` messages.
192By default, the Messages API is stateless, so you send the full conversation history with each request. To continue a conversation, add the response’s `content` to `messages` as an `assistant` message. Keep it unchanged. It can hold `thinking` and `tool_use` blocks, and during tool use, those blocks must go back as they came. Then, add the next `user` message.
191193 
192With [message threads](https://platform.claude.com/docs/en/build-with-claude/message-threads), in beta, the API can keep the conversation, so that each later request sends only the new messages. A thread expires 5 minutes after its last request and is deleted no more than 1 hour after its last use.
194Earlier `assistant` messages don’t have to come from Claude. You can write them yourself, as the following example does. In a request, `content` can be a string or an array of blocks. A response has an array of blocks. The last message is a special case. See [Prefilling Claude’s response](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#putting-words-in-claudes-mouth).
193195 
194196<CodeGroup>
195197 ```bash cURL
from line 207
205207 {"role": "user", "content": "Hello, Claude"},
206208 {"role": "assistant", "content": "Hello!"},
207209 {"role": "user", "content": "Can you describe LLMs to me?"}
208 
209210 ]
210211 }'
211212 ```
from line 282
281282 if err != nil {
282283 log.Fatal(err)
283284 }
284 fmt.Println(response)
285 fmt.Println(response.RawJSON())
285286 ```
286287 
287288 ```java Java
from line 353
352353}
353354```
354355 
356With [message threads](https://platform.claude.com/docs/en/build-with-claude/message-threads), in beta, the API can keep the conversation, so that each later request sends only the new messages. A thread expires 5 minutes after its last request and is deleted no more than 1 hour after its last use.
357 
355358### System role in messages
356359 
357360To add a new system instruction partway through a conversation, include a message with `"role": "system"` right after a user turn. That message can’t be the first entry in `messages`. This works on Claude Fable 5.2, [Claude Mythos 5.2](https://platform.claude.com/docs/en/models/mythos-5-2/overview), Claude Fable 5.1, [Claude Mythos 5.1](https://platform.claude.com/docs/en/models/mythos-5-1/overview), Claude Fable 5, [Claude Mythos 5](https://platform.claude.com/docs/en/models/mythos-5/overview), Claude Opus 5.5, Claude Opus 5, Claude Opus 4.8, Claude Sonnet 5.5, and Claude Haiku 5.5. See the full [placement rules](https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#limitations).
from line 457
454457 ```go Go
455458 client := anthropic.NewClient()
456459 
457 response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
460 message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
458461 Model: anthropic.ModelClaudeOpus4_5_20251101,
459462 MaxTokens: 1,
460463 Messages: []anthropic.MessageParam{
from line 468
465468 if err != nil {
466469 log.Fatal(err)
467470 }
468 fmt.Println(response)
471 fmt.Println(message.RawJSON())
469472 ```
470473 
471474 ```java Java
from line 481
478481 .addAssistantMessage("The answer is (")
479482 .build();
480483 
481 Message response = client.messages().create(params);
482 System.out.println(response);
484 Message message = client.messages().create(params);
485 IO.println(message);
483486 ```
484487 
485488 ```php PHP
from line 557
554557 
555558In place of a prefill, end `messages` with a `user` message. Then, choose an approach by what you want from the response:
556559 
557* **JSON that follows a schema:** Use [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs), which constrain the response to follow the schema.
560* **JSON that follows a schema:** Use [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs), which constrain the response to follow the schema. With an `enum` in the schema, they also constrain a value to fixed options, apart from its capitalization (see the [Invalid outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#invalid-outputs) section of that page).
558561* **Another output format:** Describe the format in the system prompt, which is the request’s [`system` field](https://platform.claude.com/docs/en/api/messages/create#create.system).
559562* **No preamble:** Ask in the system prompt for a direct answer.
563* **A continuation, fewer refusals, or a consistent role:** See the [Migrating away from prefilled responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#migrating-away-from-prefilled-responses) section of the Prompting best practices page.
560564 
561565Unlike a prefill, a system prompt instruction doesn’t guarantee how the response starts, so check the response’s text in your code.
562566 
563For what to use in place of other common prefills, see the [Migrating away from prefilled responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#migrating-away-from-prefilled-responses) section of the Prompting best practices page.
567The following example sets an output format in the system prompt for the multiple-choice question from the prefill example. It has no `assistant` message, and its system prompt asks for only the answer’s letter.
564568 
565To move the multiple-choice example to a model that doesn’t accept a prefill, follow these steps:
569Thinking is on for the example’s model even though the request has no `thinking` field. Because thinking tokens count toward `max_tokens`, the example sets `max_tokens` to `1024`, not `1`.
566570 
5671. Change the model and remove the `assistant` message.
5682. Ask in the system prompt for only the answer’s letter.
5693. Set `max_tokens` high enough for the whole response. On [models with thinking on by default](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking), thinking tokens also count toward `max_tokens`.
5704. Read the letter from the response’s `text` block. This block can follow a `thinking` block. Don’t join the letter to the prefill.
571<CodeGroup>
572 ```bash cURL
573 #!/bin/sh
574 curl https://api.anthropic.com/v1/messages \
575 -H "x-api-key: $ANTHROPIC_API_KEY" \
576 -H "anthropic-version: 2026-10-21" \
577 -H "content-type: application/json" \
578 -d '{
579 "model": "claude-opus-5-5",
580 "max_tokens": 1024,
581 "system": "Answer with only the letter of the correct option.",
582 "messages": [
583 {"role": "user", "content": "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"}
584 ]
585 }'
586 ```
571587 
588 ```bash CLI
589 ant messages create \
590 --model claude-opus-5-5 \
591 --max-tokens 1024 \
592 --system "Answer with only the letter of the correct option." \
593 --message '{role: user, content: "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"}'
594 ```
595 
596 ```python Python
597 message = anthropic.Anthropic().messages.create(
598 model="claude-opus-5-5",
599 max_tokens=1024,
600 system="Answer with only the letter of the correct option.",
601 messages=[
602 {
603 "role": "user",
604 "content": "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae",
605 }
606 ],
607 )
608 answer = next(
609 (block.text.strip() for block in message.content if block.type == "text"), None
610 )
611 if answer not in ("A", "B", "C"):
612 raise ValueError(f"Unexpected answer: {answer}")
613 print(answer)
614 ```
615 
616 ```typescript TypeScript
617 const anthropic = new Anthropic();
618 
619 const message = await anthropic.messages.create({
620 model: "claude-opus-5-5",
621 max_tokens: 1024,
622 system: "Answer with only the letter of the correct option.",
623 messages: [
624 {
625 role: "user",
626 content: "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"
627 }
628 ]
629 });
630 const answer = message.content.find((block) => block.type === "text")?.text.trim();
631 if (answer === undefined || !["A", "B", "C"].includes(answer)) {
632 throw new Error(`Unexpected answer: ${answer}`);
633 }
634 console.log(answer);
635 ```
636 
637 ```csharp C#
638 AnthropicClient client = new();
639 
640 var parameters = new MessageCreateParams
641 {
642 Model = Model.ClaudeOpus5_5,
643 MaxTokens = 1024,
644 System = "Answer with only the letter of the correct option.",
645 Messages = [
646 new UserMessageParam { Content = "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae" }
647 ]
648 };
649 
650 var message = await client.Messages.Create(parameters);
651 string? answer = null;
652 foreach (var block in message.Content)
653 {
654 if (block.TryPickText(out var textBlock))
655 {
656 answer = textBlock.Text.Trim();
657 break;
658 }
659 }
660 if (answer is not ("A" or "B" or "C"))
661 {
662 throw new InvalidOperationException($"Unexpected answer: {answer}");
663 }
664 Console.WriteLine(answer);
665 ```
666 
667 ```go Go
668 client := anthropic.NewClient()
669 
670 message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
671 Model: anthropic.ModelClaudeOpus5_5,
672 MaxTokens: 1024,
673 System: []anthropic.TextBlockParam{
674 {Text: "Answer with only the letter of the correct option."},
675 },
676 Messages: []anthropic.MessageParam{
677 anthropic.NewUserMessage(anthropic.NewTextBlock("What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae")),
678 },
679 })
680 if err != nil {
681 log.Fatal(err)
682 }
683 var answer string
684 for _, block := range message.Content {
685 if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {
686 answer = strings.TrimSpace(textBlock.Text)
687 break
688 }
689 }
690 if !slices.Contains([]string{"A", "B", "C"}, answer) {
691 log.Fatalf("unexpected answer: %q", answer)
692 }
693 fmt.Println(answer)
694 ```
695 
696 ```java Java
697 AnthropicClient client = AnthropicOkHttpClient.fromEnv();
698 
699 MessageCreateParams params = MessageCreateParams.builder()
700 .model(Model.CLAUDE_OPUS_5_5)
701 .maxTokens(1024L)
702 .system("Answer with only the letter of the correct option.")
703 .addUserMessage("What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae")
704 .build();
705 
706 Message message = client.messages().create(params);
707 String answer = message.content().stream()
708 .flatMap(block -> block.text().stream())
709 .map(textBlock -> textBlock.text().strip())
710 .findFirst()
711 .orElse("");
712 if (!List.of("A", "B", "C").contains(answer)) {
713 throw new IllegalStateException("Unexpected answer: " + answer);
714 }
715 IO.println(answer);
716 ```
717 
718 ```php PHP
719 $client = new Client();
720 
721 $message = $client->messages->create(
722 maxTokens: 1024,
723 messages: [
724 ['role' => 'user', 'content' => 'What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae'],
725 ],
726 model: Model::CLAUDE_OPUS_5_5,
727 system: 'Answer with only the letter of the correct option.',
728 );
729 $answer = null;
730 foreach ($message->content as $block) {
731 if ($block instanceof \Anthropic\Messages\TextBlock) {
732 $answer = trim($block->text);
733 break;
734 }
735 }
736 if (!in_array($answer, ['A', 'B', 'C'], true)) {
737 throw new \UnexpectedValueException("Unexpected answer: {$answer}");
738 }
739 echo $answer, PHP_EOL;
740 ```
741 
742 ```ruby Ruby
743 client = Anthropic::Client.new
744 
745 message = client.messages.create(
746 model: Anthropic::Model::CLAUDE_OPUS_5_5,
747 max_tokens: 1024,
748 system: "Answer with only the letter of the correct option.",
749 messages: [
750 {
751 role: "user",
752 content: "What is Latin for ant? (A) Apoidea, (B) Rhopalocera, (C) Formicidae"
753 }
754 ]
755 )
756 text_block = message.content.find { |block| block.is_a?(Anthropic::Models::TextBlock) }
757 answer = text_block&.text&.strip
758 raise "Unexpected answer: #{answer.inspect}" unless %w[A B C].include?(answer)
759 puts answer
760 ```
761</CodeGroup>
762 
763The API returns the following response. With the SDK, the example prints only the answer, `C`.
764 
765```json Output
766{
767 "id": "msg_01HCDu5LRGeP2o7s2xGmxyx8",
768 "type": "message",
769 "role": "assistant",
770 "content": [
771 {
772 "type": "thinking",
773 "thinking": "",
774 "signature": "EosnCkYICxIMMb3LzNrMu..."
775 },
776 {
777 "type": "text",
778 "text": "C"
779 }
780 ],
781 "model": "claude-opus-5-5",
782 "stop_reason": "end_turn",
783 "stop_sequence": null,
784 "usage": {
785 "input_tokens": 60,
786 "output_tokens": 32
787 }
788}
789```
790 
791In this response, a `thinking` block comes before the `text` block, which can occur [when thinking is on](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking). Its `thinking` field is empty unless the request asks for a summary (see the [Controlling thinking display](https://platform.claude.com/docs/en/build-with-claude/thinking#controlling-thinking-display) section of the Thinking page).
792 
793Thinking tokens are billed as output tokens, so `output_tokens` is `32` for a one-letter answer. To use fewer, set a lower [effort level](https://platform.claude.com/docs/en/build-with-claude/effort).
794 
795To read the answer, find the `text` block by its `type`, not by its position. Then, trim the text’s whitespace and check that it’s `A`, `B`, or `C`. With the SDK, the example does both.
796 
797What to do when the check fails depends on the response’s `stop_reason`:
798 
799* **`max_tokens`:** The response might have no `text` block. Raise `max_tokens` and send the request again.
800* **`refusal`:** Claude declined to respond. To retry on another model, see [Refusals and fallback](https://platform.claude.com/docs/en/build-with-claude/refusals-and-fallback).
801* **Any other value:** Send the request again or report the failure.
802 
572803## Vision
573804 
574805Claude can read both text and images in requests. You can supply images using the `base64`, `url`, or `file` source types. The `file` source type references an image uploaded through the [Files API](https://platform.claude.com/docs/en/build-with-claude/files). Supported media types are `image/jpeg`, `image/png`, `image/gif`, and `image/webp`. See the [Vision](https://platform.claude.com/docs/en/build-with-claude/vision) guide for more details.
575806 
807The following example makes two separate requests with the same image, the first as `base64` and the second as a `url`. In your own code, send only one.
808 
576809<CodeGroup>
577810 ```bash cURL
578811 #!/bin/sh
from line 1109
8761109 if err != nil {
8771110 log.Fatal(err)
8781111 }
879 fmt.Println(message)
1112 fmt.Println(message.RawJSON())
8801113 
8811114 // Option 2: URL-referenced image
8821115 messageFromURL, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
from line 1127
8941127 if err != nil {
8951128 log.Fatal(err)
8961129 }
897 fmt.Println(messageFromURL)
1130 fmt.Println(messageFromURL.RawJSON())
8981131 ```
8991132 
9001133 ```java Java

claude_api_primer Changed · +90 / -38 lines

### Invalid tool call ### Example event stream # API usage primer for Claude ### Invalid tool name ### Basic streaming request example

from line 1
11---
22title: API usage primer for Claude
33url: https://platform.claude.com/docs/en/claude_api_primer
4description: This guide is designed to give Claude the basics of using the Claude API. It gives explanation and examples of model IDs/the basic messages API, tool use, streaming, thinking, and nothing else.
4description: The basics of the Claude API on one page, written for Claude and other agents.
55---
66 
7# API usage primer for Claude
7This page gives Claude, or any other agent that writes code against the Claude API, the basics in one place. It covers model IDs, Messages API requests with text and images, thinking, tool use and its errors, JSON output, and streaming. The instructions on this page are for whoever sends the request, and “Claude” is the model that answers it.
88 
9> This guide is designed to give Claude the basics of using the Claude API. It gives explanation and examples of model IDs/the basic messages API, tool use, streaming, thinking, and nothing else.
9For the rest, see the [Messages API reference](https://platform.claude.com/docs/en/api/messages/create) and the guides that each section links to.
1010 
1111## Models
1212 
from line 67
6767 
6868### Multiple conversational turns
6969 
70The Messages API is stateless, which means that you always send the full conversational history to the API. You can use this pattern to build up a conversation over time. Earlier conversational turns don’t necessarily need to actually originate from Claude. You can use synthetic `assistant` messages.
70By default, the Messages API is stateless, so you send the full conversation history with each request. To continue a conversation, add the response’s `content` to `messages` as an `assistant` message. Keep it unchanged. It can hold `thinking` and `tool_use` blocks, and during tool use, those blocks must go back as they came. Then, add the next `user` message.
7171 
72With [message threads](https://platform.claude.com/docs/en/build-with-claude/message-threads), in beta, the API can keep the conversation, so that each later request sends only the new messages. A thread expires 5 minutes after its last request and is deleted no more than 1 hour after its last use.
72Earlier `assistant` messages don’t have to come from Claude. You can write them yourself, as the following example does. In a request, `content` can be a string or an array of blocks. A response has an array of blocks. The last message is a special case. See [Prefilling Claude’s response](https://platform.claude.com/docs/en/claude_api_primer#putting-words-in-claudes-mouth).
7373 
7474<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
7575 ```bash CLI
from line 102
102102 ```
103103</CodeGroup>
104104 
105With [message threads](https://platform.claude.com/docs/en/build-with-claude/message-threads), in beta, the API can keep the conversation, so that each later request sends only the new messages. A thread expires 5 minutes after its last request and is deleted no more than 1 hour after its last use.
106 
105107### Prefilling Claude’s response
106108 
107109A prefill is text that you write in an `assistant` message and put last in `messages`. An `assistant` message anywhere else in `messages` isn’t a prefill. Claude continues the prefilled text, and the response holds only the continuation.
from line 188
186188 
187189In place of a prefill, end `messages` with a `user` message. Then, choose an approach by what you want from the response:
188190 
189* **JSON that follows a schema:** Use [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs), which constrain the response to follow the schema.
191* **JSON that follows a schema:** Use [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs), which constrain the response to follow the schema. With an `enum` in the schema, they also constrain a value to fixed options, apart from its capitalization (see the [Invalid outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs#invalid-outputs) section of that page).
190192* **Another output format:** Describe the format in the system prompt, which is the request’s [`system` field](https://platform.claude.com/docs/en/api/messages/create#create.system).
191193* **No preamble:** Ask in the system prompt for a direct answer.
194* **A continuation, fewer refusals, or a consistent role:** See the [Migrating away from prefilled responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#migrating-away-from-prefilled-responses) section of the Prompting best practices page.
192195 
193196Unlike a prefill, a system prompt instruction doesn’t guarantee how the response starts, so check the response’s text in your code.
194197 
195For what to use in place of other common prefills, see the [Migrating away from prefilled responses](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices#migrating-away-from-prefilled-responses) section of the Prompting best practices page.
196 
197198To move the multiple-choice example to a model that doesn’t accept a prefill, follow these steps:
198199 
1992001. Change the model and remove the `assistant` message.
2002012. Ask in the system prompt for only the answer’s letter.
2013. Set `max_tokens` high enough for the whole response. On [models with thinking on by default](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking), thinking tokens also count toward `max_tokens`.
2023. Set `max_tokens` high enough for the whole response. On [models where thinking is always on or on by default](https://platform.claude.com/docs/en/claude_api_primer#thinking), thinking tokens also count toward `max_tokens`.
2022034. Read the letter from the response’s `text` block. This block can follow a `thinking` block. Don’t join the letter to the prefill.
203204 
205For these steps as a request in code, see [Using the Messages API](https://platform.claude.com/docs/en/build-with-claude/working-with-messages#alternatives-to-a-prefill).
206 
204207### Vision
205208 
206209Claude can read both text and images in requests. Both `base64` and `url` source types are supported for images, along with the `image/jpeg`, `image/png`, `image/gif`, and `image/webp` media types.
from line 303
300303 
301304## Thinking
302305 
303Thinking can sometimes help Claude with very hard tasks. The current mechanism is [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) (`thinking: {"type": "adaptive"}`): Claude determines when and how much to think, and you steer thinking depth with the [`effort`](https://platform.claude.com/docs/en/build-with-claude/effort) parameter rather than a token budget. Adaptive thinking is supported on Claude 4.6 and later models and Claude Mythos Preview. On Claude 5 and later models and Claude Mythos Preview, thinking is on by default when the `thinking` parameter is omitted.
306Thinking can help Claude with very hard tasks. With [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) (`thinking: {"type": "adaptive"}`), Claude determines when and how much to think.
304307 
305Thinking is supported in the following models:
308With adaptive thinking, you steer thinking depth with the [`effort` parameter](https://platform.claude.com/docs/en/build-with-claude/effort), not a token budget. Set it in `output_config`, for example, `output_config: {"effort": "medium"}`. From least to most thinking, the levels are `low`, `medium`, `high`, `xhigh`, and `max`. The [Effort levels](https://platform.claude.com/docs/en/build-with-claude/effort#effort-levels) table says which models support `xhigh` and `max`.
306309 
310The following models support thinking. In the list, “always on” means that you can’t turn thinking off. “On by default” means that thinking runs when you omit the `thinking` parameter. To turn it off, send `thinking: {"type": "disabled"}`. On Claude Haiku 5.5 and Claude Opus 5, this works only at `high` effort or below. Claude Sonnet 5.5 differs, as the text after the list explains. With neither label, thinking is off until you set `thinking`. “Legacy manual thinking” is the manual extended thinking that the [How thinking works](https://platform.claude.com/docs/en/claude_api_primer#how-thinking-works) section describes. For what each model does with each `thinking` value, see the [Configuring thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking) section of the Thinking page.
311 
307312* Claude Fable 5.2 (`claude-fable-5-2`, adaptive thinking only, always on)
308313* Claude Mythos 5.2 (`claude-mythos-5-2`, adaptive thinking only, always on)
309314* Claude Opus 5.5 (`claude-opus-5-5`, adaptive thinking only, always on)
310* Claude Sonnet 5.5 (`claude-sonnet-5-5`, adaptive thinking only, on by default; `thinking: {"type": "disabled"}` returns a 400 error, so send `thinking: {"type": "between_tools"}` to turn off up-front thinking)
315* Claude Sonnet 5.5 (`claude-sonnet-5-5`, adaptive thinking or `between_tools`, on by default)
311316* Claude Haiku 5.5 (`claude-haiku-5-5`, adaptive thinking only, on by default)
312317* Claude Fable 5.1 (`claude-fable-5-1`, adaptive thinking only, always on)
313318* Claude Mythos 5.1 (`claude-mythos-5-1`, adaptive thinking only, always on)
from line 328
323328* Claude Sonnet 4.5 (`claude-sonnet-4-5-20250929`, [deprecated on Anthropic-operated platforms](https://platform.claude.com/docs/en/about-claude/model-deprecations#overview), legacy manual thinking only)
324329* Claude Haiku 4.5 (`claude-haiku-4-5-20251001`, legacy manual thinking only)
325330 
331Claude Mythos Preview also supports thinking. See the [Configuring thinking](https://platform.claude.com/docs/en/build-with-claude/thinking#configuring-thinking) section of the Thinking page.
332 
333Claude Sonnet 5.5 returns a 400 error for `thinking: {"type": "disabled"}`. Its lowest setting is `thinking: {"type": "between_tools"}`, which turns off up-front thinking: the `thinking` blocks that come ahead of the response. That setting takes no other field, and at `xhigh` or `max` effort, it returns a 400 error.
334 
326335<Note>
327336 On Claude 4.7 and later models, manual extended thinking (`type: enabled` with a `budget_tokens` value) is not supported and returns a 400 error. Use [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) (`type: adaptive`) instead.
328337</Note>
from line 338
329338 
330339### How thinking works
331340 
332When thinking is on, Claude creates `thinking` content blocks where it outputs its internal reasoning. The API response includes `thinking` content blocks, followed by `text` content blocks.
341When thinking is on, the API response can include `thinking` content blocks before its `text` content blocks. With adaptive thinking, Claude can skip thinking for a request that doesn’t need it, and the response then has no `thinking` block. So select blocks by `type`, not by position.
333342 
343The `display` field of the `thinking` parameter sets what each `thinking` block returns. You can set it with `type: "adaptive"` or `type: "enabled"`:
344 
345* `"summarized"`: The block’s `thinking` field holds a summary of the thinking. This is the default on Claude 4.6 and earlier models.
346* `"omitted"`: The block’s `thinking` field is empty. This is the default on Claude 4.7 and later models and Claude Mythos Preview. Even when the field is empty, pass the block back.
347 
348The following example sets `display: "summarized"`.
349 
334350<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
335351 ```bash CLI
336352 ant messages create <<'YAML'
from line 388
372388 ```
373389</CodeGroup>
374390 
375Manual extended thinking (`thinking: {"type": "enabled", "budget_tokens": N}`) is the legacy mechanism. It works only on Claude 4 through 4.6 models that support thinking; Claude 4.7 and later models reject `type: enabled` with a 400 error and use [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) instead. With manual extended thinking, `budget_tokens` sets the maximum number of tokens Claude is allowed to use for its internal reasoning process; the limit applies to full thinking tokens, not to the summarized output. Unless you are using [interleaved thinking](https://platform.claude.com/docs/en/claude_api_primer#interleaved-thinking), `budget_tokens` must be less than `max_tokens` so that Claude has space to write its response after thinking is complete.
391Manual extended thinking (`thinking: {"type": "enabled", "budget_tokens": N}`) is the legacy mechanism. `budget_tokens` sets a target for how many tokens Claude uses for thinking, not a strict cap:
376392 
393* The budget applies to the full thinking, not to the summary that the response returns.
394* `budget_tokens` must be less than `max_tokens`, which leaves room for the response, unless you use [interleaved thinking](https://platform.claude.com/docs/en/claude_api_primer#interleaved-thinking).
395 
377396## Thinking with tool use
378397 
379Thinking can be used alongside tool use, allowing Claude to reason through tool selection and results processing.
398You can use thinking alongside tool use, which lets Claude reason through tool selection and results processing.
380399 
381400Important limitations:
382401 
from line 470
451470 
452471### Interleaved thinking
453472 
454Interleaved thinking allows Claude to think between tool calls, reasoning about tool results before determining the next step.
473Interleaved thinking lets Claude think between tool calls and reason about each tool result before the next step.
455474 
456<Info>
457 On models with [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) (`thinking: {type: "adaptive"}`), interleaved thinking is automatically enabled. No beta header is needed. Sonnet 4.6 supports both the `interleaved-thinking-2025-05-14` beta header with manual extended thinking and adaptive thinking.
458</Info>
475With [adaptive thinking](https://platform.claude.com/docs/en/build-with-claude/thinking), interleaved thinking is automatic. On Claude Opus 4.6, only adaptive thinking interleaves.
459476 
460On older models that use manual extended thinking (Claude 4, 4.5, and Sonnet 4.6 models), enable interleaved thinking by adding the beta header `interleaved-thinking-2025-05-14` to your API request:
477With manual extended thinking, add the `interleaved-thinking-2025-05-14` [beta header](https://platform.claude.com/docs/en/api/beta-headers) to your request. This works on Claude Sonnet 4.6, Claude Opus 4.5, Claude Sonnet 4.5, and Claude Haiku 4.5. On Claude Sonnet 4.6, the header is deprecated. The following example sends the header:
461478 
462479<CodeGroup exclude="shell:cURL, typescript, csharp, go, java, php, ruby">
463480 ```bash CLI
from line 568
551568 ```
552569</CodeGroup>
553570 
554With interleaved thinking and ONLY with interleaved thinking (not regular manual extended thinking), the `budget_tokens` can exceed the `max_tokens` parameter, as `budget_tokens` in this case represents the total budget across all thinking blocks within one assistant turn.
571With interleaved thinking, `budget_tokens` can exceed `max_tokens`, because the budget covers all thinking blocks within one assistant turn (a whole tool-use loop).
555572 
556573## Tool use
557574 
from line 606
589606 
590607### Best practices for tool definitions
591608 
592**Provide extremely detailed descriptions.** This is by far the most important factor in tool performance. Your descriptions should explain every detail about the tool, including:
609**Provide extremely detailed descriptions.** This is the most important factor in tool performance. Your descriptions should explain every detail about the tool, including:
593610 
594611* What the tool does
595612* When it should be used (and when it shouldn’t)
from line 613
596613* What each parameter means and how it affects the tool’s behavior
597614* Any important caveats or limitations
598615 
599**Consider using `input_examples` for complex tools.** For tools with nested objects, optional parameters, or format-sensitive inputs, you can provide concrete examples using the `input_examples` field (beta). This shows Claude the expected input patterns. See [Providing tool use examples](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#providing-tool-use-examples) for details.
600 
601616Example of a good tool description:
602617 
603618```json
from line 632
617632}
618633```
619634 
635**Consider using `input_examples` for complex tools.** For tools with nested objects, optional parameters, or format-sensitive inputs, add an `input_examples` field to the tool definition. It takes an array of example input objects, each valid against the tool’s `input_schema`. See the [Providing tool use examples](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools#providing-tool-use-examples) section of the Define tools page.
636 
620637## Controlling Claude’s output
621638 
622639### Forcing tool use
from line 655
638655 
639656### JSON output
640657 
641Tools do not necessarily need to be client functions. You can use tools anytime you want the model to return JSON output that follows a provided schema.
658To get a response that follows a JSON schema, use [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs). Send the schema in `output_config.format`:
642659 
660```json
661{
662 "output_config": {
663 "format": {
664 "type": "json_schema",
665 "schema": {
666 "type": "object",
667 "properties": { "city": { "type": "string" } },
668 "required": ["city"],
669 "additionalProperties": false
670 }
671 }
672 }
673}
674```
675 
676The JSON comes back in the response’s `text` block.
677 
643678### Parallel tool use
644679 
645By default, Claude might use multiple tools to answer a user query. You can disable this behavior by setting `disable_parallel_tool_use=true`.
680By default, Claude might call several tools in one response, which then has several `tool_use` blocks. To turn off parallel tool use, set `disable_parallel_tool_use: true` inside `tool_choice`. With the `auto` type, Claude then calls at most one tool in each response:
646681 
682```json
683{
684 "tool_choice": { "type": "auto", "disable_parallel_tool_use": true }
685}
686```
687 
647688## Handling tool use and tool result content blocks
648689 
649690### Handling results from client tools
from line 712
671712When you receive a tool use response, you should:
672713 
6737141. Extract the `name`, `id`, and `input` from the `tool_use` block.
715 
6747162. Run the actual tool in your code base corresponding to that tool name.
6753. Continue the conversation by sending a new message with a `tool_result`:
676717 
7183. Continue the conversation in a new request. Add two messages to `messages`:
719 
720 1. An `assistant` message with the response’s `content`, unchanged.
721 2. A `user` message with a `tool_result` for each `tool_use` block.
722 
723The `user` message looks like this:
724 
677725```json
678726{
679727 "role": "user",
from line 763
715763}
716764```
717765 
718### Invalid tool name
766### Invalid tool call
719767 
720If Claude’s attempted use of a tool is invalid (for example, missing required parameters), try the request again with more-detailed `description` values in your tool definitions.
768If your code finds an invalid tool call (for example, one missing a required parameter), return a `tool_result` that states the error, with `"is_error": true`. Claude can then try the call again with corrections.
721769 
770An invalid call usually means that Claude didn’t have enough information to use the tool. During development, give your tool definitions more detailed `description` values. To make every call match the tool’s `input_schema`, set `"strict": true` on the tool definition. See [Strict tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use).
771 
722772## Streaming messages
723773 
724774When creating a Message, you can set `"stream": true` to incrementally stream the response using server-sent events (SSE).
from line 826
776826For `tool_use` content blocks, deltas are *partial JSON strings*:
777827 
778828```json
779{"type": "content_block_delta","index": 1,"delta": {"type": "input_json_delta","partial_json": "{\"location\": \"San Fra"}}}
829{"type": "content_block_delta","index": 1,"delta": {"type": "input_json_delta","partial_json": "{\"location\": \"San Fra"}}
780830```
781831 
782832#### Thinking delta
783833 
784When using thinking with streaming:
834With `display: "summarized"`, thinking text streams in `thinking_delta` events, as in the following example. With `display: "omitted"`, each `thinking` block streams one `thinking_delta` whose `thinking` string is empty.
785835 
786836```json
787837{
from line 844
794844}
795845```
796846 
797### Basic streaming request example
847### Example event stream
848 
849The following events stream a short text response:
798850 
799851```sse
800852event: message_start

cli-sdks-libraries/cli/authentication Changed · +63 / -33 lines

## Interactive sign-in ## Interactive login

from line 1
11---
22title: CLI authentication options
33url: https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication
4description: Authenticate the ant CLI with interactive login, API keys, named profiles, and Workload Identity Federation.
4description: Authenticate the ant CLI with interactive sign-in, API keys, named profiles, and Workload Identity Federation.
55---
66 
7The `ant` CLI supports several credential sources. The [CLI quickstart](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart#authentication) covers the one-command login (`ant auth login`). This page covers every option in full.
7The `ant` CLI supports several credential sources. The [CLI quickstart](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart#authentication) covers the one-command sign-in (`ant auth login`). This page covers every option in full.
88 
9## Interactive login
9## Interactive sign-in
1010 
1111`ant auth login` lets you call the API without creating or managing an API key. It opens a browser-based OAuth flow against the Claude Console and stores the resulting credentials under `$ANTHROPIC_CONFIG_DIR` (see [Configuration directory](https://platform.claude.com/docs/en/manage-claude/wif-reference#configuration-directory) for the OS-specific default). On a remote host or in any environment without a local browser, pass `--no-browser` to print the authorize URL and paste the returned code back into the terminal.
1212 
from line 16
1616# On a remote host without a browser:
1717ant auth login --no-browser
1818 
19# Bind to a specific workspace and skip the browser picker:
19# Select a specific workspace and skip the browser picker:
2020ant auth login --workspace-id wrkspc_01...
2121 
2222# If the profile that you name with --profile doesn't exist,
23# the login creates it.
23# the sign-in creates it.
2424ant auth login --profile work
2525```
2626 
27The CLI stores each login under a profile. The first time you log in under a profile, you select a [workspace](https://platform.claude.com/docs/en/manage-claude/workspaces) in the browser. If you belong to more than one Claude Console organization, you select the organization first. The issued token is [scoped to that workspace](https://platform.claude.com/docs/en/manage-claude/workspaces#api-keys-and-resource-scoping), so the CLI can only see resources that belong to it. Pass `--workspace-id` to bind directly to a workspace and skip the workspace picker.
27The CLI stores each sign-in under a profile. The first time you sign in under a profile, you select a [workspace](https://platform.claude.com/docs/en/manage-claude/workspaces) in the browser. If you belong to more than one Claude Console organization, you select the organization first. The issued token is [scoped to that workspace](https://platform.claude.com/docs/en/manage-claude/workspaces#api-keys-and-resource-scoping), so the CLI can only see resources that belong to it. Pass `--workspace-id` to select a workspace directly and skip the workspace picker.
2828 
29The profile keeps that organization and workspace for its later logins. To work in another organization or workspace, log in under a new profile (see [Switch between workspaces](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#switch-between-workspaces)).
29The profile keeps that organization and workspace for its later sign-ins. To work in another organization or workspace, sign in under a new profile (see [Switch between workspaces](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#switch-between-workspaces)). You can also change the profile’s organization or workspace and sign in again (see [Manage profiles](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#manage-profiles)).
3030 
31Interactive login is intended for local development and scripting on your own machine. For non-interactive workloads such as CI, servers, and containers, use [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) instead.
31Interactive sign-in is intended for local development and scripting on your own machine. For non-interactive workloads such as CI, servers, and containers, use [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) instead.
3232 
33Login writes credentials to `credentials/<profile>.json`. The first login for a profile also creates `configs/<profile>.json`.
33Signing in writes credentials to `credentials/<profile>.json`. The first sign-in for a profile also creates `configs/<profile>.json`.
3434 
35A login that names a profile, with `--profile` or `ANTHROPIC_PROFILE`, makes that profile the [active profile](https://platform.claude.com/docs/en/manage-claude/wif-reference#active-profile). Any command that doesn’t name a profile, a login included, uses the active profile. Until you make another profile active, that’s `default`.
35A sign-in that names a profile, with `--profile` or `ANTHROPIC_PROFILE`, makes that profile the [active profile](https://platform.claude.com/docs/en/manage-claude/wif-reference#active-profile). Any command that doesn’t name a profile, a sign-in included, uses the active profile. Until you make another profile active, that’s `default`.
3636 
3737To remove the active profile’s stored credentials, run `ant auth logout`. The profile keeps its organization and workspace. To clear every profile, those settings included, run `ant auth logout --all`.
3838 
3939## Admin access
4040 
41By default, `ant auth login` requests a workspace-scoped token. To manage the resources documented on the [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api) page, request the `org:admin` scope under a dedicated profile. The login makes that profile active, so the example ends by switching back to your day-to-day profile:
41To manage your organization, such as with the organization commands for the [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api), you need the latest version of `ant`. To install `ant`, see [Installation](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart#installation) in the CLI quickstart. To sign in with the `org:admin` scope, you need the admin role (see the Admin API page’s [Organization roles and permissions](https://platform.claude.com/docs/en/manage-claude/admin-api#organization-roles-and-permissions) section).
4242 
43Unlike a usual sign-in, which works in one workspace, an admin sign-in can make changes across your organization.
44 
45The following commands change environment variables, so run them in a shell that you keep for administration. They list your profiles, unset `ANTHROPIC_API_KEY`, sign in under a separate profile with the `org:admin` scope, and export the token. The `--admin` flag in the `ant auth login` command adds the `org:admin` scope to the scopes that a sign-in already requests.
46 
47The sign-in also makes the `admin` profile the CLI’s active profile. Your other shells use it too. Until you switch back, clients in those shells that use the active profile, such as the `ant` CLI, can run as an admin.
48 
4349```bash CLI
44ant auth login --profile admin --scope "org:admin"
50# List your profiles. An asterisk marks the active one.
51# Note it, so that you can switch back later:
52ant profile list
4553 
46# Print a bearer token for Authorization headers:
47ant auth print-credentials --profile admin --access-token
54# Unset the API key variable.
55# While that variable is set, the SDK and the CLI use the key and not the token:
56unset ANTHROPIC_API_KEY
4857 
49# Switch back to your day-to-day profile, the one that was active
50# before the login, such as default:
51ant profile activate default
58ant auth login --profile admin --admin
59export ANTHROPIC_AUTH_TOKEN=$(ant auth print-credentials \
60 --profile admin --access-token)
5261```
5362 
54Anthropic grants the `org:admin` scope only to users and service accounts with the admin role. The issued token has organization-wide access, and any workspace binding on the profile does not constrain it. Keep the admin profile separate from your day-to-day profile so routine commands never run with elevated access.
63In this shell, the SDK and the `ant` CLI send the exported token on every call, whichever profile is active.
5564 
65For organization webhooks, sign in another way, as the [Sign in for organization webhooks](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#sign-in-for-organization-webhooks) section describes.
66 
67In this shell, run organization commands. For example, `ant organization:users list` lists your organization’s members.
68 
69The token in `ANTHROPIC_AUTH_TOKEN` is short-lived, and nothing renews it there. When requests start to return 401, follow these steps:
70 
711. Rerun the `export` command, which gets a new token if the old one has expired.
722. If requests still return 401, sign in again with the same `ant auth login` command that you used, and rerun the `export` command.
73 
74When you finish your admin work, undo what the sign-in commands changed. What to run for the active profile depends on whether you have a profile other than the one you signed in under:
75 
76* **You have another profile:** Switch back to the profile that was active before you signed in. If it was `default`, run `ant profile activate default`.
77* **You have no other profile:** `ant auth logout --all` revokes the tokens on the server and removes every profile and credential. Run it so that the profile you signed in under doesn’t stay the active one.
78 
79If you switched back, the profile you signed in under keeps its credential on disk. If you won’t need that credential for your next admin session, run `ant auth logout --profile` with the profile’s name, such as `admin`. That revokes its tokens on the server and deletes the credential.
80 
81The `unset` and `export` commands changed environment variables only in the shell where you ran them. To undo them, do one of these:
82 
83* Close that shell.
84* To keep using the shell, unset `ANTHROPIC_AUTH_TOKEN`, and set `ANTHROPIC_API_KEY` again if you use it.
85 
5686## API key
5787 
5888The CLI also reads your API key from the `ANTHROPIC_API_KEY` environment variable. Get a key from the [Claude Console](https://platform.claude.com/settings/keys).
from line 113
83113 
84114To override the key for a single run, pass [`--api-key-stdin`](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/using#global-flags) and pipe the key to the command. To point at a different API host, set `ANTHROPIC_BASE_URL` or pass `--base-url`.
85115 
86If you are using a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) that isn’t scoped to a workspace, you must [specify the workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) to run your command in. Do this by setting an `ANTHROPIC_WORKSPACE_ID` environment variable, which the CLI reads automatically, or by using the [`--workspace-id` flag](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/using#global-flags). The value must be a `wrkspc_...` ID.
116If you use a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/api-keys#key-types) scoped to the organization, [specify the workspace](https://platform.claude.com/docs/en/manage-claude/api-keys#select-a-workspace) to run your command in. Set the `ANTHROPIC_WORKSPACE_ID` environment variable, which the CLI reads automatically, or use the [`--workspace-id` flag](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/using#global-flags). The value must be a `wrkspc_...` ID.
87117 
88118```bash CLI
89119ant messages create \
from line 134
104134 
105135## Check authentication status
106136 
107`ant auth status` prints the credential source the CLI selected (API key environment variable, OAuth login, federation, Google Cloud, or profile), the active profile, the workspace the active token is bound to, and the configuration directory paths. Use it to diagnose why a workload picked the wrong credential or workspace.
137`ant auth status` prints the credential source the CLI selected (API key environment variable, OAuth sign-in, federation, Google Cloud, or profile), the active profile, the workspace the active token is scoped to, and the configuration directory paths. Use it to diagnose why a workload picked the wrong credential or workspace.
108138 
109139```bash CLI
110140ant auth status
from line 158
128158 
129159## Switch between workspaces
130160 
131An interactive-login token is bound to a single workspace. To use the CLI against more than one workspace, log in to each under its own named profile, then switch between them:
161A token from an interactive sign-in is scoped to one workspace at most. To use the CLI against more than one workspace, sign in to each under its own named profile, then switch between them:
132162 
133163```bash CLI
134164# 1. Create the profile (interactive; pick the other workspace in the
from line 165
135165# browser, or pass --workspace-id to skip the picker):
136166# ant auth login --profile other-ws
137167 
138# 2. The login made other-ws active. Switch back to your day-to-day
168# 2. The sign-in made other-ws active. Switch back to your day-to-day
139169# profile, such as default:
140170ant profile activate default
141171 

cli-sdks-libraries/sdks/ruby Changed · +5 / -1 lines

from line 40
4040end
4141```
4242 
43For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) that isn’t scoped to a workspace, set the workspace ID in the `anthropic-workspace-id` request header; [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) shows the per-request option for this SDK.
43For authentication options, including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/api-keys#key-types) scoped to the organization, set the workspace ID in the `anthropic-workspace-id` request header. For this SDK’s per-request option, see [Select a workspace](https://platform.claude.com/docs/en/manage-claude/api-keys#select-a-workspace) on the Developer API keys page.
44 
45If you sign in with `ant auth login`, the SDK doesn’t renew the access token that the sign-in stores. After the token expires, requests fail with an authentication error.
46 
47To renew the token, run `ant auth print-credentials --access-token > /dev/null`. If the token has expired or expires within 2 minutes, the command renews it and saves the new one. The redirect keeps the token out of your terminal and logs. The SDK reads the new token on its next request, so you don’t need to restart your application. If the command warns that it couldn’t renew the token, sign in again with `ant auth login`.
4448 
4549## Streaming
4650 

get-api-key Changed · +35 / -21 lines

## Before you begin ## Create a Developer API key ## Use your Developer API key ## Next steps ## Choose a key type ## Create an API key ## Use your API key ## API keys and the Admin API

from line 1
11---
22title: Get your Claude API key
33url: https://platform.claude.com/docs/en/get-api-key
4description: Find, create, and manage your API keys for the Claude API in the Claude Console.
4description: Create a Developer API key for the Claude API in the Claude Console, store it safely, and set it in your environment.
55---
66 
7API 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 the [API keys](https://platform.claude.com/settings/keys) page (`platform.claude.com/settings/keys`) in the Console.
7A Developer API key is a secret that lets your code call Claude. These steps create one in the Claude Console and set it in the `ANTHROPIC_API_KEY` environment variable, which the SDK and the CLI read.
88 
9## Choose a key type
9**Is this the key you need?** A Developer API key calls Claude, and an [Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) manages an organization. To compare them, see the [two kinds of API key](https://platform.claude.com/docs/en/manage-claude/authentication#api-keys).
1010 
11When you create a key, you choose its type, which determines what the key can do, where it works, and when it stops working. A **personal key** acts as you, and stops working if you leave an organization. A **service account key** represents a [service account](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#service-accounts), which can be used by workloads such as CI pipelines, production services, or agents. Use a personal key for your own development, and a service account key for anything shared.
11**You might not need a key.** To choose a method that doesn’t use one, see [Choose your path](https://platform.claude.com/docs/en/manage-claude/authentication#choose-your-path) on the Authentication page.
1212 
13You can also create a **workspace key**, a legacy key without an owner: it belongs to the workspace you create it in and keeps working after its creator leaves. It is preferable to use a personal or service account key, as these stop working automatically when their associated account is removed from the organization.
13## Before you begin
1414 
15## Create an API key
15Your role must allow you to create a key. To check which roles can, see [Who can create which key](https://platform.claude.com/docs/en/manage-claude/api-keys#who-can-create-which-key) on the Developer API keys page.
1616 
17## Create a Developer API key
18 
1719<Steps>
1820 <Step title="Sign in to the Claude Console">
19 Go to the Claude Console at [platform.claude.com](https://platform.claude.com/) and sign in, or create an account if you don’t have one yet.
21 Go to the [Claude Console](https://platform.claude.com/) and sign in or create an account if you don’t have one.
2022 </Step>
2123 
2224 <Step title="Open the API keys page">
23 In the Claude Console, go to the [API keys](https://platform.claude.com/settings/keys) page (`platform.claude.com/settings/keys`).
25 In the Claude Console, open the [API keys](https://platform.claude.com/settings/keys) page (`platform.claude.com/settings/keys`).
2426 </Step>
2527 
2628 <Step title="Create a key">
27 Click **Create key**, name the key, select an [expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration), and set **Linked account** to yourself or a service account. You can also select a [workspace](https://platform.claude.com/settings/workspaces) in the Console to scope the key to.
29 Click **Create key**. If the dialog first offers other ways to connect, click **Somewhere else** or **Continue with an API key**. Then, name the key and choose its settings:
30 
31 * **Expires:** how long the key lasts. You can’t change it later (see [Key expiration](https://platform.claude.com/docs/en/manage-claude/api-keys#key-expiration) on the Developer API keys page).
32 
33 * **Linked account:** who the key acts as (see [Key types](https://platform.claude.com/docs/en/manage-claude/api-keys#key-types) on the Developer API keys page):
34 
35 * Your name, marked **(you)**, for a personal key.
36 * A service account, for a service account key. Only organization admins can pick one.
37 * **Not linked**, for a legacy workspace key. Don’t use it for new integrations.
38 
39 * **Scope:** the workspace the key works in. If the key needs several workspaces, choose **Organization**. With that choice, each Claude API request must name a workspace in the `anthropic-workspace-id` header (see [Select a workspace](https://platform.claude.com/docs/en/manage-claude/api-keys#select-a-workspace) on the Developer API keys page).
2840 </Step>
2941 
3042 <Step title="Copy and store the key">
31 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.
43 The Console shows the full key only once. Copy it and store it somewhere safe, such as a secrets manager. If you lose it, create a new key.
3244 </Step>
3345</Steps>
3446 
35If the **Create key** button on the API keys page is disabled, your role might not allow you to create keys there. Ask an organization admin to change your role, or to create a service account key for your workload.
47If the **Create key** button is missing or disabled, your role might not allow it, or an organization admin might have turned off key creation. To find out why and what to do, see [Who can create which key](https://platform.claude.com/docs/en/manage-claude/api-keys#who-can-create-which-key) on the Developer API keys page.
3648 
3749These steps are for the Claude API. If you use Claude through a [cloud platform](https://platform.claude.com/docs/en/api/overview#claude-api-vs-cloud-platforms), follow that platform’s authentication steps instead.
3850 
39## Use your API key
51## Use your Developer API key
4052 
41Set the key as an environment variable:
53Set the key as an environment variable for your current shell session:
4254 
4355```bash
44export ANTHROPIC_API_KEY="sk-ant-api03-..."
56export ANTHROPIC_API_KEY="sk-ant-..."
4557```
4658 
47The [client SDK](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) reads `ANTHROPIC_API_KEY` automatically. Direct HTTP requests send the key as `Authorization: Bearer <key>`. If your API key isn’t scoped to a workspace, you must also send the `anthropic-workspace-id` header on each Claude API request, as shown in [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace). For the Admin API, see [API keys and the Admin API](https://platform.claude.com/docs/en/get-api-key#api-keys-and-the-admin-api).
59The SDK and the CLI read `ANTHROPIC_API_KEY` automatically. To set it for every new shell or on Windows, see [API key](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#api-key) on the CLI authentication options page.
4860 
49To 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 complete details, including short-lived credentials with Workload Identity Federation.
61To run the docs’ cURL samples with your key, see [Run the docs’ samples with a key](https://platform.claude.com/docs/en/manage-claude/api-keys#run-the-docs-samples-with-a-key) on the Developer API keys page.
5062 
51## API keys and the Admin API
63For key types, expiration, and key management with the Admin API, see [Developer API keys](https://platform.claude.com/docs/en/manage-claude/api-keys).
5264 
53The [Admin API](https://platform.claude.com/docs/en/api/organization) includes endpoints for managing your organization’s API keys programmatically, such as [Retrieve API Key](https://platform.claude.com/docs/en/api/organization/api_keys/retrieve) and [List API Keys](https://platform.claude.com/docs/en/api/organization/api_keys/list). These endpoints are for organization admins automating key management. They accept an [Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys), an OAuth token with the `org:admin` scope, or a personal or service account key that isn’t scoped to a specific workspace; workspace keys don’t work there. They never return a key’s secret value, only a partially redacted hint.
65## Next steps
5466 
55<Note>
56 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 on the [API keys](https://platform.claude.com/settings/keys) page (`platform.claude.com/settings/keys`) in the Claude Console.
57</Note>
67<CardGroup cols={2}>
68 <Card title="Get started with Claude" icon="code" href="https://platform.claude.com/docs/en/get-started">
69 Make your first request to Claude.
70 </Card>
71</CardGroup>
5872 

get-started Changed · +21 / -9 lines

from line 1
11---
22title: Get started with Claude
33url: https://platform.claude.com/docs/en/get-started
4description: Make your first API call to Claude and build a simple web search assistant.
4description: Make your first call to the Claude API from your terminal or your own code.
55---
66 
7By the end of this quickstart, you’ll have sent Claude a question and gotten its answer. You create a Claude Console account and sign in with the `ant` CLI or create an API key. Then, you make one request with cURL, the `ant` CLI, or a short program in Python, TypeScript, C#, Go, Java, PHP, or Ruby.
8 
79## Before you begin
810 
911<Steps continues>
from line 16
1416 <Step title="Choose how to authenticate">
1517 Signing in with the CLI is recommended for local development.
1618 
19 For code that runs in CI or on a server with an identity provider, set up [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) instead. For other ways to authenticate, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
20 
1721 Follow the steps for one of the following options.
1822 </Step>
1923</Steps>
from line 64
6064 ```
6165 </Tab>
6266 </Tabs>
67 
68 On Windows, you can install the CLI inside [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/windows/wsl/install) with the Linux steps. If you sign in with the CLI inside WSL, also run your code there so that it finds your sign-in.
6369 </Step>
6470 
6571 <Step title="Sign in" stepNumber={4}>
66 ```bash
72 ```bash CLI
6773 ant auth login
6874 ```
6975 
70 Once login is completed, the SDKs and CLI will pick up your credentials automatically.
76 Your browser opens. The first time you sign in, select an organization if you belong to more than one, and then a workspace.
77 
78 After you sign in, the SDK and the CLI use your credentials automatically unless `ANTHROPIC_API_KEY` is set (see [Which credential is used](https://platform.claude.com/docs/en/manage-claude/authentication#which-credential-is-used)).
7179 </Step>
7280</Steps>
7381 
from line 83
7583 
7684<Steps continued>
7785 <Step title="Create an API key" stepNumber={3}>
78 Create an [API key](https://platform.claude.com/settings/keys) in the Claude Console.
86 Create an API key by following the steps in [Get your Claude API key](https://platform.claude.com/docs/en/get-api-key#create-an-api-key).
7987 </Step>
8088 
8189 <Step title="Set the environment variable" stepNumber={4}>
82 The SDKs and CLI read your key from `ANTHROPIC_API_KEY`:
90 Set the key as an environment variable for your current shell session:
8391 
8492 ```bash
85 export ANTHROPIC_API_KEY="your-api-key-here"
93 export ANTHROPIC_API_KEY="sk-ant-..."
8694 ```
95 
96 The SDK and the CLI read `ANTHROPIC_API_KEY` automatically. To set it for every new shell or on Windows, see [API key](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#api-key) on the CLI authentication options page.
8797 </Step>
8898</Steps>
8999 
from line 218
208218 </Tab>
209219 </Tabs>
210220 
221 On Windows, you can install the CLI inside [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/windows/wsl/install) with the Linux steps. If you sign in with the CLI inside WSL, also run your code there so that it finds your sign-in.
222 
211223 Run `ant messages create` from your terminal:
212224 
213225 ```bash CLI
from line 693
681693 )
682694 
683695 message.content.each do |block|
684 puts block.text if block.type == :text
696 puts block.text if block.is_a?(Anthropic::Models::TextBlock)
685697 end
686698 ```
687699 </Step>
from line 719
707719 
708720You made your first API call. Next, learn the Messages API patterns you’ll use in every Claude integration.
709721 
710<Card title="Working with the Messages API" icon="messages" href="https://platform.claude.com/docs/en/build-with-claude/working-with-messages">
722<Card title="Using the Messages API" icon="messages" href="https://platform.claude.com/docs/en/build-with-claude/working-with-messages">
711723 Learn multi-turn conversations, system prompts, stop reasons, and other core patterns.
712724</Card>
713725 
from line 739
727739 </Card>
728740 
729741 <Card title="Authentication" icon="lock" href="https://platform.claude.com/docs/en/manage-claude/authentication">
730 Compare API keys and Workload Identity Federation, and set key expiration.
742 Compare CLI sign-in, Workload Identity Federation, App Attest, and API keys.
731743 </Card>
732744</CardGroup>
733745 

home Changed · +9 / -9 lines

from line 1
11---
22title: Documentation
33url: https://platform.claude.com/docs/en/home
4description: Claude API Documentation
4description: Claude API documentation
55---
66 
77<HomePage>
from line 249
249249 Quickstart
250250 </HomeJourneyLink>
251251 
252 <HomeJourneyLink icon="lock" href="https://platform.claude.com/settings/keys">
253 Get API key in Claude Console
252 <HomeJourneyLink icon="lock" href="https://platform.claude.com/docs/en/manage-claude/authentication">
253 Connect to the API
254254 </HomeJourneyLink>
255255 
256256 <HomeJourneyLink icon="settings" href="https://platform.claude.com/docs/en/models/overview">
from line 331
331331 </HomeJourneyStep>
332332 
333333 <HomeJourneyStep title="Operate">
334 <HomeJourneyLink icon="settings" href="https://platform.claude.com/docs/en/manage-claude/workspaces">
335 Workspaces and admin
334 <HomeJourneyLink icon="settings" href="https://platform.claude.com/docs/en/manage-claude/administering-claude">
335 Administering Claude
336336 </HomeJourneyLink>
337337 
338338 <HomeJourneyLink icon="lock" href="https://platform.claude.com/settings/keys">
from line 355
355355 Quickstart
356356 </HomeJourneyLink>
357357 
358 <HomeJourneyLink icon="lock" href="https://platform.claude.com/settings/keys">
359 Get API key in Claude Console
358 <HomeJourneyLink icon="lock" href="https://platform.claude.com/docs/en/manage-claude/authentication">
359 Connect to the API
360360 </HomeJourneyLink>
361361 
362362 <HomeJourneyLink icon="message" href="https://platform.claude.com/docs/en/managed-agents/onboarding">
from line 389
389389 </HomeJourneyStep>
390390 
391391 <HomeJourneyStep title="Operate">
392 <HomeJourneyLink icon="settings" href="https://platform.claude.com/docs/en/manage-claude/workspaces">
393 Workspaces and admin
392 <HomeJourneyLink icon="settings" href="https://platform.claude.com/docs/en/manage-claude/administering-claude">
393 Administering Claude
394394 </HomeJourneyLink>
395395 
396396 <HomeJourneyLink icon="lock" href="https://platform.claude.com/settings/keys">

manage-claude/admin-api Changed · +64 / -22 lines

from line 8
88 
99## Availability
1010 
11The Admin API is available to Claude Console and Claude Enterprise organizations. It isn’t available to organizations on the claude.ai Team plan or to individual Console accounts. An individual Console account must first set up an organization on the [Organization](https://platform.claude.com/settings/organization) page (`platform.claude.com/settings/organization`) in the Claude Console. See [Create an Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) for where each organization type creates its key.
11The Admin API is available to Claude Console and Claude Enterprise organizations.
1212 
13Claude Enterprise (claude.ai) organizations call the Admin API with a scoped API key created in claude.ai. From this page, only the members, invites, and [organization info](https://platform.claude.com/docs/en/manage-claude/admin-api#accessing-organization-info) endpoints apply to them. Outside this page, they can also call the following APIs and endpoints:
13<Tip>
14 The Admin API isn’t available to organizations on the claude.ai Team plan, and an individual Claude Console account can’t create an Admin API key.
15</Tip>
1416 
17If your company has a Claude Console organization, you can use the Admin API with that organization; see the [Admin API keys and tokens](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) page. An individual Console account must first set up an organization on the [Organization settings](https://platform.claude.com/settings/organization) page (`platform.claude.com/settings/organization`) in the Claude Console.
18 
19Claude Enterprise (claude.ai) organizations call the Admin API with an Enterprise Admin API key created in claude.ai. From this page, only the members, invites, and [organization info](https://platform.claude.com/docs/en/manage-claude/admin-api#accessing-organization-info) endpoints apply to them. Outside this page, they can also call the following APIs and endpoints:
20 
1521* The [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api), which is in beta and takes a key with the `read:analytics` scope.
1622* Enterprise-only endpoints: groups, custom-role reads, and the [Spend Limits API](https://platform.claude.com/docs/en/manage-claude/spend-limits-api).
17* The [Plugins API](https://platform.claude.com/docs/en/manage-claude/plugins-api) and the [Claude Tag API](https://platform.claude.com/docs/en/manage-claude/claude-tag-api), which are Enterprise-only and in beta.
23* The [Plugins API](https://platform.claude.com/docs/en/manage-claude/plugins-api), the [Claude Tag API](https://platform.claude.com/docs/en/manage-claude/claude-tag-api), and the [Claude Code Managed Settings API](https://platform.claude.com/docs/en/api/beta/organization/claude_code/managed_settings), which are Enterprise-only and in beta.
1824 
1925For members, invites, groups, and custom roles, see [User management](https://platform.claude.com/docs/en/manage-claude/user-management).
2026 
from line 30
2430 
2531The Admin API accepts any of these three credentials:
2632 
27* 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).
28* An **OAuth bearer token** with the `org:admin` scope sent in the `authorization: Bearer` header. Only users and service accounts with the admin role can obtain one. See [Obtain an OAuth bearer token](https://platform.claude.com/docs/en/manage-claude/admin-api#oauth-bearer-token).
29* A **personal key** or **service account key** that isn’t scoped to a specific workspace, sent in the `x-api-key` header. The key has the same permissions as the linked account. See [Key types](https://platform.claude.com/docs/en/manage-claude/authentication#key-types).
33* A **Console Admin API key** (starting with `sk-ant-admin...`) sent in the `x-api-key` header or the `authorization: Bearer` header. Only organization members with the admin role can provision one. See [Admin API keys and tokens](https://platform.claude.com/docs/en/manage-claude/admin-api-keys).
34* An **OAuth bearer token** with the `org:admin` scope, sent in the `authorization: Bearer` header. A user needs the admin role to obtain one. See [OAuth bearer token](https://platform.claude.com/docs/en/manage-claude/admin-api#oauth-bearer-token). For the role a service account needs, see [Permission boundaries](https://platform.claude.com/docs/en/manage-claude/wif-reference#permission-boundaries) on the Workload Identity Federation (WIF) reference page.
35* A **personal key** or **service account key** scoped to the organization, sent in the `x-api-key` header or the `authorization: Bearer` header. The key has the permissions of its linked account. See [Key types](https://platform.claude.com/docs/en/manage-claude/api-keys#key-types) on the Developer API keys page.
3036 
31An Admin API key covers most endpoints. The service-account, federation-issuer, and federation-rule endpoints accept only an `org:admin` OAuth token. Send a personal key or service account key in the `x-api-key` header, as you would an Admin API key. The following examples call the [organization info endpoint](https://platform.claude.com/docs/en/manage-claude/admin-api#accessing-organization-info) with an OAuth token and with an Admin API key.
37An Admin API key covers most endpoints, but 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) with an OAuth token and with an Admin API key.
3238 
3339The SDK exposes the endpoints on this page under `client.organization` (csharp, go: `client.Organization`; java: `client.organization()`; php: `$client->organization`), and the `ant` CLI under `ant organization`. The examples on this page use the default client, which reads an Admin API key from `ANTHROPIC_API_KEY` or an OAuth bearer token from `ANTHROPIC_AUTH_TOKEN`. The comments in each list example say whether it fetches more pages or reads only the first. For each endpoint’s parameters and responses, see the [Admin API reference](https://platform.claude.com/docs/en/api/organization).
3440 
3541### OAuth bearer token
3642 
37Log in with the [`ant` CLI](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart) under a dedicated profile with 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. `--profile admin` stores the `org:admin` credential under its own profile and makes it the CLI’s active profile. The exported variable applies to every SDK and CLI call in that shell. Use a shell you reserve for administration, unset the variable when you’re done, and switch the CLI back with `ant profile activate default`:
43You need the latest version of the `ant` CLI. To install it, see [Installation](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart#installation) in the CLI quickstart.
3844 
45Unlike a usual sign-in, which works in one workspace, an admin sign-in can make changes across your organization.
46 
47The following commands change environment variables, so run them in a shell that you keep for administration. They list your profiles, unset `ANTHROPIC_API_KEY`, sign in under a separate profile with the `org:admin` scope, and export the token. The `--admin` flag in the `ant auth login` command adds the `org:admin` scope to the scopes that a sign-in already requests.
48 
49The sign-in also makes the `admin` profile the CLI’s active profile. Your other shells use it too. Until you switch back, clients in those shells that use the active profile, such as the `ant` CLI, can run as an admin.
50 
3951```bash CLI
40ant auth login --profile admin --scope "org:admin"
41export ANTHROPIC_AUTH_TOKEN=$(ant auth print-credentials --profile admin --access-token)
52# List your profiles. An asterisk marks the active one.
53# Note it, so that you can switch back later:
54ant profile list
55 
56# Unset the API key variable.
57# While that variable is set, the SDK and the CLI use the key and not the token:
58unset ANTHROPIC_API_KEY
59 
60ant auth login --profile admin --admin
61export ANTHROPIC_AUTH_TOKEN=$(ant auth print-credentials \
62 --profile admin --access-token)
4263```
4364 
44Interactive tokens are short-lived. If requests start returning 401, rerun the `export` command to refresh the token.
65In this shell, the SDK and the `ant` CLI send the exported token on every call, whichever profile is active.
4566 
46The SDK and the `ant` CLI read `ANTHROPIC_AUTH_TOKEN` automatically. Leave `ANTHROPIC_API_KEY` unset in the same shell so they send the bearer token. Automated workloads skip the login: they authenticate through Workload Identity Federation, and the SDK and CLI perform the token exchange from the federation environment variables. See [Bootstrap a workload to manage WIF](https://platform.claude.com/docs/en/manage-claude/wif-admin-api#bootstrap-a-workload-to-manage-wif).
67For organization webhooks, sign in another way, as the [Sign in for organization webhooks](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#sign-in-for-organization-webhooks) section describes.
4768 
4869Call the Admin API with the exported token:
4970 
from line 146
125146 ```
126147</CodeGroup>
127148 
128An `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.
149The token in `ANTHROPIC_AUTH_TOKEN` is short-lived, and nothing renews it there. When requests start to return 401, follow these steps:
129150 
1511. Rerun the `export` command, which gets a new token if the old one has expired.
1522. If requests still return 401, sign in again with the same `ant auth login` command that you used, and rerun the `export` command.
153 
154When you finish your admin work, undo what the sign-in commands changed. What to run for the active profile depends on whether you have a profile other than the one you signed in under:
155 
156* **You have another profile:** Switch back to the profile that was active before you signed in. If it was `default`, run `ant profile activate default`.
157* **You have no other profile:** `ant auth logout --all` revokes the tokens on the server and removes every profile and credential. Run it so that the profile you signed in under doesn’t stay the active one.
158 
159If you switched back, the profile you signed in under keeps its credential on disk. If you won’t need that credential for your next admin session, run `ant auth logout --profile` with the profile’s name, such as `admin`. That revokes its tokens on the server and deletes the credential.
160 
161The `unset` and `export` commands changed environment variables only in the shell where you ran them. To undo them, do one of these:
162 
163* Close that shell.
164* To keep using the shell, unset `ANTHROPIC_AUTH_TOKEN`, and set `ANTHROPIC_API_KEY` again if you use it.
165 
130166For 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).
131167 
132168### Admin API key
133169 
134To 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).
170To create an Admin API key for your organization type, see [Admin API keys and tokens](https://platform.claude.com/docs/en/manage-claude/admin-api-keys).
135171 
136172<CodeGroup>
137173 ```bash cURL
from line 1402
13661402 
13671403### API keys
13681404 
1369Monitor and manage [API keys](https://platform.claude.com/docs/en/api/organization/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)) and `principal`, the identity it acts as (see [Key types](https://platform.claude.com/docs/en/manage-claude/authentication#key-types)). For a personal key, `principal` is `{"type": "user_actor", "user_id": "user_..."}`. For a service account key, it is `{"type": "service_account_actor", "service_account_id": "svac_..."}`. For a workspace key, it is `null`. Each key also has a `scope` object: `{"type": "workspace", "workspace_id": "wrkspc_..."}` for a key bound to one workspace, or `{"type": "organization"}` for a key that can work across any workspace the account has access to. Filtering the list by `workspace_id` with the Default Workspace’s ID returns only keys bound to the Default Workspace; keys without a workspace scope aren’t returned under any `workspace_id` filter.
1405Monitor and manage [API keys](https://platform.claude.com/docs/en/api/organization/api_keys/list). Each key in the response includes these fields:
13701406 
1407* `expires_at`: when the key expires. It’s `null` for a key without an expiration (see [Key expiration](https://platform.claude.com/docs/en/manage-claude/api-keys#key-expiration)).
1408* `principal`: the identity the key acts as (see [Key types](https://platform.claude.com/docs/en/manage-claude/api-keys#key-types)). It’s `{"type": "user_actor", "user_id": "user_..."}` for a personal key, `{"type": "service_account_actor", "service_account_id": "svac_..."}` for a service account key, and `null` for a workspace key.
1409* `scope`: where the key can work. It’s `{"type": "workspace", "workspace_id": "wrkspc_..."}` for a key scoped to one workspace, and `{"type": "organization"}` for a key scoped to the organization, which can work in several workspaces.
1410 
1411Filtering the list by `workspace_id` with the default workspace’s ID returns only keys scoped to the default workspace. A key scoped to the organization isn’t returned under any `workspace_id` filter. To list such keys, leave out `workspace_id`: the list then includes every Developer API key that your credential can list (see [Developer API keys](https://platform.claude.com/docs/en/manage-claude/api-keys)).
1412 
13711413List the active API keys in a workspace:
13721414 
13731415<CodeGroup>
from line 1686
16441686 
16451687### Service accounts
16461688 
1647Create and manage service accounts (`svac_...`), the non-human identities that [service account keys](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) and [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) tokens act as. These endpoints, like the federation-issuer and federation-rule endpoints, require an `org:admin` OAuth token. See [Service accounts in Manage WIF with the Admin API](https://platform.claude.com/docs/en/manage-claude/wif-admin-api#service-accounts).
1689Create and manage service accounts (`svac_...`), the non-human identities that [service account keys](https://platform.claude.com/docs/en/manage-claude/api-keys#key-types) and [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) tokens act as. These endpoints, like the federation-issuer and federation-rule endpoints, require an `org:admin` OAuth token. See [Service accounts in Manage WIF with the Admin API](https://platform.claude.com/docs/en/manage-claude/wif-admin-api#service-accounts).
16481690 
16491691### Federation issuers
16501692 
from line 1836
17941836* Handle errors from failed operations
17951837* Regularly audit member roles and permissions
17961838* Archive unused workspaces and delete pending invites you no longer need
1797* 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
1839* Monitor API key usage, audit each key’s `expires_at` (see [Key expiration](https://platform.claude.com/docs/en/manage-claude/api-keys#key-expiration)), and rotate keys periodically
17981840 
17991841## FAQ
18001842 
18011843<AccordionGroup>
18021844 <Accordion title="What permissions are needed to use the Admin API?">
1803 The Admin API accepts an Admin API key (starting with `sk-ant-admin`), an OAuth bearer token with the `org:admin` scope, or a personal key or service account key that isn’t scoped to a specific workspace. Only organization members with the admin role can provision Admin API keys. Only users and service accounts with the admin role can obtain `org:admin` tokens. A personal key or service account key has the same permissions as the linked account. See [Authentication](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication).
1845 In a Claude Console organization, you need the admin organization role to create a Console Admin API key or to sign in with the `org:admin` scope. For every credential the Admin API accepts and how roles apply to each one, see the [Authentication](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication) section. A Claude Enterprise organization uses an Enterprise Admin API key instead. See the [Admin API keys and tokens](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) page.
18041846 </Accordion>
18051847 
18061848 <Accordion title="Can the Admin API create API keys?">
from line 1850
18081850 </Accordion>
18091851 
18101852 <Accordion title="What happens to API keys when removing a user?">
1811 Behavior depends on the [key type](https://platform.claude.com/docs/en/manage-claude/authentication#key-types).
1853 Behavior depends on the [key type](https://platform.claude.com/docs/en/manage-claude/api-keys#key-types).
18121854 
18131855 Personal keys stop working when their user is removed from the organization. Service account keys stop working if their service account is archived, but continue to work even if the user that created them is removed. Workspace API keys continue to work. In the [Claude Code workspace](https://platform.claude.com/docs/en/manage-claude/workspaces#claude-code-workspace), each key is bound to the member who created it and stops working when that member is removed.
18141856 </Accordion>

manage-claude/admin-api-keys Changed · +211 / -80 lines

## Claude Console organizations ### What a Console Admin API key works with ## Get an access token with the `org:admin` scope ### Renew the access token and clean up ### Sign in for organization webhooks ## Claude Enterprise organizations ### Key access ### Create the key in claude.ai ## Use the key or access token ## Replace an Admin API key ## Which key do you need? ## Choose scopes for a Claude Enterprise key ## Use the key ## Next steps

from line 1
11---
2title: Create an Admin API key
2title: Admin API keys and tokens
33url: https://platform.claude.com/docs/en/manage-claude/admin-api-keys
4description: Create an Admin API key for your Claude Console or Claude Enterprise organization.
4description: "Get the credential a program uses to manage your Claude Console or Claude Enterprise organization: an Admin API key or a token with the org:admin scope."
55---
66 
7An Admin API key authenticates calls to the APIs that manage and report on your organization, such as the [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api) and the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api). One key can work with several of these APIs.
7**Is this the key you need?** Admin API keys and tokens manage an organization. To call Claude instead, for example to send a message, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
88 
9## Which key do you need?
9A program that holds an Admin API key or token can manage your organization. Depending on the credential, it can manage members, invites, and workspaces through the [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api), read activity records through the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api), or report usage and cost through the [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api). This page helps you choose the credential and get it.
1010 
11The key you need depends on which Claude product your organization uses: Claude Console (Claude Platform) or Claude Enterprise.
11Which credential you use depends on where you manage your organization: in the Claude Console (`platform.claude.com`) or in Claude Enterprise (`claude.ai`).
1212 
13| Organization | Claude Console | Claude Enterprise |
13| Organization | Use | What it reaches |
1414| ----- | ----- | ----- |
15| **Sign-in address** | `platform.claude.com` | `claude.ai` |
16| **Where to create it** | [Admin keys](https://platform.claude.com/settings/admin-keys) page in the Claude Console | [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access) |
17| **Key prefix** | `sk-ant-admin01-...` | `sk-ant-api01-...` |
18| **Who can create it** | Organization members with the **admin** role | **Primary owner:** any scope<br />**Organization owner:** Compliance API scopes only, for their own organization |
19| **Scopes** | None to select: every key has full access to the endpoints that accept it | [Choose scopes](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#choose-scopes-for-a-claude-enterprise-key) when you create the key. The key works only with the APIs your scopes cover |
20| **Works with** | [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api)<br />[Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api)<br />[Compliance API Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed)<br />[Safety Cases API](https://platform.claude.com/docs/en/manage-claude/enterprise-frontier-safeguards/safety-cases-api#get-access), for keys created while it’s available<br />[Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api) (legacy)<br />[Rate Limits API](https://platform.claude.com/docs/en/manage-claude/rate-limits-api)<br />[Claude Code Analytics API](https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api) | Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management)<br />[Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api)<br />[Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api)<br />[Claude Enterprise Analytics API](https://platform.claude.com/docs/en/manage-claude/analytics-api)<br />[Plugins API](https://platform.claude.com/docs/en/manage-claude/plugins-api)<br />[Claude Tag API](https://platform.claude.com/docs/en/manage-claude/claude-tag-api)<br />[Spend Limits API](https://platform.claude.com/docs/en/manage-claude/spend-limits-api) |
15| A Claude Console organization | A Console Admin API key or a token with the `org:admin` scope | The whole organization |
16| A Claude Enterprise organization | An Enterprise Admin API key | What its scopes allow |
2117 
2218On Claude Models on Google Cloud (Anthropic managed) or Claude Platform on AWS, use that platform’s credentials instead of an Admin API key. For the Admin API endpoints you can call on those platforms, see [Cloud platforms](https://platform.claude.com/docs/en/manage-claude/admin-api#cloud-platforms) on the Admin API page. For the Activity Feed on those platforms, see [Set up the Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api-access#set-up-the-compliance-api).
2319 
24Most keys reach only the organization you created them in. Some keys, such as those with Compliance API, group, or audit scopes, can reach further if your company links its organizations under a [parent organization](https://platform.claude.com/docs/en/manage-claude/compliance-api-access#which-key-do-you-need). If your company uses both Claude Console and Claude Enterprise, create one key in each.
20There are two kinds of API key, each named for its main job:
2521 
22| Key | What it works with |
23| ----- | ----- |
24| **Developer API key** | The APIs that call Claude, such as Messages, Files, and Managed Agents |
25| **Admin API key** | The APIs that manage and report on an organization, such as the [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api) and the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api) |
26 
27An Admin API key can’t call Claude. The Claude Console calls a Developer API key an “API key” and lists these keys on its **API keys** page.
28 
29## Claude Console organizations
30 
31An individual Console account can’t create an Admin API key. To use the Admin API, set up an organization, as the Admin API page’s [Availability](https://platform.claude.com/docs/en/manage-claude/admin-api#availability) section describes. In an organization, use one of two credentials to manage the whole organization:
32 
33* **A Console Admin API key** fits either an automated job with no [identity provider](https://platform.claude.com/docs/en/manage-claude/authentication#workload-identity-federation) or a tool that takes only a key. The key is a stored secret that belongs to the organization, not to a person. See [Create a key for a Claude Console organization](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#create-a-key-for-a-claude-console-organization).
34* **A token with the `org:admin` scope** fits either a person at a terminal or an automated job whose platform has an identity provider. The token is short-lived and acts as a person or a service account. With only this scope, it can’t call Claude. See [Get an access token with the `org:admin` scope](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#get-a-token-with-the-org-admin-scope).
35 
36The two differ in a few places:
37 
38* Only a Console Admin API key, not a token, reads the Compliance API’s Activity Feed. See [Query the Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed).
39* Only a token with the `org:admin` scope manages service accounts and federation.
40 
2641## Create a key for a Claude Console organization
2742 
28An individual Claude Console account cannot create this key, so [set up an organization](https://platform.claude.com/docs/en/manage-claude/admin-api#availability) first. To use the key with the Activity Feed, [enable the Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api-access#set-up-the-compliance-api) before you create it.
43Before you start:
2944 
45* You need the admin role in a Claude Console organization. See the Admin API page’s [Organization roles and permissions](https://platform.claude.com/docs/en/manage-claude/admin-api#organization-roles-and-permissions) section.
46* If the key needs to read the Activity Feed, enable the Compliance API before you create the key, as [Set up the Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api-access#set-up-the-compliance-api) describes. A key created before then can’t read the feed, so replace it with a new one.
47 
3048<Steps>
3149 <Step title="Open Admin keys settings">
32 Sign in to the Claude Console as an [organization admin](https://platform.claude.com/docs/en/manage-claude/admin-api#organization-roles-and-permissions). Go to the [Admin keys](https://platform.claude.com/settings/admin-keys) page (`platform.claude.com/settings/admin-keys`).
50 Sign in to the Claude Console and go to the [Admin keys](https://platform.claude.com/settings/admin-keys) page (`platform.claude.com/settings/admin-keys`).
3351 </Step>
3452 
3553 <Step title="Create the key">
from line 55
3755 A key that you create while the [Safety Cases API](https://platform.claude.com/docs/en/manage-claude/enterprise-frontier-safeguards/safety-cases-api#get-access) is available to your organization can also read that organization’s flagged messages and respond to its Safety Cases. You can’t leave this access out, so limit who can create and hold a key.
3856 </Warning>
3957 
40 Click **Create admin key**, give it a name, select a [key expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration), and click **Add**.
58 Click **Create admin key**, name the key, select a [key expiration](https://platform.claude.com/docs/en/manage-claude/api-keys#key-expiration), and click **Add**.
4159 </Step>
4260 
4361 <Step title="Copy and store the secret">
44 Copy the displayed secret (starting with `sk-ant-admin01-`) and store it in your secrets manager. The full secret is shown only once.
62 Copy the displayed secret, which starts with `sk-ant-admin01-`, and store it in your secrets manager. The full secret is shown only once.
4563 </Step>
4664</Steps>
4765 
66### What a Console Admin API key works with
67 
68A Console Admin API key manages the Claude Console organization it was created in. The key has no scopes to choose, so a program that holds it can call these APIs:
69 
70| API | Use it to |
71| ----- | ----- |
72| [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api) | Manage members, invites, workspaces, and [Developer API keys](https://platform.claude.com/docs/en/manage-claude/api-keys) |
73| [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api) | Report token usage and cost |
74| [Usage and Cost API](https://platform.claude.com/docs/en/manage-claude/usage-cost-api) (legacy) | Report usage and cost |
75| [Rate Limits API](https://platform.claude.com/docs/en/manage-claude/rate-limits-api) | Read your organization’s rate limits and set workspace limits |
76| [Claude Code Analytics API](https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api) | Report on Claude Code productivity |
77| [Compliance API Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed) | Read organization-wide activity events |
78 
79A key that you create while the [Safety Cases API](https://platform.claude.com/docs/en/manage-claude/enterprise-frontier-safeguards/safety-cases-api#get-access) is available to your organization also reaches that API.
80 
81## Get an access token with the `org:admin` scope
82 
83How you get the token depends on who makes the calls:
84 
85* **A person at a terminal:** Sign in with the `ant` CLI and the `org:admin` scope, as the following commands show.
86* **An automated job whose platform has an identity provider:** Use [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation). An admin creates a federation rule that grants the `org:admin` scope. See the Manage WIF with the Admin API page’s [Bootstrap a workload to manage WIF](https://platform.claude.com/docs/en/manage-claude/wif-admin-api#bootstrap-a-workload-to-manage-wif) section.
87 
88A person needs the admin role to sign in with the `org:admin` scope. For the role a service account needs, see [Permission boundaries](https://platform.claude.com/docs/en/manage-claude/wif-reference#permission-boundaries) on the WIF reference page.
89 
90You need the latest version of the `ant` CLI. To check yours, compare the output of `ant --version` with the newest release on the CLI’s [GitHub releases page](https://github.com/anthropics/anthropic-cli/releases). To install the latest version, use one of these methods:
91 
92<Tabs noDeepLinks>
93 <Tab title="Homebrew (macOS)">
94 ```bash
95 brew install anthropics/tap/ant
96 ```
97 </Tab>
98 
99 <Tab title="curl (Linux/WSL)">
100 For Linux environments, download the release binary directly.
101 
102 ```bash
103 VERSION=2.14.0
104 OS=$(uname -s | tr '[:upper:]' '[:lower:]')
105 case $(uname -m) in
106 x86_64) ARCH=amd64 ;;
107 aarch64) ARCH=arm64 ;;
108 esac
109 curl -fsSL "https://github.com/anthropics/anthropic-cli/releases/download/v${VERSION}/ant_${VERSION}_${OS}_${ARCH}.tar.gz" \
110 | sudo tar -xz -C /usr/local/bin ant
111 ```
112 
113 You can find all releases on the [GitHub releases page](https://github.com/anthropics/anthropic-cli/releases).
114 </Tab>
115 
116 <Tab title="go install">
117 You can also install the CLI from source with `go install`, which requires Go 1.26.10 or later.
118 
119 ```bash
120 go install github.com/anthropics/anthropic-cli/v2/cmd/ant@latest
121 ```
122 
123 `go install` places the binary in `$(go env GOPATH)/bin`. Add that directory to your `PATH` if it isn’t already there:
124 
125 ```bash
126 export PATH="$PATH:$(go env GOPATH)/bin"
127 ```
128 </Tab>
129</Tabs>
130 
131On Windows, you can install the CLI inside [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/windows/wsl/install) with the Linux steps. If you sign in with the CLI inside WSL, also run your code there so that it finds your sign-in.
132 
133Unlike a usual sign-in, which works in one workspace, an admin sign-in can make changes across your organization.
134 
135The following commands change environment variables, so run them in a shell that you keep for administration. They list your profiles, unset `ANTHROPIC_API_KEY`, sign in under a separate profile with the `org:admin` scope, and export the token. The `--admin` flag in the `ant auth login` command adds the `org:admin` scope to the scopes that a sign-in already requests.
136 
137The sign-in also makes the `admin` profile the CLI’s active profile. Your other shells use it too. Until you switch back, clients in those shells that use the active profile, such as the `ant` CLI, can run as an admin.
138 
139```bash CLI
140# List your profiles. An asterisk marks the active one.
141# Note it, so that you can switch back later:
142ant profile list
143 
144# Unset the API key variable.
145# While that variable is set, the SDK and the CLI use the key and not the token:
146unset ANTHROPIC_API_KEY
147 
148ant auth login --profile admin --admin
149export ANTHROPIC_AUTH_TOKEN=$(ant auth print-credentials \
150 --profile admin --access-token)
151```
152 
153In this shell, the SDK and the `ant` CLI send the exported token on every call, whichever profile is active.
154 
155For organization webhooks, sign in another way, as the [Sign in for organization webhooks](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#sign-in-for-organization-webhooks) section describes.
156 
157### Renew the access token and clean up
158 
159The token in `ANTHROPIC_AUTH_TOKEN` is short-lived, and nothing renews it there. When requests start to return 401, follow these steps:
160 
1611. Rerun the `export` command, which gets a new token if the old one has expired.
1622. If requests still return 401, sign in again with the same `ant auth login` command that you used, and rerun the `export` command.
163 
164When you finish your admin work, undo what the sign-in commands changed. What to run for the active profile depends on whether you have a profile other than the one you signed in under:
165 
166* **You have another profile:** Switch back to the profile that was active before you signed in. If it was `default`, run `ant profile activate default`.
167* **You have no other profile:** `ant auth logout --all` revokes the tokens on the server and removes every profile and credential. Run it so that the profile you signed in under doesn’t stay the active one.
168 
169If you switched back, the profile you signed in under keeps its credential on disk. If you won’t need that credential for your next admin session, run `ant auth logout --profile` with the profile’s name, such as `admin`. That revokes its tokens on the server and deletes the credential.
170 
171The `unset` and `export` commands changed environment variables only in the shell where you ran them. To undo them, do one of these:
172 
173* Close that shell.
174* To keep using the shell, unset `ANTHROPIC_AUTH_TOKEN`, and set `ANTHROPIC_API_KEY` again if you use it.
175 
176### Sign in for organization webhooks
177 
178The [organization webhooks](https://platform.claude.com/docs/en/manage-claude/organization-webhooks) endpoints accept an `org:admin` token. The token must be scoped to the default workspace or to no workspace. See that page’s [Before you start](https://platform.claude.com/docs/en/manage-claude/organization-webhooks#before-you-begin) section. To get a token that isn’t scoped to a workspace, run the sign-in commands earlier on this page with two changes:
179 
180* In the `ant auth login` command, pass `--scope "org:admin"` in place of `--admin`.
181* Use another profile name, such as `webhooks`, in both the `ant auth login` and `ant auth print-credentials` commands.
182 
183With only the `org:admin` scope, that profile can’t call Claude or run your usual commands.
184 
185## Claude Enterprise organizations
186 
187In a Claude Enterprise organization, the Admin API and the Compliance API take an Enterprise Admin API key. So does every other API listed on the [Enterprise Admin API key scopes](https://platform.claude.com/docs/en/manage-claude/enterprise-admin-api-key-scopes) page.
188 
48189## Create a key for a Claude Enterprise organization
49190 
191A key that holds only Compliance API scopes is also called a Compliance Access Key. A key that holds only `read:analytics` is also called an Analytics API key.
192 
193Before you start:
194 
195* You need the primary owner or organization owner role in a Claude Enterprise organization. See the User management page’s [Organization roles](https://platform.claude.com/docs/en/manage-claude/user-management#organization-roles) section.
196* A primary owner can select any scope. An organization owner can select only Compliance API scopes and only on a key for their own organization. See [Who can select which scopes](https://platform.claude.com/docs/en/manage-claude/enterprise-admin-api-key-scopes#who-can-select-which-scopes) on the Enterprise Admin API key scopes page.
197* If the key needs Compliance API scopes, first enable the Compliance API, as [Set up the Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api-access#set-up-the-compliance-api) describes.
198* If the key needs `read:analytics`, first get access to the Claude Enterprise Analytics API. See [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).
199 
200### Key access
201 
202When you select a Compliance API scope in claude.ai, the key form can show **Key access** options:
203 
204* **Only this organization:** The key is for your organization. This option is selected by default.
205* **All organizations:** The key’s Compliance API scopes reach all linked organizations. Only the primary owner can select this option. The key can then hold only Compliance API, group, and audit scopes.
206 
207### Create the key in claude.ai
208 
50209<Steps>
210 <Step title="Choose the scopes">
211 List every scope your program needs. For what a scope allows, see [Enterprise Admin API key scopes](https://platform.claude.com/docs/en/manage-claude/enterprise-admin-api-key-scopes). You can’t add a scope to the key later.
212 </Step>
213 
51214 <Step title="Open API settings">
52 Sign in to claude.ai as the [primary owner or an organization owner](https://platform.claude.com/docs/en/manage-claude/user-management#organization-roles). Go to [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access) and find the **Keys** section.
215 Sign in to claude.ai and open your organization’s [API settings](https://claude.ai/admin-settings/api-access), at **Organization settings** > **API**. Find the **Keys** section.
53216 </Step>
54217 
55 <Step title="Create the key">
56 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.
218 <Step title="Name the key and select its scopes">
219 Click **Create key** and name the key. If the key needs Compliance API scopes, select them first.
57220 
58 If the **Key access** options appear when you select a Compliance API scope, **Only this organization** is selected by default. To reach every organization under your parent organization, choose **All organizations**. Such a key can hold only Compliance API, group, and audit scopes.
221 If **Key access** appears, choose which organizations the key reaches. See [Key access](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#key-access).
59222 
223 Then, select any other scopes.
224 </Step>
225 
226 <Step title="Create the key">
60227 Click **Create**. If the key has the `delete:compliance_user_data` scope, also click **Confirm and create key**.
61228 </Step>
62229 
63230 <Step title="Copy and store the secret">
64 Copy the displayed secret (starting with `sk-ant-api01-`) and store it in your secrets manager. The full secret is shown only once.
231 Copy the displayed secret, which starts with `sk-ant-api01-`, and store it in your secrets manager. The full secret is shown only once.
65232 </Step>
66233</Steps>
67234 
68## Choose scopes for a Claude Enterprise key
235## Use the key or access token
69236 
70When 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. A key that holds only Compliance API scopes is also called a Compliance Access Key. A key that holds only `read:analytics` is also called an Analytics API key.
237Send a key or a token in the `Authorization` header as `Bearer <credential>`. A key also works in the `x-api-key` header. Each API’s page has complete request examples.
71238 
72| To call... | Select these scopes |
73| ----- | ----- |
74| 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` |
75| Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management): change member roles, remove members, [sign members out everywhere](https://platform.claude.com/docs/en/manage-claude/user-management#sign-a-member-out-everywhere) (beta), and create and withdraw invites (to assign the `managed` role on a role change or an invite, also select `write:rbac_groups`) | `write:members` |
76| Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management): read groups and their members | `read:rbac_groups` |
77| Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management): create, rename, and delete groups; add and remove group members; with `write:members`, assign the `managed` role (on an invite or a role change) or assign groups on an invite | `write:rbac_groups` |
78| [Plugins API](https://platform.claude.com/docs/en/manage-claude/plugins-api): read plugins, versions, installation settings, shares, and marketplaces; download plugin files, including the files of members’ personal plugins; validate a marketplace before you connect it | `read:plugins` |
79| [Plugins API](https://platform.claude.com/docs/en/manage-claude/plugins-api): upload plugins and versions; choose which version members are served; delete plugins, including members’ personal plugins; set and remove installation settings; set a marketplace’s default installation setting; validate a marketplace before you connect it (to read plugins, also select `read:plugins`) | `write:plugins` |
80| [Claude Tag API](https://platform.claude.com/docs/en/manage-claude/claude-tag-api): read Claude Tag’s settings on Slack channels and Slack workspaces; list Access bundles and where they are attached (no other scope grants read access to the Claude Tag API) | `read:claude_tag` |
81| [Claude Tag API](https://platform.claude.com/docs/en/manage-claude/claude-tag-api): set up and remove channels; change settings; attach and detach Access bundles (to read as well, also select `read:claude_tag`) | `write:claude_tag` |
82| [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` |
83| [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` |
84| [Claude Enterprise Analytics API](https://platform.claude.com/docs/en/manage-claude/analytics-api): engagement, adoption, cost, and usage reports; [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api): token usage and cost reports | `read:analytics` |
85| [Compliance API Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed): organization-wide activity events | `read:compliance_activities` |
86| [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, session transcripts, and [organization users](https://platform.claude.com/docs/en/manage-claude/compliance-org-data#list-organization-users); together with `read:compliance_org_data`, also who made a [Security posture attestation](https://platform.claude.com/docs/en/manage-claude/compliance-security-posture/results-reference#who-attested-and-comments), where the endpoint returns it: a user ID | `read:compliance_user_data` |
87| [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` |
88| [Compliance API organization endpoints](https://platform.claude.com/docs/en/manage-claude/compliance-org-data): read organization metadata and effective settings, and an organization’s [Security posture](https://platform.claude.com/docs/en/manage-claude/compliance-security-posture/results-reference); [Plugins API](https://platform.claude.com/docs/en/manage-claude/plugins-api): every `GET` endpoint, including file downloads | `read:compliance_org_data` |
89| Admin API [user management](https://platform.claude.com/docs/en/manage-claude/user-management) read endpoints, every Compliance API read endpoint, and every [Plugins API](https://platform.claude.com/docs/en/manage-claude/plugins-api) `GET` endpoint, including file downloads, with a single read-only scope (for security-audit integrations; does not include the Spend Limits or Analytics APIs) | `read:org_audit` |
239If a key lacks a scope that an endpoint needs, the call fails with `403 Forbidden`. The error message names the scopes the endpoint accepts.
90240 
91Compliance API scopes need the [Compliance API enabled](https://platform.claude.com/docs/en/manage-claude/compliance-api-access#set-up-the-compliance-api) before you can create a key with them. The `read:analytics` scope needs [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).
241## Replace an Admin API key
92242 
93The `read:plugins` and `write:plugins` scopes need an organization that can use the [Plugins API](https://platform.claude.com/docs/en/manage-claude/plugins-api), and they act only on the organization you created the key in. Keys with `read:org_audit` or `read:compliance_org_data` can read the Plugins API only in organizations that can use it. See [Plugins API scopes](https://platform.claude.com/docs/en/manage-claude/plugins-api#scopes). To read another organization’s plugins, see [Reading another organization under the same parent](https://platform.claude.com/docs/en/manage-claude/plugins-api#reading-another-organization-under-the-same-parent).
243An Enterprise Admin API key doesn’t expire. To replace a key of either kind, follow these steps:
94244 
95## Use the key
2451. **Create a new key.** Follow this page’s steps for your kind of organization.
96246 
97Pass the key in the `x-api-key` header on every request. See each API’s documentation for complete request examples.
2472. **Switch your program to the new key.** Check that its calls succeed.
98248 
99A call to an endpoint outside the key’s scopes returns `403 Forbidden`. The error message names the scopes the endpoint accepts.
2493. **Delete the old key.** Where you delete it depends on its kind:
100250 
101Neither a Claude Console key nor a Claude Enterprise key works with the Admin API’s service-account, federation-issuer, or federation-rule endpoints. Those endpoints accept only an OAuth bearer token with the `org:admin` scope. See [OAuth bearer token](https://platform.claude.com/docs/en/manage-claude/admin-api#oauth-bearer-token).
102 
103## Next steps
104 
105<CardGroup cols={2}>
106 <Card title="Admin API" href="https://platform.claude.com/docs/en/manage-claude/admin-api">
107 Manage organization members, workspaces, and API keys.
108 </Card>
109 
110 <Card title="Spend Limits API" href="https://platform.claude.com/docs/en/manage-claude/spend-limits-api">
111 Set per-member spend limits and review increase requests for your Claude Enterprise organization.
112 </Card>
113 
114 <Card title="Analytics APIs" href="https://platform.claude.com/docs/en/manage-claude/analytics-api">
115 Report on Claude Code productivity or Claude Enterprise engagement and adoption.
116 </Card>
117 
118 <Card title="Compliance API" href="https://platform.claude.com/docs/en/manage-claude/compliance-api">
119 Audit activity and retrieve or delete user content across your organization.
120 </Card>
121</CardGroup>
251 * **Console Admin API key:** Delete it on the [Admin keys](https://platform.claude.com/settings/admin-keys) page in the Claude Console.
252 * **Enterprise Admin API key:** Delete it in your organization’s [API settings](https://claude.ai/admin-settings/api-access) in claude.ai, at **Organization settings** > **API**.
122253 

manage-claude/administering-claude New page · 71 lines, new page

## Which organization you have ## In a Claude Console organization ## In a Claude Enterprise organization ## Manage your organization from code

A whole new page. There's nothing to diff it against, so here is what it says.

---
title: Administering Claude
url: https://platform.claude.com/docs/en/manage-claude/administering-claude
description: Find out which kind of Claude organization you have, how its parts fit together, and where to start managing it.
---

The admin pages are for people who manage Claude for a company or team. A Claude Console organization is for building with the Claude API, and a Claude Enterprise organization is for using Claude apps such as claude.ai. The pages cover who can use your organization, what each member can do, what the organization spends, and what happens to its data. This page shows how an organization is arranged and where to start. To write code that calls Claude instead, see [Get started with Claude](https://platform.claude.com/docs/en/get-started).

## Which organization you have

Which pages apply to you depends on which kind of organization you have:

* **Claude Console organization:** You manage it in the [Claude Console](https://platform.claude.com/settings/organization).
* **Claude Enterprise organization:** You manage it from [Organization settings](https://claude.ai/admin-settings) in claude.ai.

A company with Claude Enterprise normally also has a **parent organization**. It holds linked organizations, which can be Claude Console or Claude Enterprise organizations. Single sign-on is set up on the parent for all of them. Some features, such as the Compliance API, are turned on once for the parent and apply to every linked organization. A Claude Console organization can also stand alone, with no parent.

![With Claude Enterprise, a parent organization holds linked organizations. A Claude Console organization holds workspaces.](https://platform.claude.com/docs/images/admin-organization-structure.svg)

On a cloud platform, your cloud account’s access controls, such as identity and access management (IAM), determine who can use Claude. See your platform’s page, listed under [Claude API versus cloud platforms](https://platform.claude.com/docs/en/api/overview#claude-api-vs-cloud-platforms) on the API overview page.

## In a Claude Console organization

* **Members and roles:** Each member has one organization role, such as admin or developer, and a role in each workspace they can use. See the Admin API page’s [Organization roles and permissions](https://platform.claude.com/docs/en/manage-claude/admin-api#organization-roles-and-permissions) section and [Workspace roles and permissions](https://platform.claude.com/docs/en/manage-claude/workspaces#workspace-roles-and-permissions).
* **Workspaces:** Every organization has a default workspace. You can add more, such as one for each team or environment. A workspace you add can have its own members and its own spend and rate limits. Each request to Claude runs in one workspace, and the files and batches the request creates stay there.
* **Keys:** [Developer API keys](https://platform.claude.com/docs/en/manage-claude/api-keys) call Claude in one workspace or several. Console Admin API keys manage the whole organization, and only admins create them. See [Admin API keys and tokens](https://platform.claude.com/docs/en/manage-claude/admin-api-keys).
* **Service accounts:** A service account is an identity for a program instead of a person. Code that uses Workload Identity Federation or a service account key acts as a service account. See the Workload Identity Federation page’s [Service accounts](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#service-accounts) section.
* **Usage and cost:** The Claude Console’s [Usage page](https://platform.claude.com/usage) and [Cost page](https://platform.claude.com/cost) show what the organization uses and spends.
* **Compliance:** A Console Admin API key created after the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api) is turned on can read activity records through it. See [Query the Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed).
* **Data:** [Data residency](https://platform.claude.com/docs/en/manage-claude/data-residency) sets where inference runs and where data is stored. See [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention) for how long Anthropic keeps data, including zero data retention.

To set up a Claude Console organization by hand, start with [Workspaces](https://platform.claude.com/docs/en/manage-claude/workspaces). To choose how your code calls Claude, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).

## In a Claude Enterprise organization

* **Members and roles:** Each member has one Claude Enterprise organization role, such as primary owner, organization owner, or user. Groups, which connect members to custom roles, belong to the parent organization. See the User management page’s [Organization roles](https://platform.claude.com/docs/en/manage-claude/user-management#organization-roles) and [Groups and roles](https://platform.claude.com/docs/en/manage-claude/user-management#groups-and-roles) sections.
* **Usage:** The [Analytics dashboard](https://claude.ai/analytics) in claude.ai shows how people use Claude.
* **Compliance:** The [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api) reads records for audits.
* **Keys:** An Enterprise Admin API key manages the organization through the APIs its scopes cover. See [Create a key for a Claude Enterprise organization](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#create-a-key-for-a-claude-enterprise-organization).

To set up a Claude Enterprise organization, start in its [Organization settings](https://claude.ai/admin-settings) in claude.ai.

## Manage your organization from code

First, get a credential, and then use the API for the job:

<CardGroup cols={2}>
  <Card title="Admin API keys and tokens" icon="key" href="https://platform.claude.com/docs/en/manage-claude/admin-api-keys">
    Get the credential a program uses to manage either kind of organization.
  </Card>

  <Card title="Usage and Cost Analytics API" icon="chart" href="https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api">
    Report token usage and cost for either kind of organization.
  </Card>

  <Card title="Admin API" icon="settings" href="https://platform.claude.com/docs/en/manage-claude/admin-api">
    Manage a Claude Console organization’s members, workspaces, and Developer API keys.
  </Card>

  <Card title="User management" icon="building" href="https://platform.claude.com/docs/en/manage-claude/user-management">
    Manage a Claude Enterprise organization’s members and groups with the Admin API.
  </Card>

  <Card title="Analytics APIs" icon="gauge" href="https://platform.claude.com/docs/en/manage-claude/analytics-api">
    Report either Claude Code use or how people use Claude in Claude Enterprise.
  </Card>

  <Card title="Compliance API" icon="shield" href="https://platform.claude.com/docs/en/manage-claude/compliance-api">
    Read activity records. In Claude Enterprise, also read chats and files.
  </Card>
</CardGroup>

manage-claude/analytics-api Changed · +24 / -15 lines

### Cowork connector calls in cloud sessions

from line 6
66 
77Anthropic provides two product analytics APIs, and which one you use depends on which Claude product your organization manages:
88 
9* 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.
9* 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 a Console Admin API key.
1010* 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.
1111 
1212The 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.
from line 15
1515 
1616| API | Key type | Created in | Who can create it | What it covers |
1717| ----- | ----- | ----- | ----- | ----- |
18| **Claude Code Analytics API** | Admin API key | [Admin keys](https://platform.claude.com/settings/admin-keys) page in the Claude Console | Organization admin | Daily Claude Code metrics for each user: sessions, lines of code, commits, pull requests, tool acceptance, and estimated cost by model |
19| **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 |
18| **Claude Code Analytics API** | Console Admin API key | [Admin keys](https://platform.claude.com/settings/admin-keys) page in the Claude Console | Organization admin | Daily Claude Code metrics for each user: sessions, lines of code, commits, pull requests, tool acceptance, and estimated cost by model |
19| **Claude Enterprise Analytics API** | Analytics API key | [API settings](https://claude.ai/admin-settings/api-access) page in claude.ai (**Organization settings** > **API**) | Primary owner | Organization-wide engagement and adoption (user activity, active-user summaries, project, skill, and connector usage), plus cost and usage reports |
2020 
2121The two key types differ in what they can call:
2222 
23* An **Admin API key** (`sk-ant-admin01-...`) cannot call the Claude Enterprise Analytics API.
24* An **Analytics API key** is a key created in claude.ai with the `read:analytics` scope. Besides the Claude Enterprise Analytics API, it works with the [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api). To call Admin API endpoints such as members and invites, a key created in claude.ai needs other scopes (see [Choose scopes for a Claude Enterprise key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#choose-scopes-for-a-claude-enterprise-key)).
23* A **Console Admin API key** (`sk-ant-admin01-...`) cannot call the Claude Enterprise Analytics API.
24* An **Analytics API key** is an Enterprise Admin API key, created in claude.ai, with the `read:analytics` scope. Besides the Claude Enterprise Analytics API, it works with the [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api). To call Admin API endpoints, such as those for members and invites, an Enterprise Admin API key needs other scopes. See the [Enterprise Admin API key scopes](https://platform.claude.com/docs/en/manage-claude/enterprise-admin-api-key-scopes) page.
2525 
2626The Claude Code Analytics API and the Claude Enterprise Analytics API both appear under the [Admin API reference](https://platform.claude.com/docs/en/api/beta/organization), but they are separate APIs. If your organization uses both the Claude Platform and Claude Enterprise, you can provision both keys and use each API for its own data.
2727 
from line 29
2929 Looking for token usage and cost data rather than product analytics? See the [Usage and Cost Analytics API](https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api), which serves both Claude Console and Claude Enterprise organizations.
3030</Note>
3131 
32<Note>
33 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).
34</Note>
32If 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).
3533 
3634## Get access to the Claude Code Analytics API
3735 
from line 36
3836The Claude Code Analytics API is free for Claude Console organizations on the Claude API. Your organization needs [access to the Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api#availability), and an organization admin creates the key.
3937 
4038<Steps>
41 <Step title="Create an Admin API key">
42 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).
39 <Step title="Create a Console Admin API key">
40 Follow the steps in [Create a key for a Claude Console organization](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#create-a-key-for-a-claude-console-organization) on the Admin API keys and tokens page.
4341 </Step>
4442 
4543 <Step title="Call the API">
from line 59
6159 
6260<Steps>
6361 <Step title="Sign in as the primary owner">
64 Only the primary owner of the organization can enable API access and create Analytics API keys.
62 Only the primary owner of the organization can turn on the Analytics API and create Analytics API keys.
6563 </Step>
6664 
67 <Step title="Enable API access and create a key">
68 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.
65 <Step title="Turn on the Analytics API and create a key">
66 Go to the [API settings](https://claude.ai/admin-settings/api-access) page in claude.ai (**Organization settings** > **API**) and turn on the **Analytics API** toggle. Then, in the **Keys** section, click **Create key**, name the key, select the `read:analytics` scope, and click **Create**. Copy the displayed secret and store it in your secrets manager.
6967 </Step>
7068 
7169 <Step title="Call the API">
72 Pass the key in the `x-api-key` header and include the [`anthropic-version`](https://platform.claude.com/docs/en/api/versioning) header on every request. 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/beta/organization/analytics).
70 In a cURL request, pass the key in the `x-api-key` header and include the `anthropic-version` header ([API versions](https://platform.claude.com/docs/en/api/versioning)). 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/beta/organization/analytics).
7371 </Step>
7472</Steps>
7573 
from line 149
151149 
152150For other analytics changes with customer-managed encryption keys, see [What CMEK covers on Claude Enterprise](https://platform.claude.com/docs/en/manage-claude/cmek-coverage-claude-enterprise#turned-off-or-changed).
153151 
152### Cowork connector calls in cloud sessions
153 
154Some Cowork sessions run in the cloud in Anthropic-managed environments instead of on the user’s machine. `connectors_used_count` in [user activity](https://platform.claude.com/docs/en/api/beta/organization/analytics/users/list) counts the successful connector calls made in those cloud sessions. For dates before November 9, 2026, it leaves out most of them. This applies to `connectors_used_count` in both `cowork_metrics` and `chat_cowork_unified_metrics.sessions`.
155 
156Earlier dates are not restated. If your organization runs Cowork sessions in the cloud, these counts rise on November 9, 2026, with no change in use. As a result, do not compare totals from before and after that date. The count for the most recent available day can also be low until the next day’s data arrives.
157 
158The following numbers leave out most connector use in cloud sessions for all dates:
159 
160* **Distinct connectors:** In user activity, this applies to `distinct_connectors_used_count` in the same two objects. A user can have connector calls and zero distinct connectors on the same day.
161* **Connector usage:** In [connector usage](https://platform.claude.com/docs/en/api/beta/organization/analytics/connectors/list), this applies to the Cowork numbers for each connector, such as `cowork_metrics.distinct_session_connector_used_count`. They can be lower than the call counts in user activity suggest.
162 
154163## Next steps
155164 
156165<CardGroup cols={2}>
157166 <Card title="Claude Code Analytics API" href="https://platform.claude.com/docs/en/manage-claude/claude-code-analytics-api">
158 Track Claude Code sessions, code changes, and tool usage with an Admin API key.
167 Track Claude Code sessions, code changes, and tool usage with a Console Admin API key.
159168 </Card>
160169 
161170 <Card title="Usage and Cost Analytics API" href="https://platform.claude.com/docs/en/manage-claude/usage-cost-analytics-api">

manage-claude/api-keys New page · 430 lines, new page

## Key types ### Scope ## Key expiration ## Who can create which key ## Create and use a key ### Run the docs’ samples with a key ## Select a workspace ## Keep a key safe ## Replace a workspace key ## Manage keys with the Admin API ## Special cases ### If you use Claude Platform on AWS

A whole new page. There's nothing to diff it against, so here is what it says.

---
title: Developer API keys
url: https://platform.claude.com/docs/en/manage-claude/api-keys
description: Compare the types of Developer API key, use a key, select a workspace, and manage expiration.
---

A Developer API key is a secret that you create in the Claude Console and send with each request. Keys suit tools that need one and servers where no [identity provider](https://platform.claude.com/docs/en/manage-claude/authentication#workload-identity-federation) is available.

**Is this the key you need?** A Developer API key calls Claude, and an [Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) manages an organization. To compare them, see the [two kinds of API key](https://platform.claude.com/docs/en/manage-claude/authentication#api-keys).

**You might not need a key.** To choose a method that doesn’t use one, see [Choose your path](https://platform.claude.com/docs/en/manage-claude/authentication#choose-your-path) on the Authentication page.

## Key types

When you create a key, the **Linked account** setting determines its type. Choose yourself for a personal key or a service account for a service account key. **Not linked** makes a legacy workspace key.

If a tool that only you run asks for a key, use a personal key. If a shared or unattended workload has to use a key, give it a service account key, which doesn’t stop working when one person leaves.

The type determines who the key acts as, where it works, and when it stops working:

* **Personal key:** It acts as you, with your roles. It works in one workspace or in the workspaces where your role allows API use (see [Workspace roles and permissions](https://platform.claude.com/docs/en/manage-claude/workspaces#workspace-roles-and-permissions) on the Workspaces page). It stops working when you leave the organization or are removed from it.
* **Service account key:** It acts as a [service account](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#service-accounts). It works in one workspace or in the workspaces where the service account’s role allows API use. It stops working when the service account is archived.
* **Workspace key (legacy):** It acts as no one. It works in the workspace it was created in. It stops working when that workspace is archived.

Personal keys and service account keys are tied to an identity, so they don’t outlive the people or service accounts that own them.

Workspace keys are legacy, so use a personal or service account key for new integrations. To move off a workspace key, see [Replace a workspace key](https://platform.claude.com/docs/en/manage-claude/api-keys#replacing-workspace-api-keys).

### Scope

A personal or service account key is scoped to one workspace or to the organization:

* **Scoped to one workspace:** The key works only in that workspace. It also stops working when its owner loses access to the workspace or when the workspace is archived.
* **Scoped to the organization:** The key works in several workspaces, so each Claude API request names one (see [Select a workspace](https://platform.claude.com/docs/en/manage-claude/api-keys#select-a-workspace)).

## Key expiration

You choose a key’s expiration when you create it on the [API keys](https://platform.claude.com/settings/keys) page (`platform.claude.com/settings/keys`) in the Claude Console, and you can’t change the expiration afterward. The choices are:

* A preset: 3 hours, 1 day, 7 days, or 30 days
* A custom date and time
* **Never**, for keys you keep in a secrets manager and rotate yourself

If your organization has a maximum expiration policy, the Console limits presets and custom dates to that maximum and doesn’t offer **Never**.

If the key lasts at least 3 days, Anthropic emails the key’s creator before it expires.

After a key expires, requests made with it return a 401 `authentication_error`. An expired key can only be deleted, not turned back on, so create a new key to restore access.

The API keys table in the Console shows each key’s expiration. The [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api) reports each key’s `expires_at` on [List API Keys](https://platform.claude.com/docs/en/api/organization/api_keys/list) and [Retrieve API Key](https://platform.claude.com/docs/en/api/organization/api_keys/retrieve), so you can rotate keys before they expire.

## Who can create which key

| Key | Who can create it |
| ----- | ----- |
| Personal key, scoped to one workspace | Workspace Developer, Workspace Limited Developer, or Workspace Admin in that workspace. Organization developers who are members of that workspace can too. Organization admins have the Workspace Admin role in every workspace. |
| Personal key, scoped to the organization | Organization developers and admins |
| Service account key | Organization admins |
| Workspace key (legacy) | Workspace Developer, Workspace Limited Developer, or Workspace Admin in that workspace. Organization admins have the Workspace Admin role in every workspace. |

The default workspace has no member list, so organization developers and admins can create personal and workspace keys there.

For what each role allows, see [Organization roles and permissions](https://platform.claude.com/docs/en/manage-claude/admin-api#organization-roles-and-permissions) on the Admin API page and [Workspace roles and permissions](https://platform.claude.com/docs/en/manage-claude/workspaces#workspace-roles-and-permissions) on the Workspaces page.

An organization admin can turn off key creation on the [Security](https://platform.claude.com/settings/identity) page in the Claude Console. **Allow creating new API keys** controls the whole organization. **Allow creating new API keys in default workspace** controls only keys scoped to the default workspace.

If you can’t create the key you need, what to do depends on why:

* **You have the organization user role:** Use a workspace where you’re a Workspace Developer, Workspace Limited Developer, or Workspace Admin. On the [API keys](https://platform.claude.com/settings/keys) page, click **Create key**. If the dialog first offers other ways to connect, click **Somewhere else** or **Continue with an API key**. Then, set **Scope** to that workspace.
* **Create key is missing or disabled, or the Console says you don’t have permission:** Ask an organization admin. They can change your role, change the key creation settings, or create a service account key for your workload.

## Create and use a key

To create a key step by step, see [Get your Claude API key](https://platform.claude.com/docs/en/get-api-key).

The SDK and the CLI read a key from the `ANTHROPIC_API_KEY` environment variable. A direct HTTP request sends the key in the `Authorization` header after `Bearer`. It can send it in the legacy `x-api-key` header instead. Send only one. With `Authorization`, a request looks like this:

```http
POST /v1/messages
Authorization: Bearer YOUR_API_KEY
anthropic-version: 2026-10-21
content-type: application/json
```

Keep keys out of source control, client-side code, and prompts. To set `ANTHROPIC_API_KEY` in your shell, including on Windows, see [API key](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#api-key) on the CLI authentication options page.

The following samples show how each tool takes the key:

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Hello, Claude"}]
    }'
  ```

  ```bash CLI
  export ANTHROPIC_API_KEY=sk-ant-...
  ```

  ```python Python
  client = Anthropic()  # reads ANTHROPIC_API_KEY
  # Or pass a key that you load from a secrets manager:
  # client = Anthropic(api_key=key_from_your_secrets_manager)
  ```

  ```typescript TypeScript
  const client = new Anthropic(); // reads ANTHROPIC_API_KEY
  // Or pass a key that you load from a secrets manager:
  // const client = new Anthropic({ apiKey: keyFromYourSecretsManager });
  ```

  ```csharp C#
  AnthropicClient client = new(); // reads ANTHROPIC_API_KEY
  // Or pass a key that you load from a secrets manager:
  // AnthropicClient client = new() { ApiKey = keyFromYourSecretsManager };
  ```

  ```go Go
  client := anthropic.NewClient() // reads ANTHROPIC_API_KEY
  // Or pass a key that you load from a secrets manager
  // (import github.com/anthropics/anthropic-sdk-go/v2/option):
  // client := anthropic.NewClient(option.WithAPIKey(keyFromYourSecretsManager))
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv(); // reads ANTHROPIC_API_KEY
  // Or pass a key that you load from a secrets manager:
  // AnthropicClient client = AnthropicOkHttpClient.builder()
  //     .apiKey(keyFromYourSecretsManager)
  //     .build();
  ```

  ```php PHP
  $client = new Client(); // reads ANTHROPIC_API_KEY
  // Or pass a key that you load from a secrets manager:
  // $client = new Client(apiKey: $keyFromYourSecretsManager);
  ```

  ```ruby Ruby
  client = Anthropic::Client.new # reads ANTHROPIC_API_KEY
  # Or pass a key that you load from a secrets manager:
  # client = Anthropic::Client.new(api_key: key_from_your_secrets_manager)
  ```
</CodeGroup>

### Run the docs’ samples with a key

First, set `ANTHROPIC_API_KEY` to your key. If the key is scoped to the organization, every Claude API sample must also name a workspace (see [Select a workspace](https://platform.claude.com/docs/en/manage-claude/api-keys#select-a-workspace)). Anything else you change depends on the sample:

* **SDK and CLI samples, and cURL samples that send `x-api-key`:** Nothing else. They read `ANTHROPIC_API_KEY`.
* **cURL samples that use CLI sign-in:** These send `Authorization: Bearer $(ant auth print-credentials --access-token)`. Change it to `Authorization: Bearer $ANTHROPIC_API_KEY`.

## Select a workspace

Whether a request names a workspace depends on the key’s scope:

* **Scoped to one workspace:** Requests can leave out the `anthropic-workspace-id` header. If you send the header, it must name the key’s own workspace.
* **Scoped to the organization:** Each Claude API request must name a workspace in the `anthropic-workspace-id` header. Leave the header out of Admin API requests, which refuse it.

To find a workspace’s ID, use either of these:

* The **ID** column on the [Workspaces](https://platform.claude.com/settings/workspaces) page in the Claude Console. The page lists the default workspace too.
* [List Workspaces](https://platform.claude.com/docs/en/api/organization/workspaces/list) in the Admin API. It includes the default workspace only when you pass `include_default=true`.

The following samples set the header on one request. With the SDK, you can also set it once for every request from a client:

<CodeGroup>
  ```bash cURL
  # Required on every Claude API request for a key scoped to the organization.
  # Omit the anthropic-workspace-id header for a key scoped to one workspace.
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "anthropic-workspace-id: wrkspc_01AbCdEfGhJkLmNpQrStUvWx" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "messages": [{"role": "user", "content": "Hello, Claude"}]
    }'
  ```

  ```bash CLI
  # Required on every Claude API request for a key scoped to the organization.
  # Omit --workspace-id for a key scoped to one workspace.
  ant messages create \
    --workspace-id wrkspc_01AbCdEfGhJkLmNpQrStUvWx \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --message '{role: user, content: "Hello, Claude"}'
  ```

  ```python Python
  client = Anthropic()  # reads ANTHROPIC_API_KEY

  # Required on every Claude API request for a key scoped to the organization.
  # Omit extra_headers for a key scoped to one workspace.
  message = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      messages=[{"role": "user", "content": "Hello, Claude"}],
      extra_headers={"anthropic-workspace-id": "wrkspc_01AbCdEfGhJkLmNpQrStUvWx"},
  )
  print(message.content)

  # Or set it once for every request from this client:
  workspace_client = Anthropic(
      default_headers={"anthropic-workspace-id": "wrkspc_01AbCdEfGhJkLmNpQrStUvWx"},
  )
  ```

  ```typescript TypeScript
  const client = new Anthropic(); // reads ANTHROPIC_API_KEY

  // Required on every Claude API request for a key scoped to the organization.
  // Omit the second argument for a key scoped to one workspace.
  const message = await client.messages.create(
    {
      model: "claude-opus-5-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: "Hello, Claude" }]
    },
    { headers: { "anthropic-workspace-id": "wrkspc_01AbCdEfGhJkLmNpQrStUvWx" } }
  );
  console.log(message.content);

  // Or set it once for every request from this client:
  const workspaceClient = new Anthropic({
    defaultHeaders: { "anthropic-workspace-id": "wrkspc_01AbCdEfGhJkLmNpQrStUvWx" }
  });
  ```

  ```csharp C#
  AnthropicClient client = new(); // reads ANTHROPIC_API_KEY

  MessageCreateParams parameters = new()
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Messages = [new UserMessageParam { Content = "Hello, Claude" }],
  };

  // Required on every Claude API request for a key scoped to the organization.
  // Call client.Messages.Create(parameters) directly for a key scoped to one workspace.
  var message = await client
      .WithOptions(options =>
          options with
          {
              ExtraHeaders = new Dictionary<string, string>
              {
                  ["anthropic-workspace-id"] = "wrkspc_01AbCdEfGhJkLmNpQrStUvWx",
              },
          }
      )
      .Messages.Create(parameters);
  Console.WriteLine(message);

  // Or set it once for every request from this client:
  AnthropicClient workspaceClient = new(new ClientOptions
  {
      ExtraHeaders = new Dictionary<string, string>
      {
          ["anthropic-workspace-id"] = "wrkspc_01AbCdEfGhJkLmNpQrStUvWx",
      },
  });
  ```

  ```go Go
  client := anthropic.NewClient() // reads ANTHROPIC_API_KEY

  // Required on every Claude API request for a key scoped to the organization.
  // Omit the option for a key scoped to one workspace.
  message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
  	},
  }, option.WithHeader("anthropic-workspace-id", "wrkspc_01AbCdEfGhJkLmNpQrStUvWx"))
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(message.Content)

  // Or set it once for every request from this client:
  workspaceClient := anthropic.NewClient(
  	option.WithHeader("anthropic-workspace-id", "wrkspc_01AbCdEfGhJkLmNpQrStUvWx"),
  )
  ```

  ```java Java
  AnthropicClient client = AnthropicOkHttpClient.fromEnv(); // reads ANTHROPIC_API_KEY

  // Required on every Claude API request for a key scoped to the organization.

Cut at 300 lines. The page has the rest.

manage-claude/authentication Changed · +151 / -368 lines

## Choose your path ## Sign in with the CLI ## Which credential is used ## Browser-based applications ### Requests sent from a browser ### Key types ### Create and use a key ### Select a workspace ### Key expiration ### Replacing workspace API keys ### Browser-based applications ## Next steps

The two sides of this change are more than 400 edits apart, too far apart to line up, so this is the differ's own diff of it and the words inside a line are not marked.

from line 1
11---
22title: Authentication
33url: https://platform.claude.com/docs/en/manage-claude/authentication
4description: "Choose how your code proves who it is to the Claude API: CLI sign-in, Workload Identity Federation, App Attest, or an API key."
4description: "Choose how your code authenticates to call Claude: CLI sign-in, Workload Identity Federation, App Attest, or a Developer API key."
55---
66 
7Every request to the Claude API carries a credential that tells the API who is calling, such as you or a service account that gives a program its own identity. Choose the method by where your code runs. Every method but an API key sends a short-lived token instead of a long-lived secret, which limits the damage if a token leaks.
7Every request to the Claude API carries a credential, which tells the API who is calling, such as you or a service account in your organization. This page helps you choose the credential your code uses to call Claude, for example to send a message. The methods on this page are for accounts and organizations in the Claude Console (`platform.claude.com`).
88 
9| Method | Credential | Best for |
10| ----- | ----- | ----- |
11| CLI sign-in (see the `ant` CLI’s [Interactive login](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#interactive-login) section) | Short-lived access token that `ant auth login` stores on your computer | Local development and scripting on your own computer |
12| [Workload Identity Federation (WIF)](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, and Azure), CI/CD pipelines, and Kubernetes, where you want to eliminate static secrets |
13| [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 |
14| [API key](https://platform.claude.com/docs/en/manage-claude/authentication#api-keys) | Static `sk-ant-api...` secret sent as a bearer token in the `Authorization` header | A server with no identity provider or a tool that asks for a key |
9To manage an organization instead, such as inviting members or reading usage, see [Admin API keys and tokens](https://platform.claude.com/docs/en/manage-claude/admin-api-keys).
1510 
16On your own computer, sign in with the `ant` CLI. The SDK and the CLI then find your credentials on their own as long as `ANTHROPIC_API_KEY` isn’t set. Use Workload Identity Federation in CI or on a server or cluster with an identity provider. Use App Attest for iOS and macOS apps you distribute to end users. Choose an API key for a server with no identity provider or a tool that asks for a key. Pick a personal key for your own use or a service account key for anything shared.
11## Choose your path
12 
13Choose by where your code runs:
14 
15<CardGroup cols={2}>
16 <Card title="CLI sign-in" image="https://platform.claude.com/docs/images/authentication/cli-sign-in.svg" imageHeight={32} href="https://platform.claude.com/docs/en/manage-claude/authentication#sign-in-with-the-cli">
17 On your own computer, as you work
18 
19 Scoped to one workspace, as you
20 </Card>
21 
22 <Card title="Workload Identity Federation" image="https://platform.claude.com/docs/images/authentication/workload-identity-federation.svg" imageHeight={32} href="https://platform.claude.com/docs/en/manage-claude/workload-identity-federation">
23 In CI or on a server or cluster with an identity provider
24 
25 Scoped to one workspace, as a service account
26 </Card>
27 
28 <Card title="App Attest" image="https://platform.claude.com/docs/images/authentication/app-attest.svg" imageHeight={32} href="https://platform.claude.com/docs/en/manage-claude/app-attest">
29 In an iOS or macOS app
30 
31 Reaches Messages and token counting in one workspace
32 </Card>
33 
34 <Card title="Developer API key" image="https://platform.claude.com/docs/images/authentication/developer-api-key.svg" imageHeight={32} href="https://platform.claude.com/docs/en/manage-claude/api-keys">
35 On a server with no identity provider or in a tool that asks for a key
36 
37 Reaches one workspace or several
38 </Card>
39</CardGroup>
40 
41CLI sign-in, Workload Identity Federation, and App Attest give your code a short-lived access token for one workspace in your organization (see [Workspaces](https://platform.claude.com/docs/en/manage-claude/workspaces)). There’s no key to create, copy, or rotate.
42 
43With Workload Identity Federation, your code acts as a service account: a named identity in your organization that isn’t a person. For more, see [Service accounts](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#service-accounts) on the Workload Identity Federation page.
44 
45For a web app, see [Browser-based applications](https://platform.claude.com/docs/en/manage-claude/authentication#browser-based-applications) on this page.
46 
47On a cloud platform, use that platform’s credentials:
48 
49* [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws)
50* [Claude Models on Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-models-on-google-cloud/overview)
51* [Claude in Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry)
52* [Claude in Amazon Bedrock (`bedrock-mantle`)](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock), for the Messages API at `/anthropic/v1/messages`
53* [Claude on Amazon Bedrock (`bedrock-runtime`)](https://platform.claude.com/docs/en/build-with-claude/claude-on-amazon-bedrock-legacy), for the `InvokeModel` and `Converse` APIs and for SDK clients such as `AnthropicBedrock`
54 
55## Sign in with the CLI
56 
57On your own computer, you can sign in with the `ant` CLI instead of creating a key.
58 
59<Steps>
60 <Step title="Install the CLI">
61 <Tabs noDeepLinks>
62 <Tab title="Homebrew (macOS)">
63 ```bash
64 brew install anthropics/tap/ant
65 ```
66 </Tab>
67 
68 <Tab title="curl (Linux/WSL)">
69 For Linux environments, download the release binary directly.
70 
71 ```bash
72 VERSION=2.14.0
73 OS=$(uname -s | tr '[:upper:]' '[:lower:]')
74 case $(uname -m) in
75 x86_64) ARCH=amd64 ;;
76 aarch64) ARCH=arm64 ;;
77 esac
78 curl -fsSL "https://github.com/anthropics/anthropic-cli/releases/download/v${VERSION}/ant_${VERSION}_${OS}_${ARCH}.tar.gz" \
79 | sudo tar -xz -C /usr/local/bin ant
80 ```
81 
82 You can find all releases on the [GitHub releases page](https://github.com/anthropics/anthropic-cli/releases).
83 </Tab>
84 
85 <Tab title="go install">
86 You can also install the CLI from source with `go install`, which requires Go 1.26.10 or later.
87 
88 ```bash
89 go install github.com/anthropics/anthropic-cli/v2/cmd/ant@latest
90 ```
91 
92 `go install` places the binary in `$(go env GOPATH)/bin`. Add that directory to your `PATH` if it isn’t already there:
93 
94 ```bash
95 export PATH="$PATH:$(go env GOPATH)/bin"
96 ```
97 </Tab>
98 </Tabs>
99 
100 On Windows, you can install the CLI inside [Windows Subsystem for Linux (WSL)](https://learn.microsoft.com/windows/wsl/install) with the Linux steps. If you sign in with the CLI inside WSL, also run your code there so that it finds your sign-in.
101 </Step>
102 
103 <Step title="Sign in">
104 ```bash CLI
105 ant auth login
106 ```
107 
108 Your browser opens. The first time you sign in, select an organization if you belong to more than one, and then a workspace.
109 </Step>
110</Steps>
111 
112The CLI then stores an access token on your computer for the workspace you selected. How your code sends the token depends on the tool:
113 
114* **SDK and CLI:** They find the token on their own. A client created with no arguments uses it (in Java, with `fromEnv()`).
115* **cURL:** Add `-H "Authorization: Bearer $(ant auth print-credentials --access-token)"` to each request. Each time it runs, `ant auth print-credentials` renews the token first if it has expired or is about to. For an example, see [Authenticate curl requests with CLI credentials](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/scripting#authenticate-curl-requests-with-cli-credentials) on the CLI scripting and automation page.
116 
117If `ant auth print-credentials` warns that it couldn’t renew the token, run `ant auth login` again.
118 
119If another credential is also set, see [Which credential is used](https://platform.claude.com/docs/en/manage-claude/authentication#which-credential-is-used).
120 
121To switch workspaces or organizations, see [CLI authentication options](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication). That page also covers signing in on a computer with no browser.
122 
123## Workload Identity Federation
124 
125Workload Identity Federation (WIF) lets code in CI, on a server, or in a cluster call the API without a stored secret. WIF needs an identity provider: a service that gives your workload a signed token saying what it is. GitHub Actions, AWS, Google Cloud, and Kubernetes all do this, and many platforms call these tokens OIDC tokens. For how WIF uses these tokens, see the [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) page.
126 
127If your host gives your code no such token, use a [Developer API key](https://platform.claude.com/docs/en/manage-claude/api-keys).
128 
129An organization admin sets up WIF in the Claude Console. To set it up, follow the guide for your identity provider, such as [Use WIF with GitHub Actions](https://platform.claude.com/docs/en/manage-claude/wif-providers/github-actions). For the other providers, see [Identity providers](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#identity-providers). For what each part of the setup does, see [Set up federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#set-up-federation).
130 
131## App Attest
132 
133App Attest lets an iOS or macOS app call Claude straight from the device, with no key inside the app.
134 
135To register your app and learn how App Attest works, see [App Attest for iOS and macOS apps](https://platform.claude.com/docs/en/manage-claude/app-attest).
17136 
18137## API keys
19138 
20API keys are static secrets that you generate in the Claude Console and send on every request as a bearer token in the `Authorization` header.
139An API key is a secret that you create and send with each request.
21140 
22### Key types
141There are two kinds of API key, each named for its main job:
23142 
24When you create a key, you choose its type, which determines what the key can do, where it works, and when it stops working:
143| Key | What it works with |
144| ----- | ----- |
145| **Developer API key** | The APIs that call Claude, such as Messages, Files, and Managed Agents |
146| **Admin API key** | The APIs that manage and report on an organization, such as the [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api) and the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api) |
25147 
26| Key type | Acts as | Works in | Stops working when |
27| ----- | ----- | ----- | ----- |
28| **Personal key** | You, the user, with your roles and permissions | Either a single workspace or the workspaces where your role allows API use, chosen when the key is created | You lose access to the organization. A single-workspace key also stops working when you lose access to that workspace or that workspace is archived. Personal keys are archived when you are removed from the organization. If you are re-invited, create new keys; archived keys are not restored |
29| **Service account key** | A [service account](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#service-accounts) | Either a single workspace or anything the service account has access to, chosen when the key is created. A service account has access to the Default Workspace and to workspaces it has been added to | The service account is archived. A single-workspace key also stops working when the service account is removed from that workspace or that workspace is archived |
30| **Workspace key** (legacy) | No one: it belongs to the workspace it was created in | That workspace | It expires, is disabled or deleted, or its workspace is archived, regardless of whether its creator leaves the organization |
148An Admin API key can’t call Claude. The Claude Console calls a Developer API key an “API key” and lists these keys on its **API keys** page.
31149 
32Personal keys and service account keys are identity-backed: each belongs to a user or service account your organization already manages, and every request acts as that identity. When that identity is removed from the organization, the key stops working. This means that keys don’t accidentally outlive the people or workloads that own them. Prefer them over workspace keys for new integrations.
150To create a Developer API key, see [Get your Claude API key](https://platform.claude.com/docs/en/get-api-key). For the types of Developer API key, such as personal and service account keys, and how to send one, see [Developer API keys](https://platform.claude.com/docs/en/manage-claude/api-keys).
33151 
34If a tool that only you run asks for a key, use a personal key. A shared personal key acts as one person and breaks when they leave. For shared or automated workloads (CI, production services), have an organization admin create a service account so the workload has its own identity.
152## Which credential is used
35153 
36Workspace API keys work but are legacy. Prefer identity-backed keys or [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation). To migrate, see [Replacing workspace API keys](https://platform.claude.com/docs/en/manage-claude/authentication#replacing-workspace-api-keys).
154If `ANTHROPIC_API_KEY` is set, the SDK and the CLI use it and don’t look for a CLI sign-in or Workload Identity Federation. A credential that your code passes to the SDK comes before that variable.
37155 
38### Create and use a key
156To stop using a key, follow these steps:
39157 
40* **Create a key:** In the Claude Console, go to the [API keys](https://platform.claude.com/settings/keys) page (`platform.claude.com/settings/keys`) and click **Create key**. Name the key and select an [expiration](https://platform.claude.com/docs/en/manage-claude/authentication#key-expiration). Set **Linked account** to yourself for a personal key, or to a service account for a key shared across multiple users. You can also scope the key to a specific workspace, which lets you skip setting a workspace ID manually in future requests.
41* **Use the key:** Send it as `Authorization: Bearer <key>` on direct HTTP requests, or set the `ANTHROPIC_API_KEY` environment variable and the [client SDK](https://platform.claude.com/docs/en/cli-sdks-libraries/overview) picks it up automatically.
1581. Unset `ANTHROPIC_API_KEY` everywhere your code runs.
1592. To check which credential the CLI now uses, run `ant auth status` (see [Check authentication status](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/authentication#check-authentication-status) on the CLI authentication options page).
42160 
43```http
44POST /v1/messages
45Authorization: Bearer YOUR_API_KEY
46anthropic-version: 2026-10-21
47content-type: application/json
48```
161For the order of every credential, including `ANTHROPIC_AUTH_TOKEN` and credentials passed in code, see [Credential precedence](https://platform.claude.com/docs/en/manage-claude/wif-reference#credential-precedence) on the WIF reference page.
49162 
50You can also send the key in the legacy `x-api-key: YOUR_API_KEY` header in place of `Authorization`.
163## Browser-based applications
51164 
52Store API keys in a secrets manager, rotate them periodically, and disable or delete any key you suspect has leaked. On the [API keys](https://platform.claude.com/settings/keys) page in the Claude Console, **Disable** is reversible (the Admin API reports the key’s `status` as `"inactive"`, and **Re-enable** returns it to `"active"`), whereas **Delete** is permanent: the key is archived and still appears in [List API Keys](https://platform.claude.com/docs/en/api/organization/api_keys/list) with `status: "archived"`. Expired keys can only be deleted. 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. To limit where a leaked key works, turn on [IP allowlisting](https://platform.claude.com/docs/en/manage-claude/ip-allowlist).
165Call the Claude API from your own back end, not from code that runs in your users’ browsers. Anyone who uses a webpage can read a credential in that page’s code. Typically, your web front end calls your back end, which holds the credential and calls the Claude API.
53166 
54<CodeGroup>
55 ```bash cURL
56 curl https://api.anthropic.com/v1/messages \
57 -H "x-api-key: $ANTHROPIC_API_KEY" \
58 -H "anthropic-version: 2026-10-21" \
59 -H "content-type: application/json" \
60 -d '{
61 "model": "claude-opus-5-5",
62 "max_tokens": 1024,
63 "messages": [{"role": "user", "content": "Hello, Claude"}]
64 }'
65 ```
66 
67 ```bash CLI
68 # See /docs/en/cli-sdks-libraries/cli/authentication#api-key for zsh, bash, and Windows variants
69 export ANTHROPIC_API_KEY=sk-ant-api03-...
70 ```
71 
72 ```python Python
73 client = Anthropic(api_key="my-anthropic-api-key")
74 # or, with ANTHROPIC_API_KEY set in the environment:
75 client = Anthropic()
76 ```
77 
78 ```typescript TypeScript
79 const client = new Anthropic({ apiKey: "my-anthropic-api-key" });
80 // or, with ANTHROPIC_API_KEY set in the environment:
81 // const client = new Anthropic();
82 ```
83 
84 ```csharp C#
85 AnthropicClient client = new() { ApiKey = "my-anthropic-api-key" };
86 // Or, with ANTHROPIC_API_KEY set in the environment:
87 // AnthropicClient client = new();
88 ```
89 
90 ```go Go
91 client := anthropic.NewClient(
92 option.WithAPIKey("my-anthropic-api-key"), // defaults to os.LookupEnv("ANTHROPIC_API_KEY")
93 )
94 ```
95 
96 ```java Java
97 // Explicit
98 AnthropicClient client = AnthropicOkHttpClient.builder()
99 .apiKey("my-anthropic-api-key")
100 .build();
101 
102 // From ANTHROPIC_API_KEY (or anthropic.apiKey system property)
103 AnthropicClient clientFromEnv = AnthropicOkHttpClient.fromEnv();
104 ```
105 
106 ```php PHP
107 // Reads ANTHROPIC_API_KEY from the environment
108 $client = new Client();
109 // Or pass the key explicitly:
110 $client = new Client(apiKey: 'my-anthropic-api-key');
111 ```
112 
113 ```ruby Ruby
114 anthropic = Anthropic::Client.new(api_key: "my-anthropic-api-key")
115 # or, with ANTHROPIC_API_KEY set in the environment:
116 anthropic = Anthropic::Client.new
117 ```
118</CodeGroup>
119 
120### Select a workspace
121 
122API keys that are created for a specific workspace only work in that workspace, and API requests using these keys can omit the workspace ID.
123 
124If your API key isn’t scoped to a workspace, you must specify the workspace ID in the `anthropic-workspace-id` header for each request. See the following example for how to set this header in a request or in the SDK.
125 
126The [Admin API](https://platform.claude.com/docs/en/manage-claude/admin-api) accepts a personal key or service account key only if the key isn’t scoped to a specific workspace.
127 
128You can find a workspace’s ID in the **ID** column on the [Workspaces](https://platform.claude.com/settings/workspaces) page (`platform.claude.com/settings/workspaces`) in the Claude Console, or by calling the [List Workspaces](https://platform.claude.com/docs/en/api/organization/workspaces/list) endpoint. List Workspaces includes the Default Workspace only when you pass `include_default=true`; its ID is also in the `anthropic-workspace-id` [response header](https://platform.claude.com/docs/en/manage-claude/workspaces#identify-the-workspace-behind-an-api-response) of any request that runs there.
129 
130<CodeGroup>
131 ```bash cURL
132 # Required on every request for a key that isn't scoped to a workspace.
133 # Omit the anthropic-workspace-id header for a key scoped to one workspace.
134 curl https://api.anthropic.com/v1/messages \
135 -H "x-api-key: $ANTHROPIC_API_KEY" \
136 -H "anthropic-version: 2026-10-21" \
137 -H "anthropic-workspace-id: wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ" \
138 -H "content-type: application/json" \
139 -d '{
140 "model": "claude-opus-5-5",
141 "max_tokens": 1024,
142 "messages": [{"role": "user", "content": "Hello, Claude"}]
143 }'
144 ```
145 
146 ```bash CLI
147 # Required on every command for a key that isn't scoped to a workspace.
148 # Omit --workspace-id for a key scoped to one workspace.
149 ant messages create \
150 --workspace-id wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ \
151 --model claude-opus-5-5 \
152 --max-tokens 1024 \
153 --message '{role: user, content: "Hello, Claude"}'
154 ```
155 
156 ```python Python
157 client = Anthropic() # reads ANTHROPIC_API_KEY
158 
159 # Required on every request for a key that isn't scoped to a workspace.
160 # Omit extra_headers for a key scoped to one workspace.
161 message = client.messages.create(
162 model="claude-opus-5-5",
163 max_tokens=1024,
164 messages=[{"role": "user", "content": "Hello, Claude"}],
165 extra_headers={"anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"},
166 )
167 print(message.content)
168 
169 # Or set it once for every request from this client:
170 workspace_client = Anthropic(
171 default_headers={"anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"},
172 )
173 ```
174 
175 ```typescript TypeScript
176 const client = new Anthropic(); // reads ANTHROPIC_API_KEY
177 
178 // Required on every request for a key that isn't scoped to a workspace.
179 // Omit the second argument for a key scoped to one workspace.
180 const message = await client.messages.create(
181 {
182 model: "claude-opus-5-5",
183 max_tokens: 1024,
184 messages: [{ role: "user", content: "Hello, Claude" }]
185 },
186 { headers: { "anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ" } }
187 );
188 console.log(message.content);
189 
190 // Or set it once for every request from this client:
191 const workspaceClient = new Anthropic({
192 defaultHeaders: { "anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ" }
193 });
194 ```
195 
196 ```csharp C#
197 AnthropicClient client = new(); // reads ANTHROPIC_API_KEY
198 
199 MessageCreateParams parameters = new()
200 {
201 Model = Model.ClaudeOpus5_5,
202 MaxTokens = 1024,
203 Messages = [new UserMessageParam { Content = "Hello, Claude" }],
204 };
205 
206 // Required on every request for a key that isn't scoped to a workspace.
207 // Call client.Messages.Create(parameters) directly for a key scoped to one workspace.
208 var message = await client
209 .WithOptions(options =>
210 options with
211 {
212 ExtraHeaders = new Dictionary<string, string>
213 {
214 ["anthropic-workspace-id"] = "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ",
215 },
216 }
217 )
218 .Messages.Create(parameters);
219 Console.WriteLine(message);
220 
221 // Or set it once for every request from this client:
222 AnthropicClient workspaceClient = new(new ClientOptions
223 {
224 ExtraHeaders = new Dictionary<string, string>
225 {
226 ["anthropic-workspace-id"] = "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ",
227 },
228 });
229 ```
230 
231 ```go Go
232 client := anthropic.NewClient() // reads ANTHROPIC_API_KEY
233 
234 // Required on every request for a key that isn't scoped to a workspace.
235 // Omit the option for a key scoped to one workspace.
236 message, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
237 Model: anthropic.ModelClaudeOpus5_5,
238 MaxTokens: 1024,
239 Messages: []anthropic.MessageParam{
240 anthropic.NewUserMessage(anthropic.NewTextBlock("Hello, Claude")),
241 },
242 }, option.WithHeader("anthropic-workspace-id", "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"))
243 if err != nil {
244 log.Fatal(err)
245 }
246 fmt.Println(message.Content)
247 
248 // Or set it once for every request from this client:
249 workspaceClient := anthropic.NewClient(
250 option.WithHeader("anthropic-workspace-id", "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"),
251 )
252 ```
253 
254 ```java Java
255 AnthropicClient client = AnthropicOkHttpClient.fromEnv(); // reads ANTHROPIC_API_KEY
256 
257 // Required on every request for a key that isn't scoped to a workspace.
258 // Omit putAdditionalHeader for a key scoped to one workspace.
259 Message message = client.messages().create(MessageCreateParams.builder()
260 .model(Model.CLAUDE_OPUS_5_5)
261 .maxTokens(1024)
262 .addUserMessage("Hello, Claude")
263 .putAdditionalHeader("anthropic-workspace-id", "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ")
264 .build());
265 
266 IO.println(message.content());
267 
268 // Or set it once for every request from this client:
269 AnthropicClient workspaceClient = AnthropicOkHttpClient.builder()
270 .fromEnv()
271 .putHeader("anthropic-workspace-id", "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ")
272 .build();
273 ```
274 
275 ```php PHP
276 $client = new Client(); // reads ANTHROPIC_API_KEY
277 
278 // Required on every request for a key that isn't scoped to a workspace.
279 // Omit requestOptions for a key scoped to one workspace.
280 $message = $client->messages->create(
281 model: Model::CLAUDE_OPUS_5_5,
282 maxTokens: 1024,
283 messages: [['role' => 'user', 'content' => 'Hello, Claude']],
284 requestOptions: [
285 'extraHeaders' => ['anthropic-workspace-id' => 'wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ'],
286 ],
287 );
288 
289 echo json_encode($message->content), PHP_EOL;
290 ```
291 
292 ```ruby Ruby
293 client = Anthropic::Client.new # reads ANTHROPIC_API_KEY
294 
295 # Required on every request for a key that isn't scoped to a workspace.
296 # Omit request_options for a key scoped to one workspace.
297 message = client.messages.create(
298 model: Anthropic::Model::CLAUDE_OPUS_5_5,
299 max_tokens: 1024,
300 messages: [{ role: "user", content: "Hello, Claude" }],
301 request_options: { extra_headers: { "anthropic-workspace-id" => "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ" } }
302 )
303 
304 puts message.content
305 ```
306</CodeGroup>
307 
308If a request made with a key that isn’t scoped to a workspace omits the header, the API returns a 400 `invalid_request_error`:
309 
310```json JSON
311{
312 "type": "error",
313 "error": {
314 "type": "invalid_request_error",
315 "message": "This API key is not scoped to a workspace, so this request must include the anthropic-workspace-id header with the ID of the workspace to use. Add the header, or use an API key that is scoped to a workspace."
316 },
317 "request_id": "req_011CSHoEeqs5C35K2UUqR7Fy"
318}
319```
320 
321A header value that isn’t a valid workspace ID returns a 400 `invalid_request_error` with the message `anthropic-workspace-id header must be a valid workspace ID.` If the workspace doesn’t exist, or the key’s user or service account doesn’t have access to it, the API returns a 404 `not_found_error` with the message ``Workspace `<id>` not found.``, the same response as for any unknown workspace.
322 
323Workload Identity Federation selects a workspace at token exchange instead; see the [WIF reference](https://platform.claude.com/docs/en/manage-claude/wif-reference) for details.
324 
325### Key expiration
326 
327When you create an API key from the [API keys](https://platform.claude.com/settings/keys) page 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. 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.
328 
329Anthropic 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.
330 
331After a key expires, requests made with it return a `401 authentication_error`. Create a new key to restore access; expired keys cannot be reactivated.
332 
333The 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/organization/api_keys/list) and [Retrieve API Key](https://platform.claude.com/docs/en/api/organization/api_keys/retrieve) endpoints, so you can audit and rotate keys before they expire. The field is `null` for keys without an expiration.
334 
335Expiration 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 disable or delete any key you suspect has leaked.
336 
337### Replacing workspace API keys
338 
339If you have a workspace key, you might want to replace it with [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) or a personal or service account key. This provides better security and observability.
340 
341See the [WIF reference](https://platform.claude.com/docs/en/manage-claude/wif-reference) for details on configuring Workload Identity Federation, which is preferred over long-lived keys.
342 
343To replace a workspace key with a personal or service account key:
344 
3451. **Decide the key type.** Your own tooling should use a personal key. A shared or unattended workload should use a service account key.
3462. **Create a service account** if necessary. You might have to ask an organization admin to create one on the [Service accounts](https://platform.claude.com/settings/service-accounts) page (`platform.claude.com/settings/service-accounts`) in the Claude Console and add it to the relevant workspace.
3473. **Create the new key.** Create it specifically for the integration’s workspace unless the integration needs multiple workspaces.
3484. **Deploy the new key.** Replace the old key wherever the integration reads it, typically the `ANTHROPIC_API_KEY` environment variable or a secrets manager entry. For a key that isn’t scoped to a workspace, also send the `anthropic-workspace-id` header as shown in [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace).
3495. **Delete the old key.** Confirm that requests succeed, then delete the workspace key on the [API keys](https://platform.claude.com/settings/keys) page in the Claude Console.
350 
351### Browser-based applications
352 
353Call the Claude API from your own back end, not from code that runs in your users’ browsers. Anyone who uses a webpage can read an API key in that page’s code. Typically, your web front end calls your back end, which holds the key and calls the Claude API.
167### Requests sent from a browser
354168 
355169A request sent directly from a browser is a cross-origin (CORS) request. The API accepts one only when it includes the `anthropic-dangerous-direct-browser-access: true` header. The TypeScript SDK sends this header when you set `dangerouslyAllowBrowser` to `true`. For the cases where exposing a key this way is acceptable, see [Runtime support](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript#runtime-support) in the TypeScript SDK guide.
356170 
357Organizations that have [zero data retention (ZDR)](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#zero-data-retention-zdr-scope) cannot call the API directly from a browser, even with that header. Other organization or workspace settings can have the same effect, and no setting allows browser requests for these organizations. The API returns a 401 `authentication_error` whose message begins `CORS requests are not allowed for this Organization`, even though the API key is valid.
171Some organization and workspace settings block browser requests, even with that header. These settings include the following:
358172 
359The restriction applies only to requests that include an `Origin` header, which browsers add and server-side HTTP clients normally do not. Requests from your own back end are not affected. If your back end forwards requests that start in a browser, have it create a new request to the Claude API. Don’t pass the browser’s request through. That request still includes the browser’s `Origin` header, and the API rejects it the same way.
173* [Zero data retention (ZDR)](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#zero-data-retention-zdr-scope)
174* A [customer-managed encryption key](https://platform.claude.com/docs/en/manage-claude/cmek) attached to a workspace
360175 
361## Workload Identity Federation
176No Claude Console setting overrides the block. For a blocked request, the API returns a 401 `authentication_error`, even though the credential is valid. The error’s message begins `CORS requests are not allowed for this Organization`.
362177 
363Workload Identity Federation (WIF) lets a workload authenticate with a short-lived identity token issued by an identity provider (IdP) you already trust. Such IdPs include AWS IAM, Google Cloud, and 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.
178Both the `anthropic-dangerous-direct-browser-access` header rule and the block apply only to requests that include an `Origin` header. Browsers add that header, and server-side HTTP clients normally don’t.
364179 
365Federation removes long-lived Claude API keys from your environment, which limits the damage that a leaked credential can cause 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 step earlier in that chain (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.
366 
367To 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.
368 
369## App Attest
370 
371App 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 1 hour, and authorize only [Messages API](https://platform.claude.com/docs/en/api/messages/create) calls.
372 
373To 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).
374 
375## Next steps
376 
377<CardGroup cols={2}>
378 <Card title="Set up Workload Identity Federation" icon="lock" href="https://platform.claude.com/docs/en/manage-claude/workload-identity-federation">
379 Configure issuers, rules, and service accounts, then exchange tokens
380 </Card>
381 
382 <Card title="Identity provider guides" icon="cloud" href="https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#identity-providers">
383 Step-by-step guides for AWS, Google Cloud, Azure, GitHub Actions, Kubernetes, SPIFFE, and Okta
384 </Card>
385 
386 <Card title="WIF reference" icon="book" href="https://platform.claude.com/docs/en/manage-claude/wif-reference">
387 Environment variables, validation rules, profile configuration, and error reference
388 </Card>
389 
390 <Card title="App Attest for iOS and macOS apps" icon="fingerprint" href="https://platform.claude.com/docs/en/manage-claude/app-attest">
391 Let genuine installations of your app call the Claude API without shipping an API key
392 </Card>
393 
394 <Card title="Client SDKs" icon="code" href="https://platform.claude.com/docs/en/cli-sdks-libraries/overview">
395 Python, TypeScript, C#, Go, Java, PHP, Ruby, and the CLI
396 </Card>
397</CardGroup>
180If your back end passes on requests that start in a browser, have it create a new request to the Claude API. A request forwarded as it is keeps the browser’s `Origin` header, so the API treats it as a request from a browser.
398181 

manage-claude/claude-code-analytics-api Changed · +6 / -2 lines

from line 5
55---
66 
77<Tip>
8 **The Admin API isn’t available to organizations on the claude.ai Team plan or to individual Claude Console accounts.** If your company also has a Claude Console organization, you can use the API with that organization; see [Create an Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys). An individual Console account must first set up an organization on the [Organization](https://platform.claude.com/settings/organization) page (`platform.claude.com/settings/organization`) in the Claude Console.
8 The Admin API isn’t available to organizations on the claude.ai Team plan, and an individual Claude Console account can’t create an Admin API key.
99</Tip>
1010 
11If your company has a Claude Console organization, you can use the Admin API with that organization; see the [Admin API keys and tokens](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) page. An individual Console account must first set up an organization on the [Organization settings](https://platform.claude.com/settings/organization) page (`platform.claude.com/settings/organization`) in the Claude Console.
12 
1113The Claude Code Analytics Admin API provides programmatic access to daily aggregated usage metrics for Claude Code users, allowing 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) in the Claude Console, without the complexity of the OpenTelemetry integration.
1214 
1315This API allows you to better monitor, analyze, and optimize your Claude Code adoption:
from line 21
1921* **Usage justification:** Provide metrics to justify and expand Claude Code adoption internally
2022 
2123<Check>
22 **Admin API credentials required.** These endpoints are part of the Admin API. You can access them using an [Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys), an OAuth token with the `org:admin` scope, or a personal or service account key that isn’t scoped to a workspace; workspace API keys don’t work. See [Authentication](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication) for details.
24 **Admin API credentials required.** These endpoints are part of the Admin API.
2325</Check>
26 
27Authenticate with an [Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys) or an OAuth token with the `org:admin` scope. You can also use a personal or service account key scoped to the organization. A personal or service account key has the permissions of its user or service account. Keys scoped to a single workspace, including workspace keys, don’t work. See the Admin API page’s [Authentication](https://platform.claude.com/docs/en/manage-claude/admin-api#authentication) section.
2428 
2529<Note>
2630 The Claude Code Analytics API is available on the Claude API. If you’re using Claude Platform on AWS, view Claude Code usage on the **Usage** page in the Claude Console instead.

manage-claude/claude-tag-api Changed · +20 / -17 lines

from line 4
44description: "Manage Claude Tag in Slack for your Claude Enterprise organization from your own systems: read and change settings on Slack channels and workspaces, see which settings apply and why, and attach Access bundles."
55---
66 
7[Claude Tag](https://claude.com/docs/claude-tag/overview) is Claude working as a teammate in Slack: someone mentions Claude in a channel and Claude answers in the thread. The Claude Tag API lets you read and change, from your own systems, the Claude Tag settings that an organization owner otherwise sets by hand in [claude.ai > Organization settings > Claude Tag](https://claude.ai/admin-settings/claude-tag). Use it to turn Claude on channel by channel from an approval workflow, keep your configuration in version control, or audit what applies in every channel.
7[Claude Tag](https://claude.com/docs/claude-tag/overview) is Claude working as a teammate in Slack: someone mentions Claude in a channel and Claude answers in the thread. The Claude Tag API lets you read and change Claude Tag’s settings for Slack channels and workspaces from your own systems. Without it, people change them by hand. For example, an organization owner uses the [Claude Tag settings](https://claude.ai/admin-settings/claude-tag) page in claude.ai (**Organization settings** > **Claude Tag**). Use the API to turn Claude on channel by channel from an approval workflow, keep your configuration in version control, or audit what applies in every channel.
88 
99Claude Tag is a claude.ai product. This API manages it for a Claude Enterprise organization and has nothing to do with Claude Platform workspaces, API usage, or the Claude Console.
1010 
1111<Check>
12 **Scoped Admin API key required**
12 **Enterprise Admin API key required**
1313 
14 These endpoints require an Admin API key with the `read:claude_tag` scope (for `GET` endpoints) or the `write:claude_tag` scope (for `POST` and `DELETE` endpoints); see [Scopes](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#scopes). See [Create an Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#create-a-key-for-a-claude-enterprise-organization) for where your primary owner creates one.
14 These endpoints require an Enterprise Admin API key. `GET` endpoints need the `read:claude_tag` scope, and `POST` and `DELETE` endpoints need the `write:claude_tag` scope. For details, see [Scopes](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#scopes).
1515</Check>
1616 
17<Note>
18 The Claude Tag API is in **beta** and is available to Claude Enterprise organizations only. It is not available to Claude Platform (Claude Console) organizations.
17The Claude Tag API is in **beta** and is available to Claude Enterprise organizations only. It is not available to Claude Platform (Claude Console) organizations.
1918 
20 Every request must include the [beta header](https://platform.claude.com/docs/en/api/beta-headers) `anthropic-beta: experimental-claude-tag-2026-10-21` (the SDK and the `ant` CLI send it for you). A request without it returns `404`, exactly as if the endpoint did not exist.
21</Note>
19Every request must include the [beta header](https://platform.claude.com/docs/en/api/beta-headers) `anthropic-beta: experimental-claude-tag-2026-10-21` (the SDK and the `ant` CLI send it for you). A request without it returns `404`, exactly as if the endpoint did not exist.
2220 
2321## Endpoints
2422 
from line 29
3129| **Bundles:** list your organization’s Access bundles, read one (read-only) | `GET /v1/organizations/claude_tag/bundles`<br />`GET /v1/organizations/claude_tag/bundles/{bundle_id}` |
3230| **Bundle targets:** list where a Bundle is attached, attach it to a channel or workspace, read one attachment, detach it | `GET /v1/organizations/claude_tag/bundles/{bundle_id}/targets`<br />`POST /v1/organizations/claude_tag/bundles/{bundle_id}/targets`<br />`GET /v1/organizations/claude_tag/bundles/{bundle_id}/targets/{target_id}`<br />`DELETE /v1/organizations/claude_tag/bundles/{bundle_id}/targets/{target_id}` |
3331 
34This release covers Slack. Connecting and disconnecting a Slack workspace or Enterprise Grid, your organization’s Slack defaults, creating and editing Access bundles, spend limits, and every Claude Tag setting other than the five in [Settings](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#settings) stay in claude.ai.
32The API covers Slack. These tasks stay in claude.ai:
3533 
34* Connecting or disconnecting a Slack workspace or Enterprise Grid
35* Changing your organization’s Slack defaults
36* Creating Access bundles, or changing anything about one other than its instructions
37* Setting Claude Tag spend limits
38 
3639## Prerequisites
3740 
3841* Your organization must be on a Claude Enterprise plan, with [Claude Tag set up](https://claude.com/docs/claude-tag/admins/setup-overview) and at least one Slack workspace or Enterprise Grid connected.
39* Your primary owner creates an Admin API key with the `read:claude_tag` scope, the `write:claude_tag` scope, or both in [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access). See [Create a key for a Claude Enterprise organization](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#create-a-key-for-a-claude-enterprise-organization).
40* Every request carries three headers: `x-api-key`, `anthropic-version: 2026-10-21` (see [API versions](https://platform.claude.com/docs/en/api/versioning)), and `anthropic-beta: experimental-claude-tag-2026-10-21`.
42* Your primary owner creates an Enterprise Admin API key on the [API settings](https://claude.ai/admin-settings/api-access) page in claude.ai (**Organization settings** > **API**). The key needs the `read:claude_tag` scope, the `write:claude_tag` scope, or both. See [Create a key for a Claude Enterprise organization](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#create-a-key-for-a-claude-enterprise-organization).
43* Every cURL request carries the `x-api-key`, `anthropic-version: 2026-10-21`, and `anthropic-beta: experimental-claude-tag-2026-10-21` headers. A request with a JSON body also carries `content-type: application/json`. For the `anthropic-version` header’s values, see [API versions](https://platform.claude.com/docs/en/api/versioning).
4144 
4245In Python, TypeScript, C#, Go, Java, PHP, and Ruby, the SDK exposes these endpoints under `client.beta.organization.claude_tag` (typescript: `client.beta.organization.claudeTag`; csharp, go: `client.Beta.Organization.ClaudeTag`; java: `client.beta().organization().claudeTag()`; php: `$client->beta->organization->claudeTag`), and the [`ant` CLI](https://platform.claude.com/docs/en/cli-sdks-libraries/cli/quickstart) under `ant beta:organization:claude-tag`; they send the `anthropic-version` and `anthropic-beta` headers for you. The examples on this page read the Admin API key from the `ANTHROPIC_API_KEY` environment variable. Where an SDK or the CLI fetches more pages for you, `limit` sets the page size, not the total (see [Pagination](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#pagination)).
4346 
from line 368
365368 
3663691. Ask an organization owner to turn Claude off everywhere in claude.ai, with the **Enable Claude Tag in Slack** toggle under **Default Slack access**, which stores `enabled` as `false` on your organization’s Slack defaults. [Read-only mode](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#read-only-mode) must be off while they do.
3673702. When your approval system approves a channel, [set the channel up](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#set-up-a-channel) with `"settings": {"enabled": true}`. The request takes Slack’s own IDs and returns the channel even if it was already set up, so it is safe to repeat.
3683. In the same run, [attach](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#attach-a-bundle) the Bundles the team was approved for, so the channel’s first session already has its tools.
3713. In the same run, [attach the Bundles](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#attach-a-bundle) the team was approved for, so the channel’s first session already has its tools.
369372 
370373### Keep configuration in version control
371374 
from line 2492
24892492 
24902493| `error_code` | Status | Meaning and what to do |
24912494| ----- | ----- | ----- |
2492| `organization_level_scoped_api_key_required` | 403 | The credential is not a scoped Admin API key that belongs to the organization as a whole. Ask your primary owner for one. |
2495| `organization_level_scoped_api_key_required` | 403 | The credential is not an Enterprise Admin API key that belongs to the organization as a whole. Ask your primary owner for one. |
24932496| `api_key_scope_missing` | 403 | The key lacks `read:claude_tag` or `write:claude_tag`, whichever the endpoint requires. |
24942497| `claude_tag_writes_not_enabled` | 403 | Your organization can read through this API but is not enabled for changes. |
2495| `compliance_configuration_restricted` | 403 | Your organization has a compliance configuration under which Claude Tag stores nothing new, such as zero data retention. Setting a channel up, updating settings (even to clear them), and attaching a Bundle are refused. Detaching a Bundle and removing a channel are not, and such an organization can [remove](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#remove-a-channel) a channel even while Claude is on in it. |
2498| `compliance_configuration_restricted` | 403 | Your organization has a compliance configuration under which Claude Tag stores nothing new, such as zero data retention. Setting a channel up, updating settings (even to clear them), and attaching a Bundle are refused. Detaching a Bundle and removing a channel are not, and such an organization can [remove a channel](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#remove-a-channel) even while Claude is on in it. |
24962499| `environment_not_found` | 404 | `environment_id` names no environment or runner pool your organization can use here. The `id` in the path is fine. |
24972500| `environment_archived` | 400 | `environment_id` names an archived environment. |
24982501| `runner_pool_restricted` | 400 | The request would put a settings level on a restricted runner pool, or changes or clears `environment_id` on a settings level that stores one. An organization owner makes that change in claude.ai. See [Settings](https://platform.claude.com/docs/en/manage-claude/claude-tag-api#settings). |
from line 2518
25152518| `ccr_agent_proxy_profile_bound` | A Bundle is attached. |
25162519| `ccr_agent_proxy_profile_unbound` | A Bundle is detached. |
25172520 
2518The events name a channel or workspace by an identifier of the feed’s own, `agent_id` (prefixed `cagt_`), which no response of this API holds, so you cannot yet match an event to a channel’s or workspace’s `id`. The two Bundle events name the Bundle in `profile_id` and the channel or workspace, by the same `agent_id`, in `scope_id`.
2521The events name a channel or workspace by an identifier of the feed’s own, `agent_id` (prefixed `cagt_`). No response of this API holds that identifier, so you cannot match an event to a channel’s or workspace’s `id`. The two Bundle events name the Bundle in `profile_id` and the channel or workspace, by the same `agent_id`, in `scope_id`.
25192522 
25202523A `ccr_agent_updated` event lists what changed in `updated_fields`, under the feed’s own names:
25212524 
from line 2537
25342537## See also
25352538 
25362539<CardGroup cols={2}>
2537 <Card title="Create an Admin API key" href="https://platform.claude.com/docs/en/manage-claude/admin-api-keys">
2540 <Card title="Admin API keys and tokens" href="https://platform.claude.com/docs/en/manage-claude/admin-api-keys">
25382541 Where your primary owner creates a scoped key.
25392542 </Card>
25402543 

manage-claude/compliance-activity-feed Changed · +28 / -2 lines

## Activities that belong to an account

from line 60
6060 
6161Filter by organization, actor, activity type, or a `created_at` time window using the dotted sub-parameters `created_at.gte`, `.gt`, `.lte`, and `.lt`. See the [API reference](https://platform.claude.com/docs/en/api/compliance/activities/list) for each parameter’s type and accepted values.
6262 
63Repeatable parameters use array-bracket query syntax: pass `activity_types[]=...`, `actor_ids[]=...`, or `organization_ids[]=...` once for each value.
63Repeatable parameters use array-bracket query syntax: pass `activity_types[]=...`, `actor_ids[]=...`, or `organization_ids[]=...` once for each value. A request that filters by `organization_ids[]` does not return [activities that belong to an account](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed#activities-that-belong-to-an-account).
6464 
6565```bash cURL
6666curl --fail-with-body -sS -G \
from line 149
149149| ----- | ----- | ----- |
150150| `id` | string | Unique identifier for the activity. |
151151| `created_at` | RFC 3339 string | When the activity occurred. |
152| `organization_id` | string or null | Organization where the activity occurred, or `null` for events not tied to an organization. |
152| `organization_id` | string or null | Organization where the activity occurred, or `null` for events not tied to an organization, such as [activities that belong to an account](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed#activities-that-belong-to-an-account). |
153153| `organization_uuid` | string or null | Same scoping as `organization_id`, expressed as a UUID. |
154154| `actor` | Actor union | Who or what performed the activity. See the following actor table. |
155155| `type` | string | The activity type, for example `claude_chat_created`. |
from line 182
182182<Note>
183183 **Build forward-compatible handlers.** Pass through unrecognized `type` and `actor.type` values, and ignore fields your handler does not expect, so your integration keeps working when new activity types ship.
184184</Note>
185 
186## Activities that belong to an account
187 
188Some activities belong to a member’s account rather than to one organization, so their `organization_id` is `null`. The Activity Feed records them only for members whose email address is on a domain that your [parent organization](https://platform.claude.com/docs/en/manage-claude/compliance-api#how-the-compliance-api-works) has verified. These activities are:
189 
190* Sign-ins by email link or social login: `magic_link_login_succeeded`, `social_login_succeeded`
191* Sign-outs: `user_logged_out`
192* Account deletion: `account_deleted`
193* Trusted devices: `trusted_device_enrolled`, `trusted_device_credential_rotated`, `trusted_device_revoked`
194* Step-up verification: `step_up_authentication_succeeded`, `step_up_authentication_failed`, `step_up_credential_enrolled`
195* Consents: `user_consent_recorded`, `user_consent_revoked`
196* Changes to personal settings: `claude_user_settings_updated`
197 
198Some `user_consent_recorded` and `claude_user_settings_updated` activities have an `organization_id`. Those belong to that organization, and this section does not apply to them. SSO sign-in activities (`sso_login_*`) are not on this list.
199 
200Until about 17:00 UTC on November 13, 2026, the feed could also record these activities for members on other domains. Those activities stay in the feed.
201 
202Only a [key for the parent organization](https://platform.claude.com/docs/en/manage-claude/compliance-api-access#set-up-the-compliance-api) returns these activities. An organization with no parent organization does not receive them.
203 
204To record these activities for members on other domains, verify those domains.
205 
206<Warning>
207 If your parent organization requires SSO, a newly verified domain requires it too, for the same products. Everyone with an email address on that domain, member or not, must then sign in with SSO. In that case, anyone who is not set up in your identity provider cannot sign in.
208</Warning>
209 
210To verify a domain, follow the **Verify your domain(s)** step in [Set up single sign-on (SSO)](https://support.claude.com/en/articles/13132885-set-up-single-sign-on-sso). Each subdomain counts separately: verifying `example.com` does not cover `eu.example.com`. Recording starts when you verify a domain, and the feed does not backfill earlier activity. The feed does not record these activities for members whose domain you cannot verify, such as `gmail.com`.
185211 
186212## Next steps
187213 

manage-claude/compliance-api-access Changed · +7 / -7 lines

from line 40
4040Accepting the EFS and Enterprise Data Controls terms turns on the Compliance API for your organization.
4141 
4242<Warning>
43 A Compliance Access Key with `read:compliance_user_data` can read every chat, file, project, and session transcript in every linked organization, including content the primary owner has not seen. A key with `delete:compliance_user_data` can permanently delete chats, files, and projects. Treat Compliance Access Keys like production database credentials: store them in a secrets manager, never in source control or SIEM forwarder configuration. Treat Admin API keys the same way: one that you create while the [Safety Cases API](https://platform.claude.com/docs/en/manage-claude/enterprise-frontier-safeguards/safety-cases-api#get-access) is available to your organization can read the prompts and responses of flagged messages.
43 A Compliance Access Key with `read:compliance_user_data` can read every chat, file, project, and session transcript in every linked organization, including content the primary owner has not seen. A key with `delete:compliance_user_data` can permanently delete chats, files, projects, and code artifacts. Treat Compliance Access Keys like production database credentials: store them in a secrets manager, never in source control or SIEM forwarder configuration. Treat Admin API keys the same way: one that you create while the [Safety Cases API](https://platform.claude.com/docs/en/manage-claude/enterprise-frontier-safeguards/safety-cases-api#get-access) is available to your organization can read the prompts and responses of flagged messages.
4444</Warning>
4545 
4646<Steps>
from line 78
7878 </Step>
7979 
8080 <Step title="Open API settings">
81 Go to [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access) and find the **Keys** section.
81 Go to the [API settings](https://claude.ai/admin-settings/api-access) page in claude.ai (**Organization settings** > **API**) and find the **Keys** section.
8282 </Step>
8383 
8484 <Step title="Create the key">
from line 88
8888 | ----- | ----- |
8989 | `read:compliance_activities` | Read the Activity Feed. A key covering the parent organization reads events for the parent organization and all linked organizations. |
9090 | `read:compliance_user_data` | Read user chats, messages, files, projects, session metadata and transcripts, organization users, user preferences, and group members. Together with `read:compliance_org_data`, also read who made a [Security posture attestation](https://platform.claude.com/docs/en/manage-claude/compliance-security-posture/results-reference#who-attested-and-comments), where the endpoint returns it: a user ID. |
91 | `delete:compliance_user_data` | Delete user chats, files, and projects. |
91 | `delete:compliance_user_data` | Delete user chats, files, projects, and code artifacts. |
9292 | `read:compliance_org_data` | Read organization metadata (names, types, roles, and groups) and the effective settings in force for organizations under the parent organization. Also read an organization’s [Security posture](https://platform.claude.com/docs/en/manage-claude/compliance-security-posture/results-reference): the current results of most of its security controls, with the attestations that the response shows. User listings and group membership require `read:compliance_user_data`. |
9393 
9494 With the Plugins API, `read:compliance_org_data` also reads your organization’s plugin and plugin marketplace inventory through the Admin API, including members’ personal plugins and their files. That inventory identifies members: it carries the user ID of each member who owns or created a plugin, or with whom a plugin has been shared individually, and the email address of a plugin’s creator while they are still a member; see [Read plugins and plugin marketplaces](https://platform.claude.com/docs/en/manage-claude/compliance-org-data#read-plugins-and-plugin-marketplaces).
from line 121
121121 The Compliance API must already be [enabled for your Claude Console organization](https://platform.claude.com/docs/en/manage-claude/compliance-api-access#set-up-the-compliance-api) before an Admin API key can call the Activity Feed.
122122</Note>
123123 
124Follow 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), then set the key as an environment variable:
124Follow the steps in [Create a key for a Claude Console organization](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#create-a-key-for-a-claude-console-organization) on the Admin API keys and tokens page. Then, set the key as an environment variable:
125125 
126126```bash
127127export ANTHROPIC_ADMIN_KEY=sk-ant-admin01-...
from line 137
137137 
138138To inspect the scopes on a key you already have, use one of the following signals.
139139 
140* **Key prefix.** `sk-ant-admin01-` is an Admin API key (carries `read:compliance_activities` only, subject to the enablement timing in the preceding section; the exception is a key created while the Safety Cases API is available, which also carries that API’s scopes). `sk-ant-api01-` is a Compliance Access Key; its scopes are the subset you selected at creation.
141* **Settings UI.** For a Compliance Access Key, open the **Keys** section in [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access) and read the **Scopes** column for the key. Admin API keys, listed on the [Admin keys](https://platform.claude.com/settings/admin-keys) page (`platform.claude.com/settings/admin-keys`) in the Claude Console, have no selectable scopes.
140* **Key prefix.** `sk-ant-admin01-` is a Console Admin API key. Of the Compliance API’s scopes, it carries only `read:compliance_activities`, and only if the Compliance API was enabled for the organization when the key was created. The exception is a key created while the Safety Cases API is available, which also carries that API’s scopes. `sk-ant-api01-` is an [Enterprise Admin API key](https://platform.claude.com/docs/en/manage-claude/admin-api-keys#create-a-key-for-a-claude-enterprise-organization), with the scopes you selected when you created it. One that holds only Compliance API scopes is also called a Compliance Access Key.
141* **Settings UI.** For a Compliance Access Key, open the **Keys** section of the [API settings](https://claude.ai/admin-settings/api-access) page in claude.ai (**Organization settings** > **API**). The **Scopes** column lists each key’s scopes. Console Admin API keys, listed on the [Admin keys](https://platform.claude.com/settings/admin-keys) page (`platform.claude.com/settings/admin-keys`) in the Claude Console, have no selectable scopes.
142142* **Error responses.** A call that exceeds the key’s scopes returns a 403 with a message in the format `Missing required scopes. Got: [<scopes the key carries>] Needed one of: [<scopes the endpoint accepts>]` (`Needed: [...]` on the delete endpoints). See [Handle Compliance API errors](https://platform.claude.com/docs/en/manage-claude/compliance-errors#403-forbidden) for the full error catalog.
143143 
144144```json
from line 152
152152 
153153## Manage and rotate keys
154154 
155Delete a Compliance Access Key from the same **Keys** table where you created it: go to [claude.ai > Organization settings > API](https://claude.ai/admin-settings/api-access). Delete an Admin API key from the [Admin keys](https://platform.claude.com/settings/admin-keys) page (`platform.claude.com/settings/admin-keys`) in the Claude Console.
155Delete a Compliance Access Key in the **Keys** section of the [API settings](https://claude.ai/admin-settings/api-access) page in claude.ai (**Organization settings** > **API**). Delete a Console Admin API key from the [Admin keys](https://platform.claude.com/settings/admin-keys) page (`platform.claude.com/settings/admin-keys`) in the Claude Console.
156156 
157157Deleting a key takes effect on the next request: there is no grace period. Compliance Access Keys do not expire on their own.
158158 
Feedback