Notes
Claude API setup and best practices
What this page gives you, on a fresh macOS or Linux machine: a clean Python virtual environment, the Anthropic SDK installed inside it, an API key from console.anthropic.com, and a .env file that keeps that key out of your code and out of git. Five minutes start to finish, then your environment is ready to run any Claude API code on this machine — and the page becomes a reference you can return to whenever you need to remember the exact incantation for the next project.
Why a virtual environment
On modern macOS and on most Linux distributions, the system Python is locked down. Running pip install anthropic against the system Python fails with error: externally-managed-environment (or just pip: command not found). The fix is to put every project inside a virtual environment — an isolated Python install where you can pip install whatever you need without touching the system.
Even on systems that don't enforce this, virtual environments are the right default. They mean tutorial code from a 2023 blog post doesn't break a tutorial from 2026 by clobbering the same global packages.
Creating a virtual environment
The standard library way (Python 3.10+ recommended):
cd ~/my-claude-experiments # or wherever
python3 -m venv .venv
source .venv/bin/activate
After activate, your shell prompt usually picks up (.venv) so you can tell at a glance you're inside the venv. To leave: deactivate.
Install the packages you need:
pip install anthropic requests
For Claude API work that includes notebooks and data analysis, the typical install is:
pip install anthropic requests pandas jupyterlab python-dotenv
If your project has a requirements.txt, install everything at once:
pip install -r requirements.txt
A one-line alternative — uv
The faster modern alternative to pip + venv is uv. One install, then:
uv venv
source .venv/bin/activate
uv pip install anthropic requests
Everything later in this note assumes the standard pip + venv workflow because it's the most universally available, but uv works identically for the rest of the steps.
Getting an Anthropic API key
A small thing to know before you sign up: Anthropic runs two separate products that look like the same thing if you're new — claude.ai and console.anthropic.com. Knowing which one you need saves a frustrating afternoon.
claude.ai is the consumer chat product — free tier or a Claude Pro monthly subscription, browser and mobile apps, the place where you talk to Claude through a UI. You don't get programmatic access from here; there's no API key to copy out of claude.ai.
console.anthropic.com is the developer console — API keys, usage dashboards, model evaluations, pay-as-you-go billing in credits rather than a subscription. Every SDK call in any Claude tutorial (client.messages.create(...) and the like) goes through the API behind this console. If you want to write code that calls Claude, this is the page you need.
The two share a login but bill separately. A Claude Pro subscription does not unlock the API, and API credit does not unlock Pro chat features. If you already have a claude.ai account, the same email signs you into the console; you'll just need to add API credit specifically before any code that calls Claude will work.
To get a key:
- Sign up or sign in at console.anthropic.com. If you already have a
claude.aiidentity, sign in with the same email — Anthropic links them. - Buy credit (the cheapest top-up is plenty — a typical tutorial costs well under a cent; see the cost section below).
- Go to Settings → API Keys, click Create Key, give it a label like
tutorials-2026, copy it. The key starts withsk-ant-and is shown once — copy it before closing the dialog.
If you lose it, generate a new one. There's no penalty for having multiple keys, and rotating them is good practice.
Frequent questions about billing
Does my Claude Pro subscription get me API access? No. The Pro subscription only changes your experience on claude.ai. API access is provisioned and billed separately on the developer console.
Does API credit unlock Claude Pro features in the chat? No. The chat product runs on claude.ai and is unaffected by your API credit balance — they're disjoint systems with disjoint billing.
Can I have both? Yes, and many developers do — Pro for everyday chat, API credit for the code they're writing. The two are charged independently each month.
If I use Claude Code (the CLI), which billing applies? Either. Claude Code can run against your API key (pay-as-you-go on the console) or against a claude.ai Pro / Max subscription, depending on how you configure it. Most developers point it at the API key, because batched or large jobs get expensive very fast on the chat-tier limits.
Storing the key in a .env file
Hardcoding the key in a notebook or shell history is a leak waiting to happen. The standard pattern is a per-project .env file plus the python-dotenv library.
One-time install:
pip install python-dotenv
Create .env in the project root:
cat > .env <<'EOF'
ANTHROPIC_API_KEY=sk-ant-your-real-key-here
EOF
Crucial — add .env to .gitignore:
echo '.env' >> .gitignore
echo '.env.*' >> .gitignore
If you forget this step and push a key to GitHub, rotate it immediately in the Anthropic console (see "If your key leaks" below). GitHub scans for exposed keys but isn't perfect, and the safest assumption is that a leaked key is already in scrapers' hands.
Loading the key
The Anthropic SDK reads ANTHROPIC_API_KEY from the environment automatically — once it's set, Anthropic() works with no further code. python-dotenv is just the loader that puts the file's contents into the environment.
In a Jupyter notebook, add this as a setup cell at the top:
from dotenv import load_dotenv
load_dotenv()
In a Python script, exactly the same:
from dotenv import load_dotenv
load_dotenv()
from anthropic import Anthropic
client = Anthropic()
# client now has your key
load_dotenv() looks for .env in the current working directory by default. If you launch Jupyter or your script from a different folder, pass the path explicitly:
load_dotenv("/Users/you/projects/notes/.env")
To check the key is loaded, run this in a cell:
import os
print("key set:", bool(os.environ.get("ANTHROPIC_API_KEY")))
# Expected: key set: True
Cost notes — pick the right model for the job
Cost depends on the model. From cheapest to most expensive:
| Model | Use for | Cost per million tokens (rough) |
|---|---|---|
claude-haiku-4-5 | Fast iteration, tutorials, simple tool-use, classification | ~5 out |
claude-sonnet-4-6 | Balanced — most real-world apps | ~15 out |
claude-opus-4-7 | Maximum reasoning quality, hard tasks | ~75 out |
Default to claude-haiku-4-5 while iterating on your own prompts or running batch work — same SDK, same tool-use loop, ~20× cheaper than opus. Reserve claude-opus-4-7 for the moments that actually need its reasoning quality: hard tool-use, agent loops, evaluations, or production code paths where the model's output is the deliverable. A one-off prompt costs well under a cent regardless of model; batch jobs are where the choice matters.
Rough rule of thumb: input tokens are roughly one token per 4 characters of English prose; output tokens are billed at output prices. The Anthropic console shows your real usage in real time.
If your key leaks
If you accidentally commit a key, post it in a screenshot, share a notebook with it embedded, or just suspect anything:
- Go to console.anthropic.com → Settings → API Keys.
- Delete the leaked key. It's invalidated within seconds.
- Generate a new one, update your
.env, restart any running notebooks/scripts so the new key is loaded. - Check your usage history in the console for any unexpected calls.
The only secret you ever store is in .env. The only place that file lives is on your machine. Treat it like an SSH private key.
Troubleshooting common errors
pip: command not found — Your venv isn't activated, or your system has Python without pip. Inside the venv, pip is always available via python3 -m pip as a fallback: python3 -m pip install anthropic.
error: externally-managed-environment — macOS or your distro's Python is enforcing the "no global pip installs" rule. You're running pip against the system Python, not the venv. Run which python — if it doesn't point inside .venv/bin/, your venv isn't activated. source .venv/bin/activate and try again.
ANTHROPIC_API_KEY not set or AuthenticationError — One of:
.envdoesn't exist whereload_dotenv()is looking. Try the explicit-path form.- You launched Jupyter before adding the key. Restart the kernel after editing
.env. - The key string is wrong. Double-check no trailing whitespace, no quotes, starts with
sk-ant-. - The key was deleted in the console. Generate a new one.
SSL: CERTIFICATE_VERIFY_FAILED — Outdated Python on older macOS. Run /Applications/Python\ 3.x/Install\ Certificates.command once, or upgrade Python via brew install [email protected].
RateLimitError — You're hitting your account's rate limit. The error response includes a retry-after header. For tutorial-volume work this almost never happens; if you see it during a batch job, add a small time.sleep(1) between calls or upgrade your account tier.
ConnectionError / Read timed out — Network issue, not key issue. Retry the cell. If persistent, check that api.anthropic.com is reachable from your network.
What you now have
- An activated virtual environment that won't fight with your system Python.
- The Anthropic SDK installed.
- An API key stored in
.env, kept out of git by.gitignore. - A one-line loader (
from dotenv import load_dotenv; load_dotenv()) that picks up the key in any notebook or script. - A clear answer to which model to use for which job, and what to do if a key ever leaks.
Bookmark this page; the next time you start a new Claude API project you'll be set up in under a minute.