← Blog

Claude API Local Development & Testing Setup Guide

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

Setting up Claude API for local development means solving three problems: keeping credentials out of your codebase, avoiding real API calls (and their cost) during routine testing, and reproducing production behavior — including streaming and tool use — on your laptop. This guide walks through a practical setup that handles all three without slowing down your inner dev loop.

If you just want the short answer: use environment variables loaded from a .env file for credentials, build a thin client wrapper so you can swap in a mock transport for unit tests, and keep a small set of integration tests that hit the real API sparingly (ideally against a cheaper model) to catch schema or behavior drift. The rest of this article covers each piece.

Project structure for local Claude development

Start by isolating anything that talks to the API behind a single module. This gives you one place to swap implementations, add logging, or point at a proxy during testing.

src/
  claude-client.js      # wraps API calls
  claude-client.mock.js  # fake responses for unit tests
tests/
  unit/
  integration/
.env.local
.env.test

Your claude-client.js should expose a small, stable interface — sendMessage, streamMessage, useTool — regardless of which SDK or HTTP client sits underneath. That abstraction is what makes mocking and swapping environments painless later.

Managing API keys and environment variables locally

Never hardcode keys. Use a .env.local file (git-ignored) loaded with dotenv or your framework's built-in env loader:

# .env.local
ANTHROPIC_API_KEY=sk-ant-xxxxx
CLAUDE_MODEL=claude-3-5-sonnet-20241022
import 'dotenv/config';

const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
  throw new Error('Missing ANTHROPIC_API_KEY — check .env.local');
}

Keep separate .env.test and .env.local files so test runs never accidentally use your production key, and add both to .gitignore immediately — before you add the actual values.

If multiple people on your team need shared access without distributing a raw Anthropic key, running requests through an API gateway like SubToAPI lets you issue separate sub_live_... keys per developer or per environment. You get usage visibility per key, so you can tell at a glance which local setup is burning through quota during a debugging session. See /docs/quickstart for the setup.

Avoiding real API calls in unit tests

Unit tests should not depend on network access or cost real money every CI run. Build a mock transport that matches your client's interface:

// claude-client.mock.js
export function createMockClient(responses) {
  let call = 0;
  return {
    sendMessage: async (payload) => {
      const response = responses[call] || responses[responses.length - 1];
      call += 1;
      return response;
    },
  };
}
import { createMockClient } from './claude-client.mock.js';

const mockClient = createMockClient([
  { content: [{ type: 'text', text: 'mocked reply' }], usage: { input_tokens: 10, output_tokens: 5 } },
]);

test('summarizer formats mocked response correctly', async () => {
  const result = await summarize(mockClient, 'some input');
  expect(result).toContain('mocked reply');
});

This approach lets you test retry logic, error handling, token-usage calculations, and formatting without ever touching the network. Run these in CI on every commit — they should take milliseconds.

Testing streaming locally

Streaming responses are harder to mock because you need to simulate chunked delivery, not a single return value. A simple approach is an async generator:

async function* mockStream(chunks) {
  for (const chunk of chunks) {
    await new Promise((r) => setTimeout(r, 10));
    yield chunk;
  }
}

test('UI renders streamed tokens incrementally', async () => {
  const chunks = ['Hel', 'lo', ' world'];
  let output = '';
  for await (const chunk of mockStream(chunks)) {
    output += chunk;
  }
  expect(output).toBe('Hello world');
});

When you're ready to test against a real streaming endpoint, point your client at a staging key and verify your frontend's incremental rendering, not just the final text. SubToAPI's streaming endpoint follows standard SSE chunking, documented at /docs/streaming, so the same parsing logic works whether you're testing locally or in production.

Integration tests that actually hit the API

You still need some tests that exercise the real API — schema changes, tool-use behavior, and rate limit handling don't show up in mocks. Keep this suite small and separate from your unit tests:

npm run test:unit        # fast, no network, runs on every commit
npm run test:integration # slower, real API calls, runs on PR merge or nightly

Tips for keeping integration tests cheap and stable:

Simulating rate limits and errors locally

Production code needs to handle 429s, timeouts, and malformed responses gracefully. Test this without waiting for a real rate limit by injecting failures into your mock client:

const flakyClient = {
  sendMessage: async () => {
    throw { status: 429, message: 'rate_limited' };
  },
};

test('client retries on 429 with backoff', async () => {
  await expect(callWithRetry(flakyClient)).rejects.toMatchObject({ status: 429 });
});

This is also where a wrapper API becomes useful for local development: SubToAPI returns usage metadata and consistent error payloads on every call, so your error-handling code written against it in local testing behaves the same way in production. Check /docs/messages for the exact response fields.

Running a local proxy for request inspection

When debugging unexpected model behavior, it helps to see the exact payload being sent. A lightweight local proxy (or just verbose logging in your client wrapper) that dumps request/response JSON to a file saves time compared to re-running requests with guesswork:

async function sendMessage(payload) {
  if (process.env.DEBUG_CLAUDE) {
    console.log('REQUEST:', JSON.stringify(payload, null, 2));
  }
  const res = await fetch(endpoint, { method: 'POST', body: JSON.stringify(payload), headers });
  const data = await res.json();
  if (process.env.DEBUG_CLAUDE) {
    console.log('RESPONSE:', JSON.stringify(data, null, 2));
  }
  return data;
}

Toggle DEBUG_CLAUDE=1 locally and you get full visibility without changing production logging behavior.

Putting it together

A solid local setup has: credentials loaded from git-ignored env files, a client wrapper with a mockable interface, a fast unit test suite with zero network dependency, a small integration suite that runs less frequently, and simple tooling to inspect real requests when something goes wrong. If you want per-developer API keys with usage tracking baked in rather than managing this yourself, a free trial at /signup gets you a working key in minutes, and /pricing has the plan details if you want to compare against your current Anthropic billing setup.

questions

Do I need a separate API key for local development? It's good practice. A separate key (or a gateway that issues per-developer keys, like SubToAPI) lets you track usage and revoke access independently of production, without rotating a shared secret every time someone leaves the team.

Can I test Claude API integrations without making real API calls? Yes — mock your client's interface for unit tests covering formatting, retries, and error handling. Reserve real API calls for a small integration suite that checks schema and model behavior, since mocks can't catch upstream changes.

How do I test streaming responses locally without hitting the real endpoint every time? Simulate chunked delivery with an async generator that yields partial strings on a delay. This validates your UI's incremental rendering logic without any network dependency, then confirm against the real endpoint periodically.

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 →