digital-humans.org

Technical scope Major labs & flagship models, anthropic, vendor-analysis

Making your first call to the Claude API takes about five minutes: create an API key in the Anthropic Console, install the official SDK for Python or TypeScript, set an environment variable, and send a single POST request to the messages endpoint. Everything else – streaming, tool use, system prompts, multi-turn conversations – builds on that same request shape. This guide walks through each step with working code and flags the trade-offs that matter once you move past the toy example.

The Claude API is Anthropic's developer interface to its Claude family of models. As of early 2026 you can reach it three ways: directly through Anthropic's own API, through Amazon Bedrock, and through Google Cloud's Vertex AI. All three expose the same underlying models, but authentication, billing and available model versions differ. This piece focuses on the direct Anthropic path, which is the fastest way to get a first response and the reference implementation the others track.

Claude API in one paragraph

The Claude API is a REST interface centred on a single core endpoint – /v1/messages – that accepts a list of conversation turns and returns the model's next turn. Anthropic maintains first-party SDKs for Python and TypeScript, plus a plain HTTP contract you can call from any language. The same request format supports plain text generation, streaming, tool use (function calling), vision inputs and long-context work. Which specific models are available, their context-window sizes and their per-token prices change regularly, so treat any figure here as time-sensitive and confirm it against the official Anthropic documentation before you commit to production. If you want the wider context on how the models differ, our guide to the Claude model family breaks down the tiers and their intended jobs.

Setup in five minutes

How to get a Claude API key

To get a Claude API key, sign in to the Anthropic Console at console.anthropic.com, open the API Keys section from the account settings, and generate a new key. Copy it immediately – Anthropic shows the full secret only once, and you will need to create a fresh key if you lose it. You will also need to add a payment method and, depending on your account, some initial credit before calls will succeed, because the direct API is prepaid or billed against usage rather than offered on a permanent free tier.

A few practices are worth adopting from the first key you create. Name each key for the environment and service that uses it, so revoking a compromised credential does not take down everything else. Never paste an API key into client-side code, a notebook you will share, or a public repository – a key committed to GitHub can be scraped and abused within minutes. Anthropic and other vendors run automated secret scanning, but the safe assumption is that any exposed key is already burned. Store the key in an environment variable or a secrets manager, and rotate it on a schedule.

Install the SDK and set the environment variable

For Python, install the official package:

pip install anthropic

For TypeScript or Node.js:

npm install @anthropic-ai/sdk

Then expose your key to the process without hard-coding it. On macOS or Linux:

export ANTHROPIC_API_KEY="your-key-here"

Both SDKs read ANTHROPIC_API_KEY automatically, so you rarely need to pass the key in code at all. That default is deliberate: it keeps the secret out of your source files. For local development, a .env file loaded with a library such as python-dotenv works well, provided .env is in your .gitignore.

Your first call

Here is a complete Python example. It sends one user message and prints the model's reply.

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment

message = client.messages.create(
    model="claude-sonnet-4-5",   # confirm the current model name in the docs
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain what an API key is in two sentences."}
    ],
)

print(message.content[0].text)

A few details in this small block matter more than they look. The model string names a specific version; Anthropic's model identifiers change as new releases ship, so check the models reference rather than copying a name that may be deprecated. max_tokens is required and caps the length of the response, not the input – set it deliberately, because it directly affects both latency and cost. The messages list is the entire conversation state; the API is stateless, so on every call you resend the full history you want the model to see. The response comes back as a list of content blocks, which is why you index content[0].text rather than reading a single string – a single reply can contain several blocks, especially once tool use enters the picture.

If the call fails, the two errors you will meet first are authentication failures, which mean the key is missing, malformed or revoked, and rate-limit responses, which arrive as HTTP 429. The 429 pattern is common across vendors and worth understanding early; our explainer on 429 too many requests errors covers the retry-with-backoff discipline that applies to Claude just as it does to OpenAI.

Streaming responses

The call above waits for the entire response to be generated before returning anything. For a long answer that can mean several seconds of silence, which feels broken in a chat interface. Streaming solves this by sending tokens as they are produced, so text appears incrementally.

with client.messages.stream(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Write a short paragraph about tides."}
    ],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Stream when a human is waiting on the output – chat, live assistants, anything where perceived latency shapes the experience. Do not bother streaming when the caller is another program that needs the whole result before it can act, such as a batch job parsing structured output; there the added complexity of assembling the stream buys you nothing. Streaming also interacts with error handling: a connection can drop mid-response, so production streaming code needs to handle partial results and decide whether to retry or surface what it has.

