← Blog

Claude API TypeScript SDK: Getting Started Guide

2026-11-11 · 5 min read · SubToAPI Team

Getting started with the Claude API TypeScript SDK

If you're building a TypeScript application and want to call Claude, the fastest path is Anthropic's official @anthropic-ai/sdk package. It handles authentication headers, request typing, streaming, and retries so you don't have to write raw fetch calls against the Messages API. This guide covers installation, your first request, streaming responses, tool use, and common gotchas that trip up new users.

By the end you'll have a working TypeScript file that sends a message to Claude and prints the reply, plus enough context to extend it into a real feature — a chatbot endpoint, a content generator, or an internal tool.

Installing the SDK

Start with a Node.js project (Node 18+ recommended for native fetch support) and TypeScript already configured.

npm install @anthropic-ai/sdk
npm install -D typescript @types/node

Set your API key as an environment variable rather than hardcoding it:

export ANTHROPIC_API_KEY="your-key-here"

The SDK reads this environment variable automatically, so you don't have to pass it explicitly in most setups.

Your first request

Here's a minimal example that sends a single user message and prints the model's reply:

import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic();

async function main() {
  const message = await anthropic.messages.create({
    model: "claude-sonnet-4-5-20250929",
    max_tokens: 1024,
    messages: [
      { role: "user", content: "Explain what a closure is in JavaScript, in two sentences." },
    ],
  });

  console.log(message.content);
}

main();

Run it with ts-node or compile with tsc first. The content field is an array of content blocks — usually a single text block — rather than a plain string, which is worth remembering when you parse responses.

const textBlock = message.content.find((block) => block.type === "text");
console.log(textBlock?.text);

Handling conversation history

Claude's API is stateless: every request needs the full conversation history in the messages array. A typical pattern is to keep an array in memory (or in your database) and append to it after each turn:

type ChatMessage = { role: "user" | "assistant"; content: string };

const history: ChatMessage[] = [
  { role: "user", content: "What's the capital of Portugal?" },
];

const response = await anthropic.messages.create({
  model: "claude-sonnet-4-5-20250929",
  max_tokens: 512,
  messages: history,
});

const reply = response.content.find((b) => b.type === "text")?.text ?? "";
history.push({ role: "assistant", content: reply });

This is the same pattern you'd use for any chat-style interface, regardless of which provider's SDK you're calling.

Streaming responses

For anything user-facing, streaming matters — users shouldn't stare at a blank screen while Claude generates a long answer. The SDK exposes a stream helper:

const stream = anthropic.messages.stream({
  model: "claude-sonnet-4-5-20250929",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Write a short product changelog entry." }],
});

stream.on("text", (textDelta) => {
  process.stdout.write(textDelta);
});

const finalMessage = await stream.finalMessage();

This event-based API is cleaner than manually parsing server-sent events, and it works the same way whether you're building a CLI tool or piping chunks to a web client over a WebSocket.

Using tools (function calling)

If your application needs Claude to call functions — looking up data, running calculations, triggering actions — define tools with a JSON schema and pass them in the request:

const response = await anthropic.messages.create({
  model: "claude-sonnet-4-5-20250929",
  max_tokens: 1024,
  tools: [
    {
      name: "get_weather",
      description: "Get the current weather for a city",
      input_schema: {
        type: "object",
        properties: { city: { type: "string" } },
        required: ["city"],
      },
    },
  ],
  messages: [{ role: "user", content: "What's the weather in Lisbon?" }],
});

const toolUse = response.content.find((block) => block.type === "tool_use");
if (toolUse) {
  console.log(toolUse.name, toolUse.input);
}

You then run the actual function, send the result back as a tool_result content block, and get Claude's final answer. This loop is the backbone of most agentic Claude applications.

Where SubToAPI fits in

The official SDK talks directly to Anthropic's API using your Anthropic account credentials. If you're building a product on top of Claude and need application-level API keys, per-team usage visibility, or a dashboard your non-engineering teammates can check, SubToAPI wraps the same Messages API surface — streaming, tool use, and all — behind sub_live_... keys you can issue per application or per customer.

Swapping in SubToAPI from the SDK usually just means pointing your HTTP client at https://api.subtoapi.app/v1/messages with your sub_live_ key, since the request and response shapes mirror what the TypeScript SDK already expects:

const response = await fetch("https://api.subtoapi.app/v1/messages", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "claude-sonnet-4-5-20250929",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello Claude" }],
  }),
});

See the quickstart and messages docs for full request options, and streaming and tools for the equivalents of what you just built above. Plans start at €9/month for solo developers, with team and scale tiers for shared usage — details are on the pricing page, and there's a free trial at signup.

Common setup mistakes

Questions

Do I need the official SDK, or can I just use fetch? The SDK is optional — Claude's API is plain HTTPS/JSON, so fetch works fine. The SDK just adds TypeScript types, streaming helpers, and retry logic, which saves time on anything beyond a quick script.

What Node.js version do I need? Node 18 or later is recommended since it includes native fetch. Older versions work with a polyfill, but 18+ avoids extra dependencies.

Can I use the same code with SubToAPI instead of a direct Anthropic key? Yes — the request and response formats match, so switching mainly means changing the base URL and using a sub_live_ key instead of your Anthropic key. See the docs for details.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →