Your First Steps with the Claude API: From Setup to Production
Learn how to integrate Claude into your applications using the Messages API and Managed Agents. This guide covers API keys, SDKs, code examples, and best practices for production.
This guide walks you through getting an API key, installing the Python SDK, making your first API call, and choosing between the Messages API and Managed Agents for your use case.
Introduction
Claude isn't just a chatbot—it's a powerful API that you can integrate into your own applications, workflows, and products. Whether you're building a customer support bot, a code assistant, or a content generation tool, the Claude API gives you direct access to the same models that power claude.ai.
This guide will take you from zero to your first production-ready API call. You'll learn how to get your API key, install the SDK, write your first message, and understand the two main development surfaces: Messages API and Managed Agents.
By the end, you'll have a working Claude integration and a clear path to scaling it up.
Prerequisites
Before you start, make sure you have:
- A Claude API account (sign up is free)
- Python 3.7+ installed on your machine
- Basic familiarity with Python or TypeScript
- A terminal or command prompt
Step 1: Get Your API Key
Your API key is the credential that authenticates your requests to Claude. Keep it secret—anyone with your key can use your account.
- Go to the Anthropic Console
- Navigate to API Keys in the sidebar
- Click Create Key
- Copy the key immediately (you won't see it again)
- Store it securely (e.g., in a
.envfile or environment variable)
Security tip: Never hardcode your API key in source code. Use environment variables or a secrets manager.
Step 2: Choose Your Model
Claude comes in several flavors. For most beginners, Claude Sonnet 4.6 (claude-sonnet-4-6) is the sweet spot—intelligent enough for complex tasks, fast enough for real-time use.
| Model | ID | Best For |
|---|---|---|
| Opus 4.7 | claude-opus-4-7 | Deep reasoning, complex analysis, coding |
| Sonnet 4.6 | claude-sonnet-4-6 | General production workloads, balance of speed and smarts |
| Haiku 4.5 | claude-haiku-4-5 | High-volume, latency-sensitive apps |
Step 3: Install the SDK
Anthropic provides official SDKs for Python, TypeScript, Go, Java, Ruby, PHP, and C#. We'll use Python.
Open your terminal and run:
pip install anthropic
If you're using TypeScript:
npm install @anthropic-ai/sdk
Step 4: Make Your First API Call
Create a new Python file called hello_claude.py and add the following code:
import anthropic
Initialize the client with your API key
client = anthropic.Anthropic(
api_key="YOUR_API_KEY_HERE" # Replace with your actual key
)
Send a message
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude!"}
]
)
Print the response
print(message.content[0].text)
Run it:
python hello_claude.py
You should see Claude's greeting printed to your terminal. Congratulations—you've just made your first API call!
Understanding the Code
client.messages.create()is the core method for sending messagesmodelspecifies which Claude model to usemax_tokenslimits the length of the responsemessagesis an array of conversation turns. Each turn has arole(userorassistant) andcontent- The response is a
Messageobject;content[0].textgives you the text reply
Step 5: Build a Multi-Turn Conversation
Claude is stateless by default—each API call is independent. To have a conversation, you need to send the entire history with each request.
import anthropic
client = anthropic.Anthropic(api_key="YOUR_API_KEY_HERE")
Start the conversation
conversation = [
{"role": "user", "content": "What is the capital of France?"}
]
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
messages=conversation
)
Add Claude's response to the history
conversation.append({"role": "assistant", "content": response.content[0].text})
Ask a follow-up
conversation.append({"role": "user", "content": "What is the population of that city?"})
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
messages=conversation
)
print(response.content[0].text)
This pattern—maintaining a conversation history array and sending it with each request—is the foundation of all chat applications built on Claude.
Step 6: Choose Your Development Surface
Claude offers two main ways to build:
Messages API (Direct Model Access)
You control everything: you construct every turn, manage conversation state, and write your own tool loop. This gives you maximum flexibility.
Best for: Custom applications, complex workflows, when you need fine-grained control.Managed Agents
Anthropic handles the infrastructure. You define an agent with instructions and tools, and Claude runs autonomously in stateful sessions with persistent event history.
Best for: Autonomous tasks, customer support bots, when you want to offload state management.Here's a quick example of a Managed Agent:
import anthropic
client = anthropic.Anthropic(api_key="YOUR_API_KEY_HERE")
Define your agent
agent = client.beta.agents.create(
name="support-bot",
instructions="You are a helpful customer support agent for Acme Corp. Be polite and concise.",
model="claude-sonnet-4-6"
)
Create a session
session = client.beta.agents.sessions.create(agent_id=agent.id)
Send a message to the agent
response = client.beta.agents.sessions.message(
session_id=session.id,
content="I need help with my order #12345"
)
print(response.content[0].text)
Step 7: Add Advanced Features
Once you have the basics working, you can layer on more capabilities:
Extended Thinking
For complex reasoning tasks, enable extended thinking:
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=4096,
thinking={"type": "enabled", "budget_tokens": 2048},
messages=[{"role": "user", "content": "Solve this complex math problem step by step..."}]
)
Vision (Image Input)
Claude can analyze images:
import base64
with open("diagram.png", "rb") as f:
image_data = base64.b64encode(f.read()).decode("utf-8")
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Explain this diagram"},
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image_data}}
]
}]
)
Tool Use (Function Calling)
Give Claude the ability to call external functions:
tools = [
{
"name": "get_weather",
"description": "Get the current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
]
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}]
)
Step 8: Go to Production
Before deploying, consider these best practices:
Prompt Caching
Reduce costs and latency by caching common prefixes:
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
system=[{"type": "text", "text": "You are a helpful assistant.", "cache_control": {"type": "ephemeral"}}],
messages=[{"role": "user", "content": "Hello"}]
)
Rate Limits & Error Handling
Always handle API errors gracefully:
import time
from anthropic import Anthropic, RateLimitError, APIError
client = Anthropic(api_key="YOUR_API_KEY_HERE")
for attempt in range(3):
try:
response = client.messages.create(...)
break
except RateLimitError:
time.sleep(2 ** attempt) # Exponential backoff
except APIError as e:
print(f"API error: {e}")
break
Cost Optimization
- Use Haiku for simple, high-volume tasks
- Use prompt caching for repeated system prompts
- Set
max_tokensappropriately—don't over-allocate - Monitor usage in the Anthropic Console
Next Steps
You've now built a working Claude integration. Here's where to go next:
- Explore the Workbench – test prompts interactively
- Read the API Reference – full documentation for all endpoints
- Check the Cookbook – code samples and patterns for common use cases
- Try Claude Code – an agentic coding assistant in your terminal
Key Takeaways
- Get your API key from the Anthropic Console and store it securely
- Install the SDK (
pip install anthropic) and make your first call in minutes - Choose the right model: Sonnet for balance, Opus for deep reasoning, Haiku for speed
- Maintain conversation state by sending the full message history with each request
- Pick your surface: Messages API for full control, Managed Agents for autonomous, stateful sessions
- Layer on advanced features like vision, tool use, and extended thinking as you scale
- Plan for production with error handling, rate limits, and cost optimization from day one