Getting Started with Claude API: A Practical Guide for Developers
Learn how to build with Claude API from scratch. Covers setup, Messages API, model selection, and key features like extended thinking and tool use.
This guide walks you through setting up the Claude API, making your first call, understanding the Messages API, choosing the right model, and exploring advanced features like tool use and extended thinking.
Getting Started with Claude API: A Practical Guide for Developers
Claude by Anthropic is one of the most capable AI models available today, and its API gives developers direct access to its powerful reasoning, coding, and multimodal capabilities. Whether you're building a custom chatbot, an agentic coding assistant, or an enterprise workflow, the Claude API provides the flexibility and control you need.
This guide covers everything you need to go from zero to a working Claude integration—including setup, core API concepts, model selection, and advanced features.
Prerequisites
Before you start, you'll need:
- An Anthropic account
- An API key (generated from the Console)
- Python 3.8+ or Node.js 18+ installed
Step 1: Make Your First API Call
Let's start by setting up your environment and sending your first message to Claude.
Install the SDK
Python:pip install anthropic
TypeScript/JavaScript:
npm install @anthropic-ai/sdk
Set Your API Key
Set your API key as an environment variable:
export ANTHROPIC_API_KEY="sk-ant-..."
Send Your First Message
Here's a minimal working example in Python:
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude! What can you do?"}
]
)
print(message.content[0].text)
TypeScript equivalent:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
async function main() {
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude! What can you do?' }]
});
console.log(message.content[0].text);
}
main();
If everything works, you'll see Claude's friendly response printed in your terminal.
Step 2: Understand the Messages API
The Messages API is the core interface for interacting with Claude. It supports:
- Multi-turn conversations – Send a list of messages to maintain context
- System prompts – Set the assistant's behavior and persona
- Stop reasons – Understand why Claude stopped generating (e.g.,
end_turn,max_tokens,stop_sequence)
Basic Request Structure
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system="You are a helpful coding assistant. Keep answers concise.",
messages=[
{"role": "user", "content": "Write a Python function to reverse a string."},
{"role": "assistant", "content": "Here's a simple function:\n\ndef reverse_string(s):\n return s[::-1]"},
{"role": "user", "content": "Can you explain how that works?"}
]
)
Handling Stop Reasons
Always check the stop_reason to understand why Claude finished:
if response.stop_reason == "end_turn":
print("Claude finished naturally.")
elif response.stop_reason == "max_tokens":
print("Response was cut off. Consider increasing max_tokens.")
elif response.stop_reason == "stop_sequence":
print("Claude hit a custom stop sequence.")
Step 3: Choose the Right Model
Anthropic offers several Claude models optimized for different use cases:
| Model | Best For | Cost |
|---|---|---|
| Claude Opus 4.7 | Complex reasoning, agentic coding, research | Highest |
| Claude Sonnet 4.6 | Coding, agents, enterprise workflows | Medium |
| Claude Haiku 4.5 | Fast responses, simple tasks, high throughput | Lowest |
Step 4: Explore Key Features
Claude's API supports a rich set of features that go beyond simple text generation.
Extended Thinking
Enable Claude to "think" before responding, improving reasoning on complex tasks:
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
thinking={"type": "enabled", "budget_tokens": 1024},
messages=[
{"role": "user", "content": "Solve this math problem step by step: 15 * 27 + 8"}
]
)
Structured Outputs
Get Claude to return JSON or other structured formats reliably:
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "List three programming languages and their use cases as JSON."}
],
response_format={"type": "json_object"}
)
Tool Use (Function Calling)
Give Claude the ability to call external tools and APIs:
tools = [
{
"name": "get_weather",
"description": "Get current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
]
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in Tokyo?"}
]
)
Streaming Responses
For real-time applications, stream responses token by token:
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "Write a short poem about AI."}
]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Vision (Image Processing)
Claude can analyze images and generate text from them:
import base64
with open("chart.png", "rb") as f:
image_data = base64.b64encode(f.read()).decode("utf-8")
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What does this chart show?"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image_data}}
]
}
]
)
Step 5: Build with Developer Tools
Anthropic provides several tools to accelerate development:
- Developer Console – Prototype and test prompts with the Workbench and prompt generator
- API Reference – Full documentation for the API and SDKs
- Claude Cookbook – Interactive Jupyter notebooks covering PDFs, embeddings, and more
Best Practices
- Set appropriate max_tokens – Avoid truncation by setting a value that matches your expected response length.
- Use system prompts – Define Claude's role and constraints clearly.
- Handle errors gracefully – Implement retries with exponential backoff for rate limits.
- Monitor token usage – Track input and output tokens to manage costs.
- Leverage prompt caching – Reduce latency and cost for repeated system prompts or large contexts.
Next Steps
Now that you have a working Claude integration, explore more advanced capabilities:
- Build a tool-using agent with the Tool Use guide
- Implement batch processing for high-throughput tasks
- Use prompt caching to optimize performance
- Explore MCP (Model Context Protocol) for connecting Claude to external data sources
Key Takeaways
- Start with the Messages API – It's the core interface for all Claude interactions, supporting multi-turn conversations, system prompts, and structured outputs.
- Choose your model wisely – Sonnet 4.6 is the best all-rounder; Opus for complex reasoning; Haiku for speed and cost efficiency.
- Leverage advanced features – Extended thinking, tool use, streaming, and vision unlock powerful use cases beyond simple chat.
- Use the developer tools – The Console, Cookbook, and API reference streamline prototyping and debugging.
- Follow best practices – Set appropriate token limits, handle stop reasons, and implement error handling for production-ready applications.