Lesson
Making Your First API Call (Node.js)
Now that you have your API key stored safely in a .env file, it's time to write some code.
Anthropic provides an official SDK (Software Development Kit) for Node.js. This SDK wraps the raw HTTP requests into clean, easy-to-use JavaScript functions.
Setup
First, initialize a new Node project and install the necessary packages.
npm init -y
npm install @anthropic-ai/sdk dotenv
The Code
Create an index.js file. We will write a simple script that asks Claude to write a haiku.
// 1. Load the environment variables from the .env file
require('dotenv').config();
// 2. Import the Anthropic SDK
const Anthropic = require('@anthropic-ai/sdk');
// 3. Initialize the client (it automatically looks for process.env.ANTHROPIC_API_KEY)
const anthropic = new Anthropic();
async function main() {
try {
// 4. Send the request
const response = await anthropic.messages.create({
model: 'claude-3-haiku-20240307', // Specifies which model to use
max_tokens: 100, // Limits the length of the response
messages: [
{ role: 'user', content: 'Write a haiku about a robot learning to code.' }
]
});
// 5. Print the result
console.log(response.content[0].text);
} catch (error) {
console.error('API Error:', error);
}
}
main();
Breaking Down the Payload
When you call anthropic.messages.create(), you are sending a JSON payload to Anthropic.
- model: You must explicitly tell the API which version of Claude you want to talk to. We used
claude-3-haiku, which is the fastest and cheapest model. - max_tokens: This is a required safety limit. It stops Claude from endlessly generating text and burning through your wallet if it gets stuck in a loop.
- messages: This is an array of objects. Because the API is stateless, you must format the conversation as a list of back-and-forth messages. Here, we just have one message from the
user.
If you run node index.js in your terminal, the script will reach out to Anthropic, generate the poem, and print it to your console. You just built your first AI app!