Create an API Key

Su Suriya Ravichandran Updated 10 Nov 2026
13 min read ·Lesson 6 of 200

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:

QuestionHow 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, and production, 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 typeActs asStops working whenUse it for
Personal keyYou, with your roles and permissionsYou lose access to the organization (or to its workspace, for a single-workspace key)Your own development, learning, and scripts
Service account keyA service account: a non-human identity created by an adminThe service account is archived or removed from the workspaceShared or automated workloads: production services, CI pipelines, agents
Workspace key (legacy)No one: it belongs to the workspaceIt expires, is disabled or deleted, or the workspace is archivedExisting 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

SituationRecommended key
Following this tutorialPersonal key
Your own scripts and experimentsPersonal key
A web application used by customersService account key
A CI/CD pipeline running testsService account key
Code shared by a teamService 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:

OptionTypical use
3 hoursA quick demo or one-off test
1 dayA workshop or short experiment
7 daysA short project or evaluation
30 daysOngoing learning and development
Custom durationMatching your organization's rotation policy
NeverKeys 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:

SettingWhat to choose for this tutorialWhy
Nameclaude-tutorial-laptopA descriptive name tells you later where the key is used
Expiration30 daysLong enough to complete lessons, short enough to limit risk
Linked accountYourself (personal key)You are the only user of this key
WorkspaceA development workspace, if you have oneScoping 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 nameBetter name
testtutorial-macbook-2026-11
key1support-bot-production
my keyci-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_headers adds the header to every request made by the client.
  • extra_headers adds 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) sends GET /v1/models and asks for up to five results per page. The SDK returns an auto-paginating iterator. Wrapping it in list(...) makes the network request happen inside the try block, so any error is caught there.
  • Each except block 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.
    • APIConnectionError means the request never reached the API.
    • APIStatusError catches any other API error, such as a missing workspace header (400).
  • model.id is the string you pass as model= in requests. model.display_name is 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:

ActionEffectReversible?When to use
DisableThe key stops working immediatelyYes: Re-enable restores itYou suspect a problem and want to investigate
DeleteThe key is permanently archivedNoThe 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:

  1. Create the new key.
  2. Deploy it everywhere the old key is used (environment variables, secrets manager).
  3. Confirm that requests succeed with the new key.
  4. 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:

  1. Delete or disable it immediately in the Console. Do this first; speed matters more than anything else.
  2. Create a replacement key and deploy it.
  3. Review usage in the Console for unexpected activity.
  4. 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

  1. 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.
  2. Store it in a password manager.
  3. Set it temporarily in your terminal and run test_key.py. Which models are listed?
  4. Temporarily change the last character of the key in your terminal and run the script again. Which exception is raised?
  5. Write down the steps you would follow if this key were accidentally pushed to GitHub.
Show answers for steps 4 and 5
  1. anthropic.AuthenticationError (HTTP 401). The key no longer matches a valid credential, so the API rejects the request before doing anything else.

  2. 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.

0 Comments

Reviewed before they appear

No comments yet.

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

Ask questions about Create an API Key and get answers drawn from it.

Signed-in readers only.