How to Use the Claude API: A Complete Beginner Tutorial
This tutorial is the API wiring path — keys, SDK, and request shapes. Prompt patterns that work across models live in the prompt engineering guide. If you want the model on your own hardware instead, use the local LLM setup guide.
The Claude API is one of the best ways to add AI capabilities to your applications. This tutorial takes you from zero to a working AI app in about 15 minutes.
Desk note — who this is for / what it’s bad at: Developers who will call Messages from an app they own. Bad as a reason to open a key for “I ask Claude six questions a day” — that is claude.ai — and a poor substitute for the model comparison if you have not picked a chat tab yet.
What to check before you create a key
Listing identity: the Claude API is a per-token meter on api.anthropic.com. Claude Pro is a consumer chat cap. They are not the same product. A chat Plus seat is not an API key. The chat comparison is the $20 tab; this page is the SDK.
Before you generate a key or paste one into a tutorial snippet:
- Stay on claude.ai if there is no app. A browser tab does not need
ANTHROPIC_API_KEY. Keys exist so your process can call the model. If the job is “explain this function,” use the chat UI or the free-tier list. - The snippet key is a skip-commit. The examples below use
'your-api-key-here'so the page stays readable. Put the real value in an environment variable. A committed key is a rotation, not a lesson. Shipping generated endpoints still needs the security checklist. - Chat plan ≠ API bill. Hitting a Pro cap is not a signal to open a key “for more room.” A busy agent loop will blow past $20 in a week. Cap spend in the Anthropic console on day one. Client-side backoff is the rate-limiting page.
- Do not buy a flagship card to avoid a $5 bill. A 4090 search is unused VRAM if you needed ten Messages calls. Local weights are the local LLM setup when the repo cannot leave the building — not a cheaper Claude.
- Pick the model id from the console, not from memory. The
claude-sonnet-4-20250514string in the snippets is the id this page shipped with. Confirm the current Messages model list before you copy it into production.
Practical cadence: one messages.create in a throwaway script, then a system prompt, then streaming if a human is watching the tokens. Tool use and agents are the building AI agents page, not step 3. Docs generated from an API loop still need a human pass — see code documentation.
Prerequisites
- Basic knowledge of Python or JavaScript
- A terminal / command line
- An Anthropic account (free to create)
Step 1: Get Your API Key
- Go to console.anthropic.com
- Create an account or sign in
- Go to API Keys
- Click Create Key and copy it
Save your API key somewhere safe. You’ll need it in the next step.
Important: Never commit API keys to version control. Use environment variables or a
.envfile.
Step 2: Install the SDK
Python:
pip install anthropic
JavaScript/TypeScript:
npm install @anthropic-ai/sdk
Step 3: Your First API Call
Python:
import anthropic
client = anthropic.Anthropic(
api_key="your-api-key-here"
)
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Explain what an API is in one paragraph, like I'm 10 years old."
}
]
)
print(message.content[0].text)
JavaScript:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: 'your-api-key-here',
});
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [
{
role: 'user',
content: 'Explain what an API is in one paragraph, like I\'m 10 years old.'
}
]
});
console.log(message.content[0].text);
Run it. You should see Claude’s response printed to your terminal.
Step 4: Adding System Prompts
System prompts tell Claude how to behave. This is how you customize Claude’s personality and focus:
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system="You are a senior Python developer. Give concise, practical answers with code examples. Always use type hints.",
messages=[
{
"role": "user",
"content": "How do I read a CSV file and filter rows where the 'age' column is greater than 30?"
}
]
)
Step 5: Multi-Turn Conversations
Claude supports conversation history. Pass previous messages to maintain context:
messages = [
{"role": "user", "content": "What's the best Python web framework for a REST API?"},
{"role": "assistant", "content": "For a REST API, I'd recommend FastAPI..."},
{"role": "user", "content": "Show me a basic FastAPI setup with one endpoint."}
]
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=messages
)
Step 6: Streaming Responses
For better UX in real-time applications, stream the response token by token:
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about coding"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Pricing Quick Reference
| Model | Input (per 1M tokens) | Output (per 1M tokens) |
|---|---|---|
| Claude 3.5 Sonnet | $3.00 | $15.00 |
| Claude 3 Haiku | $0.25 | $1.25 |
| Claude 3 Opus | $15.00 | $75.00 |
For most use cases, Claude 3.5 Sonnet offers the best balance of intelligence and cost. Use Haiku for simple, high-volume tasks.
Desk note — who this is for / what it’s bad at: Sonnet for app features you will actually ship. Haiku for classification and short rewrites at volume. Opus for rare, expensive reasoning — not a default. Bad at treating this table as a chat-plan receipt; the $20 Claude Pro button is a different meter.
Common Errors & Fixes
AuthenticationError, Your API key is invalid or missing. Double-check it.
RateLimitError, You’re sending too many requests. Add exponential backoff or reduce frequency. The same rate-limiting patterns you put in front of your own API apply when you are the client.
InvalidRequestError, Usually means your messages array is malformed. Ensure roles alternate between user and assistant.
What to Build Next
Now that you have the basics, here are some practical project ideas:
- Code review bot, Paste code, get suggestions — or wire the loop in CI
- A small agent, Tool use plus a step cap; see building AI agents
- Documentation generator, Turn code into docs automatically
- Chat support bot, Customer service powered by Claude
- Content summarizer, Feed in articles, get key takeaways
Frequently Asked Questions
What represents a ‘Token’ in Claude?
A token is essentially a piece of a word. In the Claude models, a token typically corresponds to about 3 to 4 English characters. This means 100 tokens are roughly equivalent to 75 words. This metric is critical to understand because Anthropic bills its API usage based exclusively on the token counts of your input (prompts) and output (generated text).
How does Tool Calling (Function Calling) work with the API?
The Claude API supports “Tool Use” (similar to OpenAI’s function calling). You can pass a JSON schema describing external tools (like a weather API, a database querying function, or a calculator to build a custom t-test app) alongside your prompt. Claude will intelligently decide if it needs to use a tool to answer the user’s question, halt execution, ask you (the local application) to run the tool, and then incorporate the tool’s result back into its final response.
Why do I keep getting RateLimitErrors despite passing the hard-coded limits?
If you are running multi-threaded scripts or loops, Anthropic enforces limits on both Requests Per Minute (RPM) and Tokens Per Minute (TPM). Even if you only send 5 requests, if your context window pushes massive megabytes of data, you’ll hit the TPM cap instantly. To avoid this, implement the tenacity library in Python to add automatic exponential back-offs and retries.
Are Claude API requests logged or used for training?
No. Anthropic’s enterprise and general API Terms of Service explicitly protect developers: any data processed via the Claude API is not used to train Anthropic’s foundational models. Also, prompts and completions are only retained for a strict 30-day period for trust and safety purposes before being securely deleted.
TCAL evaluates software from vendor documentation, public pricing, and reported capabilities. For how this desk works, read the Editorial Policy.
Related Reading
- How to Run LLMs Locally: Ollama, llama.cpp, and Hardware Requirements
- Best AI Tools for Code Documentation
- Prompt Engineering Guide: 10 Techniques That Actually Work
- Building AI Agents: Architecture Patterns and Practical Examples
- Automating Code Reviews with AI: A Practical Integration Guide
- CI/CD Pipeline Design: From Zero to Production Deployment
- Vector Databases Explained: When You Need One and How to Choose
- Best Web Hosting for Developers
- ChatGPT vs Claude vs Gemini: Which AI Is Best for Developers?
- How AI Is Actually Changing Software Development Workflows
- The State of AI: What Developers Need to Know