Set up Claude/Anthropic API integration
✓Works with OpenClaudeYou are an AI integration engineer. The user wants to set up Claude/Anthropic API integration in their application.
What to check first
- Run
curl https://api.anthropic.com/v1/modelsto verify API endpoint accessibility - Confirm you have a valid Anthropic API key from https://console.anthropic.com/account/keys
- Check Node.js version with
node --version(requires 14.0+) or Python version withpython --version(requires 3.7+)
Steps
- Install the official Anthropic SDK using
npm install @anthropic-ai/sdk(Node.js) orpip install anthropic(Python) - Store your API key as an environment variable:
export ANTHROPIC_API_KEY="sk-ant-..."on macOS/Linux orset ANTHROPIC_API_KEY=sk-ant-...on Windows - Verify the API key is loaded by checking
echo $ANTHROPIC_API_KEYorecho %ANTHROPIC_API_KEY% - Import the Anthropic client class in your code and initialize it with the constructor
- Call the
messages.create()method with required parameters:model,max_tokens, andmessagesarray - Handle the response object by accessing the
content[0].textproperty for the assistant's reply - Implement error handling for
APIError,APIConnectionError, andRateLimitErrorexceptions - Test with a simple completion request before integrating into production workflows
Code
// Node.js example - install: npm install @anthropic-ai/sdk
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
async function setupClaudeAPI() {
try {
// Create a message using Claude
const message = await client.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1024,
messages: [
{
role: "user",
content: "Hello Claude, introduce yourself briefly.",
},
],
});
// Extract the text response
const assistantReply = message.content[0].text;
console.log("Claude's response:", assistantReply);
// Access usage information
console.log("Input tokens:", message.usage.input_tokens);
console.log("Output tokens:", message.usage.output_tokens);
return assistantReply;
} catch (error) {
if (error.status === 401) {
console.error("Invalid API key - check ANTHROPIC_API_KEY");
} else if (error.status === 429) {
console.error("Rate limited - wait before retrying");
} else if (error instanceof Anthropic.APIConnectionError) {
console.error("Connection failed
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Forgetting to handle rate limits — Anthropic returns 429 errors that need exponential backoff
- Hardcoding the model name in 50 places — use a single config so you can swap models in one place
- Not setting a timeout on API calls — a hanging request can lock your worker indefinitely
- Logging API responses with sensitive data — PII can end up in your logs without realizing
- Treating the API as deterministic — same prompt, different output. Test on multiple runs
When NOT to Use This Skill
- For deterministic tasks where regex or rule-based code would work — LLMs add cost and latency for no benefit
- When you need 100% accuracy on a known schema — use structured output APIs or fine-tuning instead
- For real-time low-latency applications under 100ms — even the fastest LLM is too slow
How to Verify It Worked
- Test with malformed inputs, empty strings, and edge cases — APIs often behave differently than docs suggest
- Verify your error handling on all 4xx and 5xx responses — most code only handles the happy path
- Run a load test with 10x your expected traffic — rate limits hit fast
- Check token usage matches your estimate — surprises here become surprises on your bill
Production Considerations
- Set a daily spend cap on your Anthropic console — prevents runaway costs from bugs or attacks
- Use prompt caching for static parts of your prompts — can cut costs by 50-90%
- Stream responses for any user-facing output — perceived latency drops by 70%
- Have a fallback model ready — if Claude is down, you should be able to swap to a backup with one config change
Related AI/ML Integration Skills
Other Claude Code skills in the same category — free to download.
OpenAI Integration
Integrate OpenAI API with best practices
Embedding Search
Implement vector embedding search
RAG Pipeline
Build Retrieval-Augmented Generation pipeline
Prompt Template
Create reusable prompt templates with variables
AI Streaming
Implement streaming AI responses
LangChain Setup
Set up LangChain for AI workflows
Model Comparison
Compare responses from multiple AI models
AI Rate Limiter
Implement rate limiting for AI API calls
Want a AI/ML Integration skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.