Create an API Key
What an API Key Is
An API key is a secret string that works like a password for your program. When your code sends a request to the Claude API, the key proves which account the request belongs to.
Technically, a Claude API key is a static bearer credential. "Static" means it stays the same until it expires or is revoked. "Bearer" means that whoever holds ("bears") it can use it; the API does not check anything else about the caller. Keys are created in the Claude Console and start with the prefix:
sk-ant-
A full key looks like sk-ant-api03- followed by a long random string.
Why API Keys Exist
Every request to the Claude API must answer four questions, and the key answers all of them:
| Question | How the key answers it |
|---|---|
| Who is calling? (authentication) | The key identifies a user or service account in your organization |
| What may they do? (authorization) | The key's type and workspace scope limit what it can access |
| Who pays? (billing) | Usage is charged to the organization the key belongs to |
| What happened? (auditing) | Usage and requests can be traced back to the key and its owner |
Because a key carries all of this, anyone who has your key can make requests that you pay for. Treat it exactly like a password.
Before You Start: The Claude Console
API keys are managed in the Claude Console at:
https://platform.claude.com
The Console is separate from the Claude app. A Claude app subscription does not give you API access, and a Console account is not an app plan. In the Console, you can:
- create and manage API keys,
- set up billing and view usage,
- view rate limits and spend limits,
- organize work into workspaces, and
- try prompts in the browser-based playground.
Organizations and Workspaces
Two concepts determine where a key works:
- Organization: your company or personal account in the Console. Billing, members, and limits belong to the organization.
- Workspace: a subdivision of an organization. Every organization has a Default Workspace, and you can create more, for example
development,staging, andproduction, or one per product.
Why workspaces exist: they separate environments and use cases. Each workspace can have its own keys and limits, so a runaway development script cannot use up the budget of your production application, and usage reports show which project consumed what.
Billing
API usage is billed per token to your organization. Before your first real request, open the Billing page in the Console and make sure billing is set up. If it is not, requests fail even with a valid key.
Key Types
When you create a key, you choose its type. The type determines whose identity the key uses and when it stops working.
| Key type | Acts as | Stops working when | Use it for |
|---|---|---|---|
| Personal key | You, with your roles and permissions | You lose access to the organization (or to its workspace, for a single-workspace key) | Your own development, learning, and scripts |
| Service account key | A service account: a non-human identity created by an admin | The service account is archived or removed from the workspace | Shared or automated workloads: production services, CI pipelines, agents |
| Workspace key (legacy) | No one: it belongs to the workspace | It expires, is disabled or deleted, or the workspace is archived | Existing integrations only; avoid for new work |
Why Identity-Backed Keys Are Preferred
Personal keys and service account keys are identity-backed: each one belongs to a user or service account your organization manages. When that identity leaves or is removed, its keys stop working automatically. This prevents a common security problem, where keys keep working long after the person who created them has left the company.
Workspace keys have no owner, so they keep working until someone remembers to delete them. That is why they are considered legacy.
Choosing a Type
| Situation | Recommended key |
|---|---|
| Following this tutorial | Personal key |
| Your own scripts and experiments | Personal key |
| A web application used by customers | Service account key |
| A CI/CD pipeline running tests | Service account key |
| Code shared by a team | Service account key, never a teammate's personal key |
A shared personal key acts as one person and breaks when that person leaves. For anything shared, ask an organization admin to create a service account.
Key Expiration
When creating a key, you also choose when it expires:
| Option | Typical use |
|---|---|
| 3 hours | A quick demo or one-off test |
| 1 day | A workshop or short experiment |
| 7 days | A short project or evaluation |
| 30 days | Ongoing learning and development |
| Custom duration | Matching your organization's rotation policy |
| Never | Keys stored in a secrets manager that you rotate yourself |
Important details:
- Expiration is set at creation and cannot be changed later.
- If your organization has a maximum-expiration policy, the Console limits the options, and Never may be unavailable.
- Anthropic emails the key's creator before expiration: 7 days before for keys with a lifetime of at least 14 days, and 1 day before for keys with a lifetime of at least 7 days. Shorter-lived keys expire without a warning.
- After expiration, requests return
401 authentication_error. Expired keys cannot be reactivated; create a new key.
Why expiration matters: if a key leaks without anyone noticing, expiration limits how long it can be misused. It does not replace careful storage; it limits the damage when storage fails.
Step-by-Step: Create Your Key
Step 1: Sign In to the Claude Console
Go to https://platform.claude.com and sign in, or create an account.
Step 2: Open the API Keys Page
Navigate to the API keys page:
https://platform.claude.com/settings/keys
Step 3: Create the Key
Click Create key, then fill in the settings:
| Setting | What to choose for this tutorial | Why |
|---|---|---|
| Name | claude-tutorial-laptop | A descriptive name tells you later where the key is used |
| Expiration | 30 days | Long enough to complete lessons, short enough to limit risk |
| Linked account | Yourself (personal key) | You are the only user of this key |
| Workspace | A development workspace, if you have one | Scoping the key to one workspace means you never need to send a workspace ID |
Note: If the Create key button is disabled, your role in the organization does not allow creating keys. Ask an organization admin to change your role or to create a service account key for you.
Step 4: Copy the Key Immediately
The Console shows the full key only once, at creation. Copy it and store it somewhere safe right away, such as a password manager or your organization's secrets manager.
If you lose the key, you cannot view it again, and the Console or Admin API shows only a partially redacted hint. Create a new key and delete the lost one.
Warning: Do not paste the key into source code, chat messages, emails, tickets, or screenshots. Anyone who sees it can use it. Lesson 7 shows how to give the key to the SDK safely.
Naming Keys Well
A good name answers "where is this key used?" at a glance:
| Weak name | Better name |
|---|---|
test | tutorial-macbook-2026-11 |
key1 | support-bot-production |
my key | ci-github-actions-staging |
Clear names make it easy to find and revoke the right key during an incident, and to clean up unused keys.
Workspace Scope and the anthropic-workspace-id Header
A key created for a specific workspace works only in that workspace, and requests need no extra information.
A key that is not scoped to one workspace can work in several, so every request must say which workspace to use. It does this with the anthropic-workspace-id header. Without that header, the API returns a 400 error explaining that the key is not scoped to a workspace and the request must include anthropic-workspace-id.
You can find a workspace's ID (it starts with wrkspc_) in the ID column of the Workspaces page in the Console. With the SDK, you send it like this:
from anthropic import Anthropic
# Option 1: set it for every request from this client
client = Anthropic(
default_headers={"anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"},
)
# Option 2: set it for a single request
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=100,
messages=[{"role": "user", "content": "Hello, Claude"}],
extra_headers={"anthropic-workspace-id": "wrkspc_01JwQvzr7rXLA5AGx3HKfFUJ"},
)
default_headersadds the header to every request made by the client.extra_headersadds it to one request only.
Recommendation for beginners: create a key scoped to a single workspace, and you never have to deal with this header.
Test Your Key Without Spending Tokens
The Models API (GET /v1/models) lists the available models. It requires authentication but does not run a model, so it uses no tokens. That makes it ideal for testing a key.
With cURL
export ANTHROPIC_API_KEY="sk-ant-api03-..." # Paste your key (Lesson 7 covers this properly)
curl https://api.anthropic.com/v1/models \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2026-10-21"
A valid key returns a JSON list of models. An invalid key returns an authentication_error.
With the SDK
Save this as test_key.py:
"""test_key.py: verify an API key with a zero-token request."""
import sys
import anthropic
from anthropic import Anthropic
def main() -> int:
client = Anthropic() # Reads ANTHROPIC_API_KEY
try:
models = list(client.models.list(limit=5))
except anthropic.AuthenticationError:
print("Key rejected: it is invalid, expired, disabled, or deleted.")
return 1
except anthropic.PermissionDeniedError:
print("Key is valid but lacks permission for this request.")
return 1
except anthropic.APIConnectionError:
print("Could not reach the API. Check your network.")
return 1
except anthropic.APIStatusError as error:
print(f"Unexpected API error {error.status_code}: {error.message}")
return 1
print("Key works. Some available models:")
for model in models:
print(f" {model.id:<24} {model.display_name}")
return 0
if __name__ == "__main__":
sys.exit(main())
python test_key.py
Example output (the models listed depend on your account and the current lineup):
Key works. Some available models:
claude-opus-5-5 Claude Opus 5.5
claude-sonnet-5-5 Claude Sonnet 5.5
claude-haiku-5-5 Claude Haiku 5.5
How the Script Works
client.models.list(limit=5)sendsGET /v1/modelsand asks for up to five results per page. The SDK returns an auto-paginating iterator. Wrapping it inlist(...)makes the network request happen inside thetryblock, so any error is caught there.- Each
exceptblock maps to one failure category:AuthenticationError(401) means the key itself is the problem.PermissionDeniedError(403) means the key works but is not allowed to do this.APIConnectionErrormeans the request never reached the API.APIStatusErrorcatches any other API error, such as a missing workspace header (400).
model.idis the string you pass asmodel=in requests.model.display_nameis the human-readable name.{model.id:<24}left-aligns the ID in a 24-character column so the output lines up.
If this script prints models, your key, network, and SDK installation all work.
Managing Keys After Creation
The API keys page lists every key with its name, type, and expiration. You can manage keys in two ways:
| Action | Effect | Reversible? | When to use |
|---|---|---|---|
| Disable | The key stops working immediately | Yes: Re-enable restores it | You suspect a problem and want to investigate |
| Delete | The key is permanently archived | No | The key is leaked, unused, or replaced |
Expired keys can only be deleted.
Rotating a Key
Rotation means replacing a key with a new one on a regular schedule or after a possible exposure. Rotation follows this order to avoid downtime:
- Create the new key.
- Deploy it everywhere the old key is used (environment variables, secrets manager).
- Confirm that requests succeed with the new key.
- Delete the old key.
Why this order: if you delete the old key first, every application that uses it fails until the new key is deployed.
If a Key Leaks
If a key appears in a Git commit, a public repository, a screenshot, or a shared document:
- Delete or disable it immediately in the Console. Do this first; speed matters more than anything else.
- Create a replacement key and deploy it.
- Review usage in the Console for unexpected activity.
- Remove the key from the place it leaked. Deleting a file in a new commit does not remove it from Git history, so the key must be revoked regardless.
Rate Limits and Spend Limits
Your key's requests are subject to your organization's limits:
- Rate limits: how many requests and tokens per minute you can use.
- Spend limits: the maximum monthly cost.
You can see them on the Rate limits page and the Billing page in the Console. New organizations start on a lower usage tier and can move to higher tiers over time. Exceeding a rate limit returns 429 rate_limit_error. Lessons 142–146 show how to handle it.
Common Mistakes
Losing the Key After Closing the Dialog
Why it happens: the key is shown only once.
Fix: you cannot recover it. Create a new key, store it immediately, and delete the old one.
Committing the Key to Git
What happens: the key ends up in a repository, sometimes a public one. Automated scanners look for exposed credentials constantly, so a leaked key can be misused quickly.
Fix: revoke the key immediately and create a new one. To prevent it, keep keys in environment variables or .env files that Git ignores (Lessons 7, 8, 172, 173).
Sharing a Personal Key with a Team or an Application
What happens: everything works until the key's owner leaves the organization. Then the key stops working, and every system that used it breaks at once.
Fix: use service account keys for shared and automated workloads.
Using a Key Without a Workspace Scope and Forgetting the Header
What happens: every request fails with a 400 error mentioning anthropic-workspace-id.
Fix: create a key scoped to one workspace, or send the header with default_headers.
Choosing "Never" Expiration for Casual Keys
What happens: a forgotten tutorial key keeps working indefinitely, waiting to be leaked.
Fix: use a time-limited key for learning and experiments. Reserve Never for keys in a secrets manager with a rotation process.
Confusing Key Errors with Code Errors
Fix: 401 authentication_error almost always means the key is wrong, expired, disabled, or missing, not that your code is wrong. Run test_key.py to isolate the problem.
Best Practices
- One key per application and environment. Separate keys for development, staging, and production make usage easy to track and incidents easy to contain.
- Prefer identity-backed keys: personal keys for yourself, service account keys for anything shared or automated.
- Scope keys to a single workspace unless you truly need several.
- Set an expiration that matches the key's purpose.
- Store keys in a password manager or secrets manager, never in code or documents.
- Name keys descriptively so you know where each one is used.
- Rotate keys periodically, and immediately after any possible exposure.
- Delete unused keys. Every active key is a potential leak.
- Use workspaces and spend limits to keep development experiments away from production budgets.
Exercise
- Create a personal API key for this tutorial with a 30-day expiration, scoped to a single workspace if one is available. Give it a descriptive name.
- Store it in a password manager.
- Set it temporarily in your terminal and run
test_key.py. Which models are listed? - Temporarily change the last character of the key in your terminal and run the script again. Which exception is raised?
- Write down the steps you would follow if this key were accidentally pushed to GitHub.
anthropic.AuthenticationError(HTTP 401). The key no longer matches a valid credential, so the API rejects the request before doing anything else.Delete or disable the key in the Console immediately. Create a new key and update your environment. Check the Console's usage for activity you do not recognize. Then remove the key from the repository. The key must be revoked even after it is removed from the files, because it remains in Git history and may already have been copied.