How Do I Use the Claude API?

Install the SDK (pip install anthropic for Python), set your API key from console.anthropic.com, and call client.messages.create() with model, max_tokens, and messages parameters. The minimum working code is about 8 lines.

Step 1: Get an API Key

  1. Go to console.anthropic.com
  2. Create an account or sign in
  3. Navigate to API Keys and create a new key
  4. Set it as an environment variable: export ANTHROPIC_API_KEY="sk-ant-..."

Step 2: Python Quick-Start

# Install: pip install anthropic
import anthropic

client = anthropic.Anthropic()  # uses ANTHROPIC_API_KEY env var

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

print(message.content[0].text)

Step 3: Python Streaming

import anthropic

client = anthropic.Anthropic()

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

JavaScript (fetch) Example

const response = await fetch('https://api.anthropic.com/v1/messages', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'x-api-key': process.env.ANTHROPIC_API_KEY,
    'anthropic-version': '2023-06-01'
  },
  body: JSON.stringify({
    model: 'claude-sonnet-4-20250514',
    max_tokens: 1024,
    messages: [
      { role: 'user', content: 'Explain recursion in one paragraph.' }
    ]
  })
});

const data = await response.json();
console.log(data.content[0].text);

API Pricing

Model Input (1M tokens) Output (1M tokens)
Claude 3 Haiku $0.25 $1.25
Claude 3.5 Sonnet $3.00 $15.00
Claude 3 Opus $15.00 $75.00

Key Parameters

Find ready-to-use prompts for the Claude API in the ClaudHQ prompt library, or use ClaudKit for a visual API request builder.

Related Questions