API Authentication and API Keys
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
The API key is the only thing standing between the internet and your invoice. This lesson explains how Claude API authentication works, which kind of key to use for which job, how to keep keys out of code, and what to do the day one leaks.
Learning objectives
- Send a correctly authenticated request using either documented header.
- Choose between personal keys, service account keys and the legacy workspace key.
- Use key expiration, disable and delete properly.
- Load the key safely in Python and Laravel, and redact it from logs.
- Explain why a key must never reach a browser.
Prerequisites
How authentication works
Anthropic's authentication page lists three methods:
| Method | Credential | Best for |
| API key | A static sk-ant-api… secret | Local development, scripts and servers where you control secret storage |
| Workload Identity Federation | A short-lived token exchanged from your identity provider (AWS, Google Cloud, Azure, Kubernetes, CI and others) | Production workloads that should hold no static secret |
| App Attest | A short-lived token for a genuine iOS or macOS app installation | Apps that call the API directly from the device |
This course uses API keys, because every beginner starts there. Know that Workload Identity Federation exists: when your workload already has a cloud identity, it removes the long-lived secret altogether.
Sending the key
The documentation shows the key sent as a bearer token, and also accepts the legacy x-api-key header. Both work; the SDKs do it for you.
# Documented primary form
curl https://api.anthropic.com/v1/messages \
-H "Authorization: Bearer $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2026-10-21" \
-H "content-type: application/json" \
-d '{"model":"claude-sonnet-5-5","max_tokens":50,"messages":[{"role":"user","content":"Hi"}]}'
# Legacy header, still accepted and used in many examples
# -H "x-api-key: $ANTHROPIC_API_KEY"
With an SDK you set the ANTHROPIC_API_KEY environment variable and write anthropic.Anthropic(); the client finds the key itself.
Key types
| Type | Acts as | Use it for |
| Personal key | You, with your roles and permissions | Your own development and scripts. It stops working when you leave the organisation. |
| Service account key | A service account an admin creates | CI and production services, so the workload has its own identity |
| Workspace key (legacy) | No one; it belongs to a workspace | Avoid for new work. Anthropic recommends identity-backed keys instead. |
Identity-backed keys (personal and service account) stop working when their owner is removed, so they cannot quietly outlive the person or service that created them. That is the reason to prefer them.
A key can be scoped to one workspace. If yours is not, every request must include an anthropic-workspace-id header, or the API returns a 400 error telling you so. The simplest fix is to create the key scoped to a workspace.
Expiration, disabling and deleting
- Expiration is set at creation and cannot be changed. After it passes, requests return 401
authentication_error and the key cannot be reactivated. Anthropic emails the creator as expiry approaches for long-lived keys.
- Disable is reversible: the key can be re-enabled later.
- Delete is permanent.
- IP allowlisting can limit where a leaked key works.
Step by step: load the key safely
Fail early with a clear message if the key is missing, and never print it. This Python helper also hides the key if it ever lands in a string you are about to log:
import os
class MissingApiKey(RuntimeError):
pass
def load_api_key() -> str:
"""Read the key from the environment and fail early with a clear message."""
key = os.environ.get("ANTHROPIC_API_KEY", "").strip()
if not key:
raise MissingApiKey("ANTHROPIC_API_KEY is not set. Add it to your environment or .env file.")
if not key.startswith("sk-ant-"):
# A sanity check only: it catches pasted-the-wrong-thing mistakes, it does not validate the key.
raise MissingApiKey("ANTHROPIC_API_KEY does not look like an Anthropic key (expected prefix sk-ant-).")
return key
def redact(text: str) -> str:
"""Hide a key if it ever ends up in a string you are about to log."""
key = os.environ.get("ANTHROPIC_API_KEY", "")
if key and key in text:
text = text.replace(key, f"{key[:10]}…[redacted]")
return text
In Laravel, read the key in config/services.php, never with env() in application code. This matters because env() returns null once the configuration is cached:
// config/services.php
'anthropic' => [
'key' => env('ANTHROPIC_API_KEY'),
'model' => env('ANTHROPIC_MODEL', 'claude-sonnet-5-5'),
],
// anywhere in the app
$key = config('services.anthropic.key');
Find keys you may have committed by mistake before someone else does:
git grep -n "sk-ant-" -- . ':!*.example'
git log -p --all -S"sk-ant-" | head
If either command shows a real key, treat it as leaked: disable it in the Console first, then clean the history.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
An agency runs five client sites that use Claude. Each site has its own service-account key scoped to its workspace, with a 30-day expiration and a calendar reminder to rotate. A shared personal key would have broken the day its owner left the agency. When one client's server is compromised, the agency disables that single key, creates a replacement and redeploys that one site. The other four never notice.
Common errors and solutions
| Symptom | Cause | Fix |
401 authentication_error | Malformed, revoked or expired key, or the wrong header. | Create a new key; check for stray spaces or quotes in .env. |
| 401 starting "CORS requests are not allowed for this Organization" | The request came from a browser (it has an Origin header) and your organisation cannot call the API from a browser. | Call the API from your own back end. Do not forward the browser's request as-is. |
Laravel: key is null in production | env() used outside config files after config:cache. | Read it via config('services.anthropic.key'). |
400 about anthropic-workspace-id | Key not scoped to a workspace. | Scope the key or send the header. |
Security considerations
- Never send the key to a browser. Anyone using a page can read its code and network traffic. The documented pattern is: browser calls your back end, your back end holds the key and calls Claude.
- Store keys in a secrets manager in production and rotate them periodically.
- Use an expiration and, where you can, IP allowlisting.
- If a key leaks, disable it first, investigate second.
- Keep logs free of keys and full request headers.
Performance and cost considerations
A stolen key is a cost incident. Spend limits (lesson 2.1) cap the damage, and separate keys per project let you see which one is spending. Check the Console's usage page when an invoice surprises you.
Key takeaways
- Keys are sent as
Authorization: Bearer (documented) or the legacy x-api-key; SDKs handle it.
- Prefer personal keys for yourself and service account keys for shared services; avoid legacy workspace keys.
- Expiration is fixed at creation; disable is reversible; delete is permanent.
- The key lives on the server only.
Lesson recap: pick the right key type, know expire, disable and delete, and keep the key on the server.
Knowledge check
- Name the three authentication methods in Anthropic's documentation.
- Why prefer a service account key over a shared personal key for production?
- What is the difference between disabling and deleting a key?
- Why does
env('ANTHROPIC_API_KEY') sometimes return null in a cached Laravel app?
- A 401 says "CORS requests are not allowed for this Organization". What is wrong, and how do you fix it?
Answers and explanations
- API key, Workload Identity Federation, and App Attest.
- A personal key acts as one person and stops working when they leave. A service account gives the workload its own identity.
- Disabled keys can be re-enabled; deleted keys are gone permanently (they remain visible as archived).
- After
php artisan config:cache, Laravel stops reading .env and env() only works inside config files. Read values with config().
- The call came from a browser, and the organisation is not allowed to make browser calls. Send the request from your own back end.
Official references and further reading
Related tutorials