enAPI

API Reference

Complete reference for the Claude API.

Overview

The Claude API allows you to integrate Claude’s capabilities into your applications. This guide covers authentication, making requests, and handling responses.

Authentication

All API requests require an API key. Get your API key from the Anthropic Console.

export ANTHROPIC_API_KEY='your-api-key-here'

Quick Start

Python

import anthropic
 
client = anthropic.Anthropic(
    api_key="your-api-key-here",
)
 
message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Hello, Claude!"}
    ]
)
 
print(message.content)

JavaScript

import Anthropic from "@anthropic-ai/sdk";
 
const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});
 
const message = await client.messages.create({
  model: "claude-3-5-sonnet-20241022",
  max_tokens: 1024,
  messages: [
    { role: "user", content: "Hello, Claude!" }
  ]
});
 
console.log(message.content);

Available Models

ModelDescriptionContext Window
claude-3-5-sonnet-20241022Latest and most capable model200K tokens
claude-3-opus-20240229High intelligence for complex tasks200K tokens
claude-3-haiku-20240307Fast and cost-effective200K tokens

Key Concepts

Messages API

The Messages API is the primary way to interact with Claude.

Request Parameters

  • model (string, required): The model to use
  • messages (array, required): Array of message objects
  • max_tokens (integer, required): Maximum tokens to generate
  • temperature (float, optional): Randomness in responses (0-1)
  • system (string, optional): System prompt to guide behavior

Response Format

{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hello! How can I help you today?"
    }
  ],
  "model": "claude-3-5-sonnet-20241022",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 12,
    "output_tokens": 25
  }
}

Advanced Features

Streaming

Enable streaming for real-time responses:

with client.messages.stream(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello!"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Vision

Claude can analyze images:

message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/jpeg",
                        "data": "/9j/4AAQSkZJRg...",
                    },
                },
                {
                    "type": "text",
                    "text": "What's in this image?"
                }
            ],
        }
    ],
)

Tool Use

Enable Claude to use tools and functions:

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

Best Practices

  1. Rate Limiting: Implement proper rate limiting and retry logic
  2. Error Handling: Handle API errors gracefully
  3. Token Management: Monitor token usage to optimize costs
  4. Caching: Cache responses when appropriate
  5. Security: Never expose API keys in client-side code

Rate Limits

TierRequests per minuteTokens per minute
Free5040,000
Pro1,000400,000
EnterpriseCustomCustom

Error Handling

Common error codes:

  • 400: Invalid request
  • 401: Authentication error
  • 403: Permission denied
  • 429: Rate limit exceeded
  • 500: Server error
try:
    message = client.messages.create(...)
except anthropic.APIError as e:
    print(f"API error: {e}")
except anthropic.RateLimitError as e:
    print(f"Rate limit exceeded: {e}")

Resources

Need Help?