◉CLAUDE LABJP
●CC 2.1.332 — In 2.1.332 (11/25), skills from MCP servers show up in the / menu as server:skill (beta)●SONNET 4.5 — Sonnet 4.5 retires from the Claude API on 11/30, 4 days left. Move to claude-sonnet-5-5●/SHIP — Users report a custom ship skill hidden behind the new built-in /ship command●NEW — New: Before Sonnet 4.5 retires, compare the 3 places its answers change●GEMINI 2.5 — Using Gemini 2.5 alongside Claude? From 12/1 requests reroute to newer models at their rates. 5 days left●JETBRAINS — Our guide to using Claude Code from JetBrains IDEs is the most-read page right now●CC 2.1.332 — In 2.1.332 (11/25), skills from MCP servers show up in the / menu as server:skill (beta)●SONNET 4.5 — Sonnet 4.5 retires from the Claude API on 11/30, 4 days left. Move to claude-sonnet-5-5●/SHIP — Users report a custom ship skill hidden behind the new built-in /ship command●NEW — New: Before Sonnet 4.5 retires, compare the 3 places its answers change●GEMINI 2.5 — Using Gemini 2.5 alongside Claude? From 12/1 requests reroute to newer models at their rates. 5 days left●JETBRAINS — Our guide to using Claude Code from JetBrains IDEs is the most-read page right now
Articles/API & SDK
⬡ API & SDK/2026-03-04Intermediate

Claude API Quickstart — Your First API Call in 5 Minutes

Get started with the Claude API. From your API key to your first Python and TypeScript request, plus error handling and cost estimates — a 5-minute quickstart.

API28SDK4Python32TypeScript24Development3

The night I first called the API, I was trying to sort multilingual reviews for my wallpaper app. I pasted a sample, ran it, and got a 404. The cause had nothing to do with setup: I'd copied a model name from an old article.

What I'd tell you first is that your first call is about getting a minimal setup through in the right order. This guide goes from API key to your first Python and TypeScript request in about five minutes, and then covers the two things you hit right after that first success: error handling and a sense of cost.

What is the Claude API?

The Claude API lets you integrate Claude's capabilities into your own applications. Through Anthropic's developer platform, you can programmatically access text generation, code generation, analysis, summarization, and more.

ℹ️
Using the API requires an Anthropic account and an API key. Free credits are provided, so you can start experimenting right away.

Getting Your API Key

  1. Visit console.anthropic.com
  2. Create an account or log in
  3. Navigate to the "API Keys" section and create a new key
  4. Save the key securely (it's only shown once)
# Set as environment variable
export ANTHROPIC_API_KEY="YOUR_API_KEY"

Make one rule non-negotiable from the start: never hardcode the key in source. Reading it from an environment variable keeps it out of accidental commits.

Python SDK

Installation

pip install anthropic

Your First Request

import anthropic
 
client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
 
message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Write a prime number checker in Python"}
    ]
)
 
print(message.content[0].text)

The model string has to match a name from the official model list exactly. A single wrong character returns an error, so this is where most first attempts stall.

Streaming Responses

For real-time output:

with client.messages.stream(
    model="claude-sonnet-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain the basics of machine learning"}
    ]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

TypeScript SDK

Installation

npm install @anthropic-ai/sdk

Your First Request

import Anthropic from "@anthropic-ai/sdk";
 
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment
 
const message = await client.messages.create({
  model: "claude-sonnet-5",
  max_tokens: 1024,
  messages: [
    { role: "user", content: "Implement FizzBuzz in TypeScript" }
  ],
});
 
console.log(message.content[0].text);

Key Parameters

ParameterDescriptionExample
modelModel to useclaude-opus-4-8, claude-sonnet-5
max_tokensMaximum output tokens1024, 4096
temperatureRandomness (0–1)0 = deterministic, 1 = creative
systemSystem prompt"You are a Python expert"
stop_sequencesStop strings (generation halts on a match)["<END>"]

Using System Prompts

message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    system="You are a senior software engineer. Always include code examples and comment on performance.",
    messages=[
        {"role": "user", "content": "What are effective caching strategies?"}
    ]
)
💡
System prompts are a powerful way to consistently control Claude's behavior. Use them for expert personas, standardized output formats, and domain-specific rules.

Minimal Error Handling

Once the first sample works, the next thing you meet is errors. In real use, you only feel safe firing off requests after you've decided how the code behaves when a call fails. The SDK separates exceptions by type, so at minimum, catching rate limits, input errors, and other transport errors separately makes root-cause triage much faster.

import anthropic
 
client = anthropic.Anthropic()
 
