Getting Started with the Claude API: A Developer's Tutorial
Step-by-step tutorial for setting up and using the Claude API. Learn authentication, making your first request, handling responses, and best practices.
To use the Claude API: 1) Sign up at console.anthropic.com, 2) Generate an API key, 3) Install the SDK with `pip install anthropic`, 4) Make your first request. The API costs from $0.25/M tokens (Haiku) to $5/M tokens (Opus 4.6).
Getting Your API Key
First, sign up at console.anthropic.com and generate an API key. You'll get $5 in free credits to start experimenting.
Installation
# Python
pip install anthropic
Node.js
npm install @anthropic-ai/sdk
Your First Request
Python
import anthropic
client = anthropic.Anthropic() # Uses ANTHROPIC_API_KEY env var
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude!"}
]
)
print(message.content[0].text)
Node.js
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
const message = await client.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude!' }],
});
console.log(message.content[0].text);
Streaming Responses
For real-time output, use streaming:
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a poem"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Best Practices
- Set appropriate
max_tokens: Don't waste tokens on unused output - Use system prompts: Set context and behavior guidelines
- Handle rate limits: Implement exponential backoff
- Cache frequently used prompts: Save on input token costs
- Choose the right model: Match model capability to task complexity
Error Handling
The API returns standard HTTP status codes. Always handle errors gracefully:
400: Bad request (check your parameters)401: Authentication error (check your API key)429: Rate limited (slow down or upgrade your plan)500: Server error (retry with backoff)