Lesson 02 Claude API Setup & First Calls
Theme:
Lesson 02 · Slide 1

Claude API Setup & First Calls

From zero to your first real API response in under 30 minutes. We'll cover authentication, the SDK, and the core Messages API pattern.

Learning Objectives

Lesson 02 · Slide 2

Getting Your API Key

API keys authenticate your requests and link usage to your billing account. Never commit them to version control.

Steps

  1. Visit console.anthropic.com and sign in or create an account
  2. Navigate to API Keys in the left sidebar
  3. Click Create Key, give it a descriptive name (e.g. "dev-laptop")
  4. Copy the key immediately — it won't be shown again
  5. Store it in a .env file at your project root

.env Pattern

# .env  (never commit this file — add it to .gitignore)
ANTHROPIC_API_KEY=sk-ant-api03-...

# .env.example  (safe to commit — shows structure without secrets)
ANTHROPIC_API_KEY=your_api_key_here

Security rule: add .env to your .gitignore immediately. Exposed keys should be rotated on the console within minutes.

Lesson 02 · Slide 3

SDK Install & Project Setup

pip install anthropic python-dotenv tiktoken

Recommended Project Structure

my-project/
├── .env              # secrets (gitignored)
├── .env.example      # template (committed)
├── .gitignore
├── requirements.txt
├── demo/
│   └── first_call.py
└── notebooks/
    └── explore.pdf

Client Initialisation

import anthropic
from dotenv import load_dotenv

load_dotenv()  # loads ANTHROPIC_API_KEY from .env

client = anthropic.Anthropic()
# The SDK auto-reads ANTHROPIC_API_KEY from the environment
Notes: The SDK raises anthropic.AuthenticationError if the key is missing or invalid — easy to diagnose in the terminal.
Lesson 02 · Slide 4

The Messages API

All calls go through client.messages.create(). Here is a minimal but complete request:

message = client.messages.create(
    model="claude-haiku-4-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain recursion in one paragraph."}
    ]
)

print(message.content[0].text)

Key Response Fields

FieldTypeDescription
contentlist[ContentBlock]The model's reply — access text via .content[0].text
usage.input_tokensintTokens in your prompt (billed)
usage.output_tokensintTokens in the response (billed)
stop_reasonstr"end_turn", "max_tokens", or "tool_use"
modelstrExact model version used
Lesson 02 · Slide 5

Model Selection

Anthropic offers a tiered family. Choose based on your latency, cost, and capability requirements.

ModelSpeedCost tierBest use case
claude-haiku-4-5Fastest$Classification, triage, simple Q&A, high-volume pipelines
claude-sonnet-4-5Fast$$Drafting, analysis, coding tasks, most production workloads
claude-opus-4-5Slower$$$$Complex reasoning, nuanced writing, tasks needing maximum accuracy

Tip: Start prototyping with Haiku to keep costs low, then benchmark against Sonnet/Opus only where quality matters. Many tasks never need Opus.

Notes: Pricing changes — always check anthropic.com/pricing for current numbers. The cost-per-token difference between Haiku and Opus is roughly 60×.
Lesson 02 · Slide 6

Streaming Responses

For long outputs or real-time UX, streaming lets you display tokens as they arrive rather than waiting for the full response.

Why Stream?

with client.messages.stream(
    model="claude-haiku-4-5",
    max_tokens=512,
    messages=[{"role": "user", "content": "Write a haiku about APIs."}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

# After the loop, access usage:
final_message = stream.get_final_message()
print(f"\nInput tokens:  {final_message.usage.input_tokens}")
print(f"Output tokens: {final_message.usage.output_tokens}")
Notes: Run demo/first_call.py, show basic then streaming, point out token counts in the final message object.
Lesson 02 · Slide 7

Demo

Live walkthrough using demo/first_call.py.

Demo Steps

  1. Verify .env is present — check with print(os.environ.get("ANTHROPIC_API_KEY", "MISSING")[:8])
  2. Run a basic (non-streaming) call; inspect the full response object in the REPL
  3. Note usage.input_tokens and usage.output_tokens
  4. Switch to streaming mode; watch tokens arrive in the terminal in real time
  5. Try changing max_tokens to 10 — observe stop_reason="max_tokens"
Notes: Run demo/first_call.py, show basic then streaming, point out token counts. Students should follow along in their own terminals.

📥 Demo Files

⬇ first_call.py
Lesson 02 · Slide 8

Lab & Homework

Lab Exercises

  1. First Call — make a working API call; print the response text and both token counts
  2. Multi-turn Conversation — build a 3-turn conversation by appending assistant and user messages to the messages list; observe how context accumulates
  3. Model Comparison — send the same complex prompt to Haiku and Sonnet; time the response and compare quality

Homework Tasks

  1. Read the Anthropic API docs on rate limits. What are the tier-1 limits for requests/minute and tokens/minute? How would you implement exponential back-off in Python?
  2. Implement a cost_estimator(prompt: str, model: str) -> float function that uses tiktoken to estimate the cost of a call before making it.
  3. Explore the system parameter of messages.create. Write a system prompt that makes the model always respond in bullet points, then test it with 3 different user messages.
1 / ?