← Blog

How to Use the Anthropic API: A Developer Walkthrough

2026-09-03 · 5 min read · SubToAPI Team

Using the Anthropic API means sending HTTP requests to Anthropic's Messages endpoint with an API key, a model name, and a list of messages, then handling the JSON (or streamed) response in your app. That's the whole mechanic — the rest is knowing the request shape, the authentication headers, and a handful of parameters that control cost and behavior.

This guide walks through the process end to end: getting authenticated, making your first request, streaming output, using tools, and handling the errors you'll actually hit in production.

1. Get an API Key and Set Up Auth

Every request to the Anthropic API needs two headers:

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-3-5-sonnet-20241022",
    "max_tokens": 1024,
    "messages": [
      {"role": "user", "content": "Explain what a race condition is."}
    ]
  }'

Store your key as an environment variable, never hardcode it in source, and never ship it in client-side JavaScript — it will be scraped from your bundle. If you're building a public-facing app, you need a backend proxy or a service that issues scoped, revocable keys on top of the Anthropic API. SubToAPI does exactly this: you connect your Claude access once, then generate sub_live_... keys per application, each independently rate-limited and revocable, with usage tracked per key. See the quickstart if you want that layer without building it yourself.

2. Make Your First Request

The core object in the Anthropic API is the Messages endpoint. You send a model, a max_tokens limit, and a messages array where each entry has a role (user or assistant) and content.

const res = await fetch("https://api.anthropic.com/v1/messages", {
  method: "POST",
  headers: {
    "x-api-key": process.env.ANTHROPIC_API_KEY,
    "anthropic-version": "2023-06-01",
    "content-type": "application/json",
  },
  body: JSON.stringify({
    model: "claude-3-5-sonnet-20241022",
    max_tokens: 1024,
    messages: [{ role: "user", content: "Summarize this in one sentence: ..." }],
  }),
});

const data = await res.json();
console.log(data.content[0].text);

Key parameters to know:

Multi-turn conversations just mean appending each new user/assistant pair to the messages array and resending the whole history — the API is stateless between calls.

3. Stream Responses for Real-Time Output

For chat UIs or anything user-facing, you don't want to wait for the full response before showing anything. Set "stream": true and read the response as Server-Sent Events:

const res = await fetch("https://api.anthropic.com/v1/messages", {
  method: "POST",
  headers: {
    "x-api-key": process.env.ANTHROPIC_API_KEY,
    "anthropic-version": "2023-06-01",
    "content-type": "application/json",
  },
  body: JSON.stringify({
    model: "claude-3-5-sonnet-20241022",
    max_tokens: 1024,
    stream: true,
    messages: [{ role: "user", content: "Write a haiku about caching." }],
  }),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  process.stdout.write(decoder.decode(value));
}

Each chunk arrives as a named event (content_block_delta, message_stop, etc.), so your client needs to parse the SSE format, not just concatenate raw text. If you're using SubToAPI's proxy, streaming works the same way against https://api.subtoapi.app/v1/messages — see streaming docs for the event reference.

4. Use Tools for Structured Actions

Tool use (function calling) lets Claude decide when to call a function you define, instead of just generating text. You describe tools with a JSON schema, and Claude returns a tool_use block with the arguments it wants to call your function with:

{
  "model": "claude-3-5-sonnet-20241022",
  "max_tokens": 1024,
  "tools": [
    {
      "name": "get_weather",
      "description": "Get current weather for a location",
      "input_schema": {
        "type": "object",
        "properties": { "location": { "type": "string" } },
        "required": ["location"]
      }
    }
  ],
  "messages": [{ "role": "user", "content": "What's the weather in Lisbon?" }]
}

Your code executes get_weather, then sends the result back as a tool_result message so Claude can incorporate it into a final answer. This is the pattern behind most agent frameworks. Full parameter details are in the tools docs.

5. Handle Errors and Rate Limits

The Anthropic API returns standard HTTP status codes: 400 for malformed requests, 401 for bad auth, 429 for rate limits, 529 when the API is overloaded. Build retry logic with exponential backoff for 429 and 529, and always check stop_reason in successful responses — max_tokens means your output got cut off, which is a silent bug if you don't check for it.

If you're managing multiple applications or team members against one Claude subscription, tracking who's hitting limits and why gets tedious fast. SubToAPI adds per-key usage metadata and dashboard visibility on top of the raw API, plus team seats (Solo €9, Team €19/seat, Scale €49/seat) so you're not sharing one raw key across a codebase. Check pricing or start a free trial at signup.

6. Read the Reference When You Need Specifics

Once the basic loop — auth, request, response, error handling — is working, most of what you need day to day is parameter-level detail: which models support which context windows, exact token limits, message formatting edge cases. The messages docs cover the request/response schema in full.

questions

Do I need a paid plan to use the Anthropic API? Yes, the API is metered and billed per token — there's no free unlimited tier, though new accounts typically get trial credit to test requests before committing.

What's the difference between the Anthropic API and the Claude.ai app? Claude.ai is a consumer chat interface; the API is the programmatic endpoint developers integrate into apps, backends, and automation, with parameters like system prompts and tool use that the chat UI doesn't expose.

Can I call the Anthropic API directly from a browser app? Not safely — it exposes your key. Route requests through a backend or a proxy service that issues scoped keys, so client code never touches your raw credentials.

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 →