Artificial intelligence is transforming how we build software. In this tutorial, you’ll learn how to integrate the three most popular AI APIs: OpenAI, Anthropic Claude, and Google Gemini.
Why use AI APIs?
AI APIs allow you to add advanced capabilities to your applications without the need to train your own models:
- Text generation – Chatbots, assistants, content
- Data analysis – Information extraction, classification
- Automation – Document processing, emails
1. OpenAI (GPT-4)
OpenAI is the pioneer behind ChatGPT. Its API is the most mature on the market.
Installation
npm install openai
Basic example
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function chat(message) {
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: message }
],
});
return response.choices[0].message.content;
}
// Usage
const answer = await chat('What is a REST API?');
console.log(answer);
Pricing (approximate)
- GPT-4: $0.03 / 1K input tokens, $0.06 / 1K output tokens
- GPT-3.5: $0.0005 / 1K tokens (much cheaper)
2. Anthropic Claude
Claude stands out for its ability to follow complex instructions and its large context window (up to 200K tokens).
Installation
npm install @anthropic-ai/sdk
Basic example
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
async function chat(message) {
const response = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [
{ role: 'user', content: message }
],
});
return response.content[0].text;
}
// Usage
const answer = await chat('Explain what TypeScript is');
console.log(answer);
Pricing (approximate)
- Claude Sonnet: $3 / 1M input tokens, $15 / 1M output tokens
- Claude Haiku: $0.25 / 1M tokens (ideal for simple tasks)
3. Google Gemini
Gemini is Google’s AI offering, with excellent integration across the Google Cloud ecosystem.
Installation
npm install @google/generative-ai
Basic example
import { GoogleGenerativeAI } from '@google/generative-ai';
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
async function chat(message) {
const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
const result = await model.generateContent(message);
return result.response.text();
}
// Usage
const answer = await chat('How does a database work?');
console.log(answer);
Pricing
- Gemini Pro: Free up to a certain limit, then pay-as-you-go
Which one should you choose?
- OpenAI: If you need the most battle-tested and well-documented model
- Claude: If you work with long documents or complex instructions
- Gemini: If you already use Google Cloud or want a cost-effective option