How to call Claude API from JavaScript
Quick answer
Use the
anthropic JavaScript SDK to call the Claude API by creating an Anthropic client with your API key, then invoke client.messages.create() with the model name (e.g., claude-3-5-sonnet-20241022) and your messages. This approach provides a simple, secure way to interact with Claude from JavaScript.PREREQUISITES
Node.js 18+Anthropic API keynpm install anthropic
Setup
Install the official anthropic SDK for JavaScript and set your API key as an environment variable.
- Run
npm install anthropicto install the SDK. - Set your API key in your environment:
export ANTHROPIC_API_KEY=your_api_key(Linux/macOS) orset ANTHROPIC_API_KEY=your_api_key(Windows).
npm install anthropic Step by step
Here is a complete JavaScript example using the Anthropic SDK to call Claude. It sends a simple prompt and prints the response.
import anthropic from "anthropic";
import dotenv from "dotenv";
dotenv.config();
async function callClaude() {
const client = new anthropic.Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const response = await client.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 300,
system: "You are a helpful assistant.",
messages: [
{ role: "user", content: "Hello Claude, how do I call your API from JavaScript?" }
]
});
console.log("Claude response:", response.content);
}
callClaude().catch(console.error); output
Claude response: To call the Claude API from JavaScript, use the official Anthropic SDK, create a client with your API key, and call client.messages.create() with your prompt and model name.
Common variations
- Async/await: The example uses async/await for clarity.
- Streaming: The Anthropic SDK supports streaming responses for real-time output.
- Different models: Replace
claude-3-5-sonnet-20241022with other Claude models as needed. - Environment variables: Use
dotenvor your platform's secret manager to securely manage API keys.
Troubleshooting
- If you get
401 Unauthorized, verify yourANTHROPIC_API_KEYis set correctly. - If the response is empty or times out, check your network connection and model name spelling.
- For rate limits, consider adding retry logic or upgrading your API plan.
Key Takeaways
- Use the official
anthropicJavaScript SDK to call Claude API securely and easily. - Set your API key in environment variables and never hardcode it in your code.
- The
client.messages.create()method requiresmodel,system, andmessagesparameters. - You can switch Claude models by changing the
modelparameter string. - Handle common errors like unauthorized access and rate limits by checking API keys and network.