Get a key and install the SDK
Create an API key in the Claude Console and export it as ANTHROPIC_API_KEY. The official SDKs pick it up automatically, so never paste keys into your code.
export ANTHROPIC_API_KEY="sk-ant-..."
# TypeScript
npm install @anthropic-ai/sdk
# Python
pip install anthropicA basic request (TypeScript)
Responses come back as a list of content blocks. Check the block type before reading text.
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
system: "You are a concise assistant for UK small businesses.",
messages: [{ role: "user", content: "Give me 3 ideas to reduce late invoice payments." }],
});
for (const block of response.content) {
if (block.type === "text") console.log(block.text);
}The same thing in Python
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
system="You are a concise assistant for UK small businesses.",
messages=[{"role": "user", "content": "Give me 3 ideas to reduce late invoice payments."}],
)
for block in response.content:
if block.type == "text":
print(block.text)Stream long answers
Streaming shows text as it's generated and avoids timeouts on long outputs. If you just want the final result, the SDK can collect it for you.
const stream = client.messages.stream({
model: "claude-opus-5-5",
max_tokens: 64000,
messages: [{ role: "user", content: "Write a detailed onboarding guide for new staff." }],
});
stream.on("text", (text) => process.stdout.write(text));
const final = await stream.finalMessage();
console.log("\nTokens used:", final.usage.output_tokens);Cache the parts that repeat
If every request starts with the same long instructions or reference document, mark it for caching. Later requests that share that exact prefix read it from cache at a fraction of the price.
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
system: [
{ type: "text", text: longPolicyHandbook, cache_control: { type: "ephemeral" } },
],
messages: [{ role: "user", content: "How many days' holiday do part-timers get?" }],
});
console.log(response.usage.cache_read_input_tokens); // > 0 on a cache hitTip: Caching is a prefix match. Don't put timestamps or user IDs above the cached block, or you'll never get a hit.