Tool use basics

Tool use – Anthropic's term for function calling – lets Claude ask your code to run a function and hand back the result. The model does not execute anything itself. It inspects the tools you describe, decides one is needed, and returns a structured request naming the tool and its arguments. Your code runs the real function and returns the output in a follow-up message, at which point the model incorporates it into its answer.

You declare tools with a JSON schema for their inputs:

tools = [
    {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name"}
            },
            "required": ["city"],
        },
    }
]

message = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "What's the weather in Lisbon?"}],
)

When Claude decides to call get_weather, the response stop_reason will be tool_use and one of the content blocks will contain the tool name and the arguments it chose. The loop is: read that block, execute your actual weather lookup, append a tool_result message with the data, and call the API again so the model can turn the raw result into a natural reply. The quality of your description fields is not cosmetic – it is the main lever you have over whether the model calls the right tool with sensible arguments. Vague descriptions produce wrong calls. This same pattern underpins most agent frameworks; if you are building toward autonomous behaviour, our overview of AI chatbot development frameworks shows where tool use fits into larger orchestration.

System prompts

A system prompt sets the model's role, constraints and behaviour for the whole conversation, separately from the back-and-forth of messages. In the Claude API it is a top-level parameter, not a message with a system role:

message = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=1024,
    system="You are a concise technical editor. Reply in British English and never use bullet points.",
    messages=[{"role": "user", "content": "Summarise the benefits of streaming."}],
)

The distinction matters. Conversation messages carry the specific exchange; the system prompt carries standing instructions that should apply to every turn – tone, format rules, domain constraints, safety boundaries. Putting persistent instructions in the system field keeps them stable as the message history grows and shrinks. Anthropic's prompt engineering guidance recommends being explicit and concrete here rather than terse, and gives Claude-specific advice such as using XML-style tags to delimit sections of a long instruction. Over-loading the user message with role instructions works less reliably than a well-formed system prompt, especially across a multi-turn session.

Cost and rate limits

Billing on the direct Claude API is per-token, split between input and output, with output priced higher than input across the model line. Exact prices and the boundaries between model tiers change, so verify current figures rather than trusting a number you read once. We keep a running breakdown in our analysis of Anthropic Claude API pricing, which is the place to check the trade-offs between the faster, cheaper models and the more capable, more expensive ones.

Two mechanisms cut cost materially. Prompt caching lets you mark a large, stable portion of your prompt – a long system prompt, a document, a set of examples – to be cached, so repeated calls that reuse it pay a reduced rate on the cached portion. This is the single biggest saving for applications that resend the same context on every turn. The Batch API is the other lever: for work that is not latency-sensitive, submitting requests as a batch runs them asynchronously at a lower price than real-time calls. Reach for it when you are grading, classifying or generating at volume overnight rather than serving a live user.

Rate limits are enforced per account and organised into usage tiers. New accounts start on lower limits that rise as your spending and account history grow. When you exceed a limit you get the HTTP 429 discussed earlier; the correct response is exponential backoff with jitter, not an immediate retry that compounds the problem. Design for these ceilings from the start, because hitting them in production is a question of when, not if.

Next steps

Once the single-call pattern is solid, the natural extensions are multi-turn conversations, vision and richer agent integration. Multi-turn is a matter of accumulating the messages list: append each user turn and each assistant reply, and resend the whole array, trimming or summarising older turns before you exhaust the context window. Vision arrives through the same messages endpoint – you attach an image as a content block alongside text, and the model reasons over both, which opens up document understanding, chart reading and screenshot-driven workflows.

The most significant recent direction is the Model Context Protocol, an open standard Anthropic introduced for connecting models to external tools and data sources through a common interface rather than bespoke integrations. Instead of hand-wiring every tool, an MCP server exposes capabilities that any compatible client can use. If you are heading toward agents that touch real systems, our explainer on the Model Context Protocol is the next thing to read, and the broader picture of where this is going lives in our coverage of AI agents news and developments.

The virtue of the Claude API is that all of this – streaming, tools, vision, multi-turn, MCP – hangs off the one request shape you learned in the first example. You are not learning five APIs. You are learning one endpoint and layering capabilities onto it. Start with the twenty-line call, get authentication and error handling right, then add exactly the features your application needs and nothing more.