Simple definition#
The Claude API is one HTTP endpoint, POST /v1/messages: you send a model ID, optional system instructions, a list of messages and optional tools; Claude returns content blocks (text, tool calls, thinking). Everything else — tools, structured output, caching, citations, files — is a feature of that one endpoint or a small supporting API (Batches, Files, Models, Token counting). Official SDKs exist for Python, TypeScript, Java, Go, Ruby, C# and PHP.
Start simple: pick the right surface#
| Need | Surface | You own |
|---|---|---|
| Classify, summarise, extract, answer | Single Messages call | The prompt and output handling |
| Multi-step pipeline with fixed steps | Messages + your code (a workflow) | The orchestration |
| Agent with your own tools | Messages + tool runner (SDK helper that runs the loop) | Tools and hosting |
| Coding/filesystem agent on your infrastructure | Claude Agent SDK (the Claude Code harness as a library) | Hosting and sandboxing |
| Hosted, stateful agent with a sandbox, schedules, memory | Claude Managed Agents (Anthropic runs the loop and the container) | Agent configuration and tools you expose |
A first request#
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY or an `ant auth login` profile
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
output_config={"effort": "medium"}, # low | medium | high | xhigh | max
system="You are a senior reviewer for a Java payments platform.",
messages=[{"role": "user", "content": "Explain the risk in this diff: ..."}],
)
if response.stop_reason == "refusal":
... # handle; see fallbacks below
print(next(b.text for b in response.content if b.type == "text"))
print(response.usage) # input, output and cache token counts — log them
Things to know from the first day:
- Thinking is built in. Current models think adaptively; control depth with
effort, not a token budget (fixedbudget_tokensis rejected on current models). - No prefill. You cannot start the assistant’s reply for it on current models; use structured outputs or instructions instead.
- Stream long work. For large
max_tokensor long tasks, useclient.messages.stream(...)andget_final_message()to avoid HTTP timeouts. - Sampling parameters are going away.
temperature,top_pandtop_kare rejected on the newest API version; steer with instructions and effort.
Tools and agents#
Define tools with a name, description and JSON schema (or a typed function), and let the SDK’s tool runner drive the call–execute–repeat loop:
from anthropic import beta_tool
@beta_tool
def get_order(order_id: str) -> str:
"""Look up an order by ID and return status, amount and customer tier as JSON.
Args:
order_id: The order identifier, e.g. "ORD-10294".
"""
return orders_service.find(order_id).to_json()
runner = client.beta.messages.tool_runner(
model="claude-sonnet-5-5",
max_tokens=16000,
tools=[get_order],
messages=[{"role": "user", "content": "Why was ORD-10294 not refunded?"}],
)
final = runner.until_done()
Design rules (detail in tool calling):
- Descriptions are prompts. Say what the tool does, when to use it, and what it returns. Keep the set small and non-overlapping; with many tools, use the tool search tool so definitions load on demand.
- Use
strict: trueon tool definitions to guarantee schema-valid arguments; validate again on the server side anyway. - Return errors as data (
is_error: true) so the model can recover, and return all parallel tool results in one message. - Server tools run on Anthropic’s side with no loop code: web search, web fetch, code execution. MCP servers can be attached directly through the MCP connector.
- On the newest models, forced tool choice (
any/ a named tool) is not supported — useautoplus a clear instruction, or structured outputs if you only wanted JSON.
Structured outputs#
When you need JSON, constrain the response to a schema instead of asking politely:
from pydantic import BaseModel
class Triage(BaseModel):
component: str
severity: str # "S1".."S4"
duplicate_of: str | None
summary: str
result = client.messages.parse(
model="claude-haiku-5-5",
max_tokens=2000,
messages=[{"role": "user", "content": f"Triage this bug report:\n{report}"}],
output_format=Triage,
)
ticket = result.parsed_output # a validated Triage instance
Prompt caching: the biggest free win#
Caching stores a prefix of the request (tools → system → messages) so later requests that start with the same bytes pay a fraction of the input price and get faster time to first token.
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=4000,
system=[{
"type": "text",
"text": CODING_STANDARDS_AND_ARCHITECTURE_GUIDE, # large and stable
"cache_control": {"type": "ephemeral"},
}],
messages=[{"role": "user", "content": diff_to_review}], # varies per call
)
print(response.usage.cache_read_input_tokens) # should be > 0 on repeat calls
- Put stable content first and volatile content last. A timestamp, request ID or unsorted JSON in the system prompt silently breaks the cache.
- To add operator instructions mid-conversation on current models, append a
system-role message tomessagesrather than editing the top-level system prompt — the cached prefix survives. - Verify with
cache_read_input_tokens; if it stays at zero, something in the prefix is changing.
Batches, files, citations and documents#
| Feature | What it does | Typical engineering use |
|---|---|---|
| Message Batches | Up to tens of thousands of requests, asynchronous, 50% cheaper | Evaluations, back-fills, bulk code or ticket analysis |
| Files API | Upload once, reference by file_id |
Large specs, PDFs and images reused across calls |
| PDF and image input | Documents and screenshots as content blocks | Reading design documents, architecture diagrams, UI screenshots |
| Citations | Answers carry exact quoted spans and page numbers | Grounded answers over policies and standards |
| Token counting | Exact token count before you send | Budgeting, chunking decisions |
Long-running work#
| Problem | Feature |
|---|---|
| Conversation approaching the context window | Compaction (server-side summarisation of earlier turns) or context editing (clearing old tool results) |
| Agent should pace itself within a budget | Task budgets (advisory token budget the model sees) |
| Keep state between sessions | Memory tool (file-like memory you store) |
| Many short requests in a long loop | Message threads (the API keeps the conversation briefly so you send only new turns) |
| Want the full coding-agent harness in your code | Claude Agent SDK (claude-agent-sdk / @anthropic-ai/claude-agent-sdk) |
| Want Anthropic to host loop, sandbox, schedules and outcomes | Claude Managed Agents — versioned agent configs, per-session containers, vault-held credentials, scheduled deployments, rubric-graded outcomes, multi-agent workflows |
In Java with Spring AI#
Most of this hub’s Java examples use Spring AI. Switching the Anthropic starter to a current model is configuration:
spring.ai.anthropic.api-key=${ANTHROPIC_API_KEY}
spring.ai.anthropic.chat.model=claude-sonnet-5-5
Spring AI gives portability across vendors; the official Anthropic Java SDK (com.anthropic) gives first access to Claude-specific features such as effort, caching control, fallbacks and Managed Agents. A common pattern is Spring AI for standard chat and RAG, and the native SDK in the few services that need Claude-specific features.
Where Claude runs#
| Option | Operated by | Choose it when |
|---|---|---|
| Claude API (platform.claude.com) | Anthropic | You want every feature first, including fast mode, server-side fallbacks and Managed Agents |
| Claude Platform on AWS | Anthropic, billed through AWS | AWS procurement with first-party feature parity |
| Amazon Bedrock | AWS | Your controls, networking and data agreements are built around Bedrock |
| Google Cloud — Vertex AI or Anthropic-managed | Google or Anthropic | Google Cloud estates |
| Microsoft Foundry | Microsoft, billed via Marketplace at API rates | Azure estates |
Feature availability differs by platform — some beta features, server tools and Managed Agents arrive on the Claude API first. Check the platform table in the documentation before you design around a feature. For residency, the inference_geo parameter pins where inference runs on supported models.
Production checklist#
- Errors: catch specific SDK errors (rate limit, overloaded, not found, bad request) and retry only the retryable ones; the SDKs already retry 408/409/429/5xx twice by default.
- Refusals: check
stop_reasonbefore reading content; enable fallbacks on the Claude API (fallbacks="default"with theserver-side-fallback-2026-07-01beta) or the client-side middleware elsewhere. - Observability: log model, effort,
usage(including cache reads), latency and stop reason per request; the SDKs emit OpenTelemetry spans. - Secrets: API keys in a secret manager; prefer workload identity federation over long-lived keys in CI and cloud workloads.
- Prompt injection: treat tool results, web pages, files and emails as untrusted data; give agents least privilege (AI security).
- Versioning: keep prompts, tool definitions and model IDs in version control and change them through the same review and evaluation gate as code.
Common mistakes#
Review questions#
When would you use the Agent SDK instead of the API tool runner? When you want the full Claude Code harness — built-in file, shell and search tools, context management, sub-agents, hooks and permissions — in your own process. The tool runner only loops over tools you define.
What does Managed Agents add over the Agent SDK? Hosting. Anthropic runs the loop and a per-session sandbox, stores versioned agent configurations, holds credentials in vaults, and supports schedules and graded outcomes.
How do you make prompt caching effective?
Stable content first, volatile content last, deterministic tool lists, no timestamps in the prefix, mid-conversation system messages instead of edits, and verification through cache_read_input_tokens.
Summary#
- One endpoint, many features: tools, structured outputs, caching, citations, files.
- Choose the simplest surface: single call → workflow → tool runner → Agent SDK → Managed Agents.
- Effort replaces thinking budgets; stream long work; handle refusals.
- Caching and batches are the biggest cost levers; log
usageon every call.
References#
- Anthropic, Messages API and tool use overview.
- Anthropic, Structured outputs.
- Anthropic, Prompt caching.
- Anthropic, Batch processing.
- Anthropic, Compaction.
- Anthropic, Claude Managed Agents overview.
- Anthropic, Claude Agent SDK.