Getting Started with the Claude API: A Practical Guide for Developers
Learn how to build with Claude using the Messages API, SDKs, and managed agents. Includes code examples, model selection tips, and key capabilities for text, code, and vision tasks.
This guide walks you through setting up the Claude API, making your first API call, understanding the Messages API structure, choosing the right model, and exploring key features like extended thinking, tool use, and vision processing.
Getting Started with the Claude API: A Practical Guide for Developers
Claude by Anthropic is one of the most powerful and developer-friendly AI models available today. Whether you're building a custom chatbot, an agentic coding assistant, or an enterprise workflow automation, the Claude API gives you direct access to frontier intelligence. This guide will take you from zero to a working Claude integration, covering everything you need to know to build production-ready applications.
Why Build with Claude?
Claude offers two primary paths for developers:
- Messages API: Direct model prompting access for custom agent loops and fine-grained control.
- Claude Managed Agents: A pre-built, configurable agent harness that runs on managed infrastructure—ideal for long-running tasks and asynchronous work.
Prerequisites
Before you begin, make sure you have:
- An Anthropic account and API key (get one from the Anthropic Console)
- Python 3.8+ or Node.js 18+ installed
- Basic familiarity with REST APIs and JSON
Step 1: Make Your First API Call
Let's start with the classic "Hello, World!" for the Claude API. We'll use the official Anthropic SDK for Python.
Install the SDK
pip install anthropic
Send Your First Message
Create a file named first_call.py and add the following code:
import anthropic
client = anthropic.Anthropic(
api_key="your-api-key-here" # Replace with your actual API key
)
message = client.messages.create(
model="claude-sonnet-4-20250522",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude! What can you do?"}
]
)
print(message.content[0].text)
Run it:
python first_call.py
You should see a friendly response from Claude explaining its capabilities. Congratulations—you've just made your first Claude API call!
TypeScript Version
If you prefer TypeScript/JavaScript:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: 'your-api-key-here',
});
async function main() {
const message = await client.messages.create({
model: 'claude-sonnet-4-20250522',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude! What can you do?' }],
});
console.log(message.content[0].text);
}
main();
Step 2: Understand the Messages API Structure
The Messages API is the core of Claude's request/response system. Here's what you need to know:
Request Structure
A typical request has these components:
model: The Claude model identifier (e.g.,claude-sonnet-4-20250522)max_tokens: Maximum number of tokens in the responsemessages: An array of message objects, each with arole(userorassistant) andcontentsystem(optional): A system prompt to set Claude's behavior
Multi-Turn Conversations
To continue a conversation, include the full message history:
import anthropic
client = anthropic.Anthropic(api_key="your-api-key")
messages = [
{"role": "user", "content": "What is the capital of France?"},
{"role": "assistant", "content": "The capital of France is Paris."},
{"role": "user", "content": "What is its population?"}
]
response = client.messages.create(
model="claude-sonnet-4-20250522",
max_tokens=256,
messages=messages
)
print(response.content[0].text)
Stop Reasons
Every response includes a stop_reason field that tells you why Claude stopped generating:
"end_turn": Claude finished naturally"max_tokens": The response hit the token limit"stop_sequence": Claude encountered a custom stop sequence"tool_use": Claude wants to call a tool (more on this later)
response = client.messages.create(
model="claude-sonnet-4-20250522",
max_tokens=50,
messages=[{"role": "user", "content": "Tell me a long story"}]
)
print(f"Stop reason: {response.stop_reason}")
print(f"Content: {response.content[0].text}")
Step 3: Choose the Right Model
Claude offers several models optimized for different use cases:
| Model | Best For | Speed | Cost |
|---|---|---|---|
| Claude Opus 4.7 | Complex reasoning, agentic coding, deep analysis | Slower | Higher |
| Claude Sonnet 4.6 | General coding, agents, enterprise workflows | Fast | Medium |
| Claude Haiku 4.5 | Quick tasks, classification, real-time chat | Fastest | Lowest |
claude-sonnet-4-20250522 for most use cases. It offers the best balance of intelligence, speed, and cost. Upgrade to Opus for complex reasoning tasks, or use Haiku for high-volume, low-latency applications.
Step 4: Explore Key Features
Claude's API supports a rich set of features beyond simple text generation. Here are the most important ones:
Extended Thinking
For complex reasoning tasks, enable Claude's extended thinking capability:
response = client.messages.create(
model="claude-sonnet-4-20250522",
max_tokens=2048,
thinking={"type": "enabled", "budget_tokens": 1024},
messages=[
{"role": "user", "content": "Solve this step by step: If a train leaves Station A at 60 mph and another leaves Station B at 80 mph, 200 miles apart, when do they meet?"}
]
)
print(response.content[0].text)
Structured Outputs
Get Claude to return JSON or other structured formats:
response = client.messages.create(
model="claude-sonnet-4-20250522",
max_tokens=1024,
messages=[
{"role": "user", "content": "Extract the following information as JSON: name, age, and occupation from this text: 'John is a 35-year-old software engineer.'"}
]
)
print(response.content[0].text)
Vision (Image Processing)
Claude can analyze images and generate text from them:
import base64
with open("chart.png", "rb") as image_file:
image_data = base64.b64encode(image_file.read()).decode("utf-8")
response = client.messages.create(
model="claude-sonnet-4-20250522",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Describe this chart in detail."},
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data
}
}
]
}
]
)
print(response.content[0].text)
Tool Use (Function Calling)
Claude can call external tools and APIs. Here's a simple example with a weather tool:
def get_weather(location: str) -> str:
# In production, call a real weather API
return f"The weather in {location} is sunny, 72°F."
response = client.messages.create(
model="claude-sonnet-4-20250522",
max_tokens=1024,
tools=[
{
"name": "get_weather",
"description": "Get the current weather for a location",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g., San Francisco"
}
},
"required": ["location"]
}
}
],
messages=[
{"role": "user", "content": "What's the weather like in Tokyo?"}
]
)
Check if Claude wants to use a tool
if response.stop_reason == "tool_use":
tool_call = response.content[1] # The tool_use block
if tool_call.name == "get_weather":
result = get_weather(tool_call.input["location"])
print(f"Tool result: {result}")
else:
print(response.content[0].text)
Step 5: Use Developer Tools
Anthropic provides several tools to accelerate your development:
- Developer Console: Prototype and test prompts in your browser with the Workbench and prompt generator.
- API Reference: Full documentation for the Claude API and client SDKs.
- Claude Cookbook: Interactive Jupyter notebooks covering PDFs, embeddings, and more.
Best Practices for Production
- Handle errors gracefully: Always wrap API calls in try/except blocks and handle rate limits.
- Use streaming for real-time apps: Enable
stream=Truein your API call to receive tokens as they're generated. - Implement retry logic: Use exponential backoff for transient failures.
- Monitor token usage: Track input and output tokens to manage costs.
- Cache common responses: Use prompt caching for frequently used system prompts.
Key Takeaways
- The Claude API offers two paths: the Messages API for full control and Managed Agents for hands-off deployment.
- Start with Claude Sonnet 4.6 for the best balance of performance and cost, then scale up to Opus or down to Haiku as needed.
- Master the Messages API structure—especially multi-turn conversations and stop reasons—to build robust applications.
- Leverage advanced features like extended thinking, structured outputs, vision, and tool use to unlock Claude's full potential.
- Use Anthropic's Developer Console and Cookbook to prototype faster and learn best practices.