Getting Started with the Claude API: A Practical Guide for Developers
Learn how to build with the Claude API from scratch. Covers setup, Messages API, model selection, key features like extended thinking and tool use, and best practices for production.
This guide walks you through setting up the Claude API, making your first call with the Messages API, choosing the right model, and exploring key capabilities like tool use, extended thinking, and structured outputs.
Introduction
Anthropic's Claude API gives developers direct access to the latest Claude models—Claude Opus 4.7, Claude Sonnet 4.6, and Claude Haiku 4.5—for building custom AI-powered applications. Whether you're creating a coding assistant, a customer support bot, or an agent that can browse the web and run code, the API provides the flexibility and control you need.
This guide covers everything you need to go from zero to a working Claude integration. You'll learn how to set up your environment, make your first API call, understand the Messages API structure, choose the right model, and explore advanced features like tool use and extended thinking.
Prerequisites
Before you begin, make sure you have:
- An Anthropic account and an API key from the Developer Console
- Python 3.8+ or Node.js 18+ installed
- Basic familiarity with REST APIs and JSON
Step 1: Make Your First API Call
Install the SDK
Anthropic provides official SDKs for Python and TypeScript. Install the one for your language:
Pythonpip install anthropic
TypeScript
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 the simplest possible API call—a single-turn text generation:
Pythonimport anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude!"}
]
)
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-20250514',
max_tokens: 1024,
messages: [
{ role: 'user', content: 'Hello, Claude!' }
]
});
console.log(message.content[0].text);
}
main();
You should receive a friendly greeting from Claude. Congratulations—you've made your first API call!
Step 2: Understand the Messages API
The Messages API is the core interface for interacting with Claude. Every request follows a consistent structure:
Request Structure
model(required): The model identifier (e.g.,claude-sonnet-4-20250514)max_tokens(required): Maximum number of tokens in the responsemessages(required): An array of message objects, each withroleandcontentsystem(optional): A system prompt to set Claude's behaviortemperature(optional): Controls randomness (0.0 to 1.0)
Multi-Turn Conversations
To continue a conversation, simply append new messages to the messages array:
messages = [
{"role": "user", "content": "What is the capital of France?"},
{"role": "assistant", "content": "The capital of France is Paris."},
{"role": "user", "content": "Tell me more about its history."}
]
Stop Reasons
Every response includes a stop_reason field that tells you why Claude stopped generating:
"end_turn": Claude finished naturally"max_tokens": Claude hit the token limit"stop_sequence": Claude encountered a custom stop sequence"tool_use": Claude wants to call a tool (more on this later)
Step 3: Choose the Right Model
Claude offers three model tiers, each optimized for different use cases:
| Model | Best For | Speed | Cost |
|---|---|---|---|
| Claude Opus 4.7 | Complex reasoning, agentic coding, research | Slowest | Highest |
| Claude Sonnet 4.6 | General coding, agents, enterprise workflows | Fast | Moderate |
| Claude Haiku 4.5 | High-throughput, real-time apps, simple tasks | Fastest | Lowest |
Step 4: Explore Key Features
Extended Thinking
For complex reasoning tasks, enable extended thinking to let Claude "think" before responding. This is especially useful for math, logic puzzles, and multi-step analysis.
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
thinking={"type": "enabled", "budget_tokens": 1024},
messages=[
{"role": "user", "content": "Solve this: A bat and a ball cost $1.10. The bat costs $1.00 more than the ball. How much does the ball cost?"}
]
)
Tool Use (Function Calling)
Claude can call external tools to fetch data, run code, or perform actions. Define tools in your request, and Claude will request tool calls when needed.
tools = [
{
"name": "get_weather",
"description": "Get the current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"units": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
]
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in Tokyo?"}
]
)
Check if Claude wants to use a tool
if message.stop_reason == "tool_use":
tool_call = message.content[1] # The tool use block
print(f"Claude wants to call: {tool_call.name}")
print(f"With arguments: {tool_call.input}")
Structured Outputs
For production applications, you often need structured data (JSON) instead of free text. Use the structured_outputs parameter to enforce a schema:
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "Extract the name, date, and amount from this invoice: 'Invoice #1234 - John Doe - $500 - Due 2025-06-01'"}
],
structured_outputs={
"type": "json_schema",
"json_schema": {
"name": "invoice",
"strict": True,
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"date": {"type": "string"},
"amount": {"type": "number"}
},
"required": ["name", "date", "amount"]
}
}
}
)
print(message.content[0].text)
Output: {"name": "John Doe", "date": "2025-06-01", "amount": 500.0}
Streaming
For real-time user experiences, stream Claude's response token by token:
stream = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a short poem about AI."}],
stream=True
)
for event in stream:
if event.type == "content_block_delta":
print(event.delta.text, end="", flush=True)
Step 5: Build with Developer Tools
Anthropic provides several tools to accelerate development:
- Developer Console: Prototype 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 PDF processing, embeddings, and more.
Best Practices for Production
- Handle errors gracefully: Implement retry logic with exponential backoff for rate limits and transient errors.
- Use prompt caching: Cache system prompts and long context to reduce latency and cost.
- Monitor token usage: Track input and output tokens to stay within budget.
- Set appropriate max_tokens: Avoid truncation by setting
max_tokenshigh enough for your use case. - Validate structured outputs: Always parse and validate JSON responses before using them.
Conclusion
The Claude API gives you direct access to frontier AI models with fine-grained control over behavior, output format, and tool integration. Start with the quickstart to make your first call, then explore features like tool use and extended thinking as your application grows.
For more advanced topics, check out the Claude Managed Agents for long-running tasks, or dive into the MCP connector for integrating with external services.
Key Takeaways
- The Claude API uses a simple Messages API structure with
model,max_tokens, andmessagesas required fields. - Choose Claude Sonnet 4.6 for general use, Claude Opus 4.7 for complex reasoning, and Claude Haiku 4.5 for high-throughput tasks.
- Enable tool use to let Claude call external functions, and structured outputs to get reliable JSON responses.
- Streaming provides real-time token-by-token output for better user experiences.
- Start with the quickstart in the Developer Console, then explore the Cookbook and API reference for deeper learning.