try:
    message = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=1024,
        messages=[{"role": "user", "content": "Hello"}],
    )
    print(message.content[0].text)
except anthropic.RateLimitError:
    # 429: wait and retry. Exponential backoff is the standard move
    print("Rate limit hit. Wait a moment and retry.")
except anthropic.BadRequestError as e:
    # 400: wrong model name, max_tokens exceeded — a mistake on your side
    print(f"Bad request: {e}")
except anthropic.APIStatusError as e:
    # Other server-side errors. Branch on status_code
    print(f"API error ({e.status_code}): {e.message}")

What burned me was a review-sorting batch where I swallowed RateLimitError and retried instantly, which only made the throttling worse. I found the half-finished log in the morning and my stomach dropped. Here's the line I draw now:

Treat a 429 as "please wait," not as a failure. Inserting a wait before the retry is what keeps an overnight batch stable, at least in my experience.

Tool Use (Function Calling)

The Claude API supports calling external functions:

message = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=1024,
    tools=[
        {
            "name": "get_weather",
            "description": "Get weather for a given city",
            "input_schema": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "City name (e.g., Tokyo)"
                    }
                },
                "required": ["city"]
            }
        }
    ],
    messages=[
        {"role": "user", "content": "What's the weather in Tokyo?"}
    ]
)

Choosing the Right Model

ModelStrengthsBest For
Claude Opus 4.8Highest capability, deep reasoningComplex analysis, high-quality code
Claude Sonnet 5Balanced speed and qualityEveryday tasks, chatbots
Claude Haiku 4.5Fastest, lowest costHigh-volume processing, classification

For a first build, starting with Sonnet 5 is the natural choice: the balance of speed and quality lets you get a feel for it while iterating. If accuracy falls short, move up to Opus 4.8; if you're running high-volume classification or summarization, drop down to Haiku 4.5. Ship on something, then tune to the workload — in my experience that's the fastest path.

Get a Sense of Cost Early

The API bills per token. Free credits cover your first experiments, but before you put anything into production, it helps to have a feel for the unit price so the bill doesn't surprise you later.

Prices get revised and sometimes carry limited-time rates, so check the official pricing page for the current input and output rates rather than trusting any number in an article. The formula is simple: (input tokens × input rate) + (output tokens × output rate). Try it with 50K input and 10K output tokens and you'll see how heavily the output side weighs.

⚠️
In production, cap `max_tokens` to what you actually need and manage rate limits alongside it. Output tokens cost more than input, so letting long responses run unbounded is where costs tend to balloon.

Pitfalls Right After Your First Call

The most common one is the model-name issue above. Version strings change, so rather than pasting a name from an article or an old sample, confirm the current string in the official docs before you pass it.

Next is max_tokens. It caps the output, not the input length. If a response feels cut off, suspect max_tokens first. Set it too high, though, and you pay for output you didn't need.

Missing environment variables are another classic. Anthropic() auto-discovers ANTHROPIC_API_KEY, but reopening a terminal can wipe the export. When you hit an auth error, the quickest check is echo $ANTHROPIC_API_KEY to confirm the value is actually set.

Next Steps

  • Vision (Image Input) — Analyze and describe images via the API
  • Advanced Tool Use — Automate complex multi-step workflows
  • Batch Processing — Handle large volumes of requests efficiently
  • MCP Integration — Connect services with Model Context Protocol

Run the official minimal sample untouched, then rewrite it into the smallest version of your own use case. Add one piece of error handling, and get a feel for the cost. Follow that order, and the call you got working in five minutes becomes a foundation you can actually ship on.

Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

⬡ API & SDK2026-03-15
Building an AI Chatbot with Claude API — Streaming, Conversation History & Cost Optimization
A record of building a chatbot on the Claude API from a minimal script upward: conversation history, streaming, a FastAPI endpoint, cost trimming, LINE/Telegram/Discord, and PII masking. The retry logic was rebuilt around measured jitter and the retry-after header.
⬡ API & SDK2026-10-14
A 429 With retry-after: 120 Makes the Anthropic SDK Try to Wait 120 Seconds
I ran the Anthropic SDK's automatic retries against a mock server in 12 scenarios. Two retries by default, retry-after obeyed with no cap, and spend-limit 429s that no amount of waiting fixes. Code for a retry wrapper with a wait cap and a time budget, plus the logs.
⬡ API & SDK2026-07-24
When Memory Store Listings Returned Half the Rows: Migrating to agent-memory-2026-07-22
agent-memory-2026-07-22 changed memories.list: fixed ordering, stricter depth, segment-based path_prefix matching. How an audit quietly halved, an access layer that survives it, finding every call site with ast, and measured depth=1 traversal cost.