You want to build something with Claude. Great. In this article, you will create an Anthropic account, get an API key, install the SDK, and make your first API call — in both Python and TypeScript.

This is Article 2 in the Claude AI — From Zero to Power User series. If you are new to Claude, start with Article 1: What is Claude?.

By the end of this article, you will have a working Claude API setup and understand how tokens, pricing, and error handling work.


Step 1: Create an Anthropic Account

Go to console.anthropic.com and create an account. You can sign up with an email address or Google account.

After signing up, you land on the Anthropic Console. This is where you manage API keys, view usage, and check billing.


Step 2: Get an API Key

  1. In the Console, go to API Keys in the left sidebar.
  2. Click Create Key.
  3. Give it a name (for example, “claude-tutorial”).
  4. Copy the key immediately. You will not see it again.

Your API key looks like this: sk-ant-api03-...

Important: Never commit your API key to git. Never share it publicly. We will set it as an environment variable in the next step.


Step 3: Set Your API Key as an Environment Variable

The safest way to use your API key is as an environment variable.

macOS / Linux:

export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"

To make this permanent, add it to your shell profile:

echo 'export ANTHROPIC_API_KEY="sk-ant-api03-your-key-here"' >> ~/.zshrc
source ~/.zshrc

Windows (PowerShell):

$env:ANTHROPIC_API_KEY = "sk-ant-api03-your-key-here"

Both the Python and TypeScript SDKs automatically read the ANTHROPIC_API_KEY environment variable. You do not need to pass it in code.


Step 4: Install the SDK

Python

Requires Python 3.8 or later.

pip install anthropic

Or with a virtual environment (recommended):

python -m venv claude-env
source claude-env/bin/activate  # macOS/Linux
pip install anthropic

TypeScript

Requires Node.js 18 or later.

npm install @anthropic-ai/sdk

Or create a new project:

mkdir claude-tutorial && cd claude-tutorial
npm init -y
npm install @anthropic-ai/sdk typescript tsx

Step 5: Your First API Call

Let’s send a simple message to Claude and get a response.

Python

import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "What is the capital of France?"}
    ]
)

print(message.content[0].text)

Save this as hello_claude.py and run it:

python hello_claude.py

Output:

The capital of France is Paris.

TypeScript

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

async function main() {
  const message = await client.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: 1024,
    messages: [
      { role: "user", content: "What is the capital of France?" }
    ],
  });

  if (message.content[0].type === "text") {
    console.log(message.content[0].text);
  }
}

main();

Save this as hello_claude.ts and run it:

npx tsx hello_claude.ts

Output:

The capital of France is Paris.

Both examples use Sonnet 4.6, the balanced model. You can change the model parameter to claude-opus-4-6 or claude-haiku-4-5 to use different models.


Understanding the Response

The API returns a response object with useful information. Let’s print the full response:

Python

import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "What is 2 + 2?"}
    ]
)

print(f"ID: {message.id}")
print(f"Model: {message.model}")
print(f"Role: {message.role}")
print(f"Stop reason: {message.stop_reason}")
print(f"Input tokens: {message.usage.input_tokens}")
print(f"Output tokens: {message.usage.output_tokens}")
print(f"Content: {message.content[0].text}")

TypeScript

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

async function main() {
  const message = await client.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: 1024,
    messages: [
      { role: "user", content: "What is 2 + 2?" }
    ],
  });

  console.log(`ID: ${message.id}`);
  console.log(`Model: ${message.model}`);
  console.log(`Role: ${message.role}`);
  console.log(`Stop reason: ${message.stop_reason}`);
  console.log(`Input tokens: ${message.usage.input_tokens}`);
  console.log(`Output tokens: ${message.usage.output_tokens}`);

  if (message.content[0].type === "text") {
    console.log(`Content: ${message.content[0].text}`);
  }
}

main();

Example output:

ID: msg_01XFDUDYJgAACzvnptvVoYEL
Model: claude-sonnet-4-6
Role: assistant
Stop reason: end_turn
Input tokens: 14
Output tokens: 12
Content: 2 + 2 equals 4.

Here is what each field means:

FieldDescription
idUnique message ID
modelThe model that generated the response
roleAlways assistant for responses
stop_reasonWhy the model stopped: end_turn (finished), max_tokens (hit limit), tool_use (wants to call a tool)
usage.input_tokensHow many tokens your prompt used
usage.output_tokensHow many tokens the response used
contentArray of content blocks (usually one text block)

Understanding Tokens and Cost

Tokens are the units Claude uses to process text. One token is roughly 3-4 characters in English. A typical English word is 1-2 tokens.

Quick estimates:

  • “Hello, world!” = about 4 tokens
  • A 500-word article = about 700 tokens
  • A 1000-line code file = about 3000 tokens

