← Blog

Claude API TypeScript SDK: Usage Example Guide

2026-11-14 · 4 min read · SubToAPI Team

Claude API TypeScript SDK Usage Example

If you're building a Node.js or TypeScript application and want to call Claude, the fastest path is Anthropic's official @anthropic-ai/sdk package. It gives you typed request/response objects, streaming support, and tool-use helpers without having to hand-roll fetch calls and JSON parsing.

This article walks through a complete, working setup: installing the SDK, making your first typed request, streaming responses, handling tool use, and dealing with errors — all in TypeScript. By the end you'll have a minimal but production-ready pattern you can drop into a backend service.

Installing and configuring the SDK

Install the package and set your API key as an environment variable:

npm install @anthropic-ai/sdk
export ANTHROPIC_API_KEY=sk-ant-...

Basic client setup:

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

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

The SDK reads ANTHROPIC_API_KEY from the environment automatically if you omit the apiKey option, but being explicit keeps the code portable across environments and makes it easier to swap keys in CI.

A typed message request

The core type you'll work with is Anthropic.Messages.MessageCreateParams. TypeScript will flag missing fields like model, max_tokens, or messages at compile time, which catches a lot of mistakes before you ever hit the network.

async function askClaude(prompt: string) {
  const response = await anthropic.messages.create({
    model: "claude-opus-4",
    max_tokens: 1024,
    messages: [{ role: "user", content: prompt }],
  });

  const textBlock = response.content.find(
    (block) => block.type === "text"
  );

  return textBlock?.text ?? "";
}

askClaude("Summarize the plot of Dune in two sentences.").then(console.log);

Note that response.content is an array of typed blocks (text, tool_use, etc.), not a plain string. This is one of the most common gotchas for developers moving from a raw fetch-based integration — you need to filter for the block type you expect.

Streaming responses

For chat UIs or anything latency-sensitive, streaming is essential. The SDK exposes an async iterator over events:

async function streamResponse(prompt: string) {
  const stream = anthropic.messages.stream({
    model: "claude-opus-4",
    max_tokens: 1024,
    messages: [{ role: "user", content: prompt }],
  });

  for await (const event of stream) {
    if (event.type === "content_block_delta" && event.delta.type === "text_delta") {
      process.stdout.write(event.delta.text);
    }
  }

  const finalMessage = await stream.finalMessage();
  return finalMessage;
}

stream.finalMessage() resolves once the stream completes, giving you the full assembled message object — useful for logging token usage or persisting the final result after streaming the deltas to a client.

Using tools with typed schemas

Claude's tool-use feature lets the model call functions you define. TypeScript's type inference helps here too, especially if you define your tool schema once and reuse it:

const weatherTool: Anthropic.Tool = {
  name: "get_weather",
  description: "Get current weather for a city",
  input_schema: {
    type: "object",
    properties: {
      city: { type: "string" },
    },
    required: ["city"],
  },
};

const response = await anthropic.messages.create({
  model: "claude-opus-4",
  max_tokens: 1024,
  tools: [weatherTool],
  messages: [{ role: "user", content: "What's the weather in Lisbon?" }],
});

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

You'd then run your actual weather lookup, and send the result back in a follow-up message with role "tool_result" so Claude can produce a final answer.

Error handling

The SDK throws typed errors you can catch and branch on:

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

try {
  const response = await anthropic.messages.create({
    model: "claude-opus-4",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello" }],
  });
} catch (error) {
  if (error instanceof Anthropic.APIError) {
    console.error(error.status, error.message);
  } else {
    throw error;
  }
}

Rate limits (429) and overload errors (529) are the two you'll hit most often in production — plan for retries with backoff on both.

Why some teams wrap this in an HTTP API instead

The pattern above works well for a single backend service with one Anthropic account. It gets more complicated when you need per-application API keys, usage tracking across multiple teams, or billing attribution without building that infrastructure yourself.

This is the gap SubToAPI fills: it turns your existing Claude access into a standard HTTPS API with its own sub_live_... keys, streaming, tool use, and usage metadata per key — so you can issue separate keys to different apps or team members without changing much of the code above. The request shape mirrors the official Messages API closely, so if you're already comfortable with the TypeScript SDK pattern shown here, swapping the base URL and key is mostly it:

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-opus-4",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Hello" }],
  }),
});

Check the quickstart and messages docs for the full request/response shape, or streaming and tools if you need those specifically. Plans start with a free trial at signup, and pricing details are on the pricing page.

questions

Does the official TypeScript SDK support streaming out of the box? Yes. Calling anthropic.messages.stream() returns an async iterator you can loop over with for await, plus a finalMessage() promise for the completed response.

What's the most common TypeScript mistake when using the Claude SDK? Treating response.content as a string instead of an array of typed content blocks. You need to find the block with type === "text" (or "tool_use") before reading its contents.

Can I use the TypeScript SDK pattern with a non-Anthropic endpoint? Yes, if the service mirrors the Messages API request/response shape. Services like SubToAPI are designed to accept the same structure, so most of your existing TypeScript code only needs a base URL and key change.

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 →