How to Calculate Cost

Claude charges per million tokens. For Sonnet 4.6:

  • Input: $3.00 per million tokens
  • Output: $15.00 per million tokens

Our “What is the capital of France?” example used about 14 input tokens and 12 output tokens. The cost:

Input:  14 tokens × ($3.00 / 1,000,000) = $0.000042
Output: 12 tokens × ($15.00 / 1,000,000) = $0.000180
Total:  $0.000222

That is less than $0.001. You can make thousands of simple API calls for just a few cents.

Cost by Model

ModelInput ($/MTok)Output ($/MTok)Simple call cost
Opus 4.6$5.00$25.00~$0.0004
Sonnet 4.6$3.00$15.00~$0.0002
Haiku 4.5$1.00$5.00~$0.00007

We will cover cost optimization in detail in Article 4: Understanding Models.


API Tiers

Anthropic uses a tier system that controls your rate limits. Higher tiers give you more requests per minute:

TierDepositRequests/min (Sonnet)Tokens/min (Sonnet)
Tier 1$55040,000
Tier 2$401,00080,000
Tier 3$2002,000160,000
Tier 4$400+4,000400,000

Tier 4 also unlocks the 1M token context window (beta) for Opus 4.6 and Sonnet 4.6. Most developers start at Tier 1 and move up as they need more capacity.


Error Handling

The API can return errors. Here is how to handle the most common ones:

Python

import anthropic

client = anthropic.Anthropic()

try:
    message = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=[
            {"role": "user", "content": "Hello, Claude!"}
        ]
    )
    print(message.content[0].text)

except anthropic.AuthenticationError:
    print("Invalid API key. Check your ANTHROPIC_API_KEY.")

except anthropic.RateLimitError:
    print("Rate limit hit. Wait a moment and try again.")

except anthropic.APIStatusError as e:
    print(f"API error: {e.status_code} - {e.message}")

TypeScript

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

async function main() {
  try {
    const message = await client.messages.create({
      model: "claude-sonnet-4-6",
      max_tokens: 1024,
      messages: [
        { role: "user", content: "Hello, Claude!" }
      ],
    });

    if (message.content[0].type === "text") {
      console.log(message.content[0].text);
    }
  } catch (error) {
    if (error instanceof Anthropic.AuthenticationError) {
      console.error("Invalid API key. Check your ANTHROPIC_API_KEY.");
    } else if (error instanceof Anthropic.RateLimitError) {
      console.error("Rate limit hit. Wait a moment and try again.");
    } else if (error instanceof Anthropic.APIError) {
      console.error(`API error: ${error.status} - ${error.message}`);
    }
  }
}

main();

Common Error Codes

CodeErrorWhat to Do
401Authentication errorCheck your API key
400Invalid requestCheck your parameters (model name, max_tokens, messages format)
429Rate limitWait and retry. Consider upgrading your tier
500Server errorRetry after a short delay
529OverloadedClaude is temporarily overloaded. Retry with backoff

The SDKs have built-in retry logic for 429 and 500 errors. By default, they retry up to 2 times with exponential backoff.


Using a System Prompt

A system prompt tells Claude how to behave. Add it as a separate parameter:

Python

import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system="You are a helpful coding assistant. Always include code examples in your answers.",
    messages=[
        {"role": "user", "content": "How do I read a file in Python?"}
    ]
)

print(message.content[0].text)

TypeScript

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

async function main() {
  const message = await client.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: 1024,
    system: "You are a helpful coding assistant. Always include code examples in your answers.",
    messages: [
      { role: "user", content: "How do I read a file in Python?" }
    ],
  });

  if (message.content[0].type === "text") {
    console.log(message.content[0].text);
  }
}

main();

We will cover system prompts in depth in Article 5: Prompt Engineering Basics.


Direct API vs AWS Bedrock vs Google Vertex AI

You can access Claude through three platforms:

PlatformBest ForSetup
Anthropic API (direct)Most developers, startupsAPI key from console.anthropic.com
AWS BedrockTeams already on AWSAWS account, IAM setup
Google Vertex AITeams already on Google CloudGCP project, service account

For this tutorial series, we use the direct Anthropic API. The code is nearly identical for Bedrock and Vertex — you just change the client initialization.


Summary

In this article, you:

  1. Created an Anthropic account and got an API key
  2. Set the API key as an environment variable
  3. Installed the Python and TypeScript SDKs
  4. Made your first API call
  5. Learned about the response object, tokens, and pricing
  6. Added error handling
  7. Used a system prompt

Cost of everything in this article: Less than $0.01.


What’s Next?

In the next article, we will set up Claude Code — the terminal-native AI coding assistant. You will learn how to install it, configure it, and use it to work with your codebase.

Next: Claude Code CLI — Installation, Setup, and First Commands