The
Claude API lets developers place
Anthropic’s models inside applications, workflows and agents. It is the right route when a team needs programmatic control rather than a person chatting on Claude’s website or in the desktop app.
A first request takes only a few lines of code. A dependable product requires more: secure key handling, explicit conversation state, model routing, validated outputs, retries, rate-limit handling, cost controls and evaluation.
This guide covers that full path. For the consumer product, start with our
complete guide to Claude. For the terminal coding agent, use the separate
Claude Code guide.
What is the Claude API?
The Claude API is Anthropic’s developer interface for sending content to Claude models and receiving generated responses. Its central endpoint is the Messages API.
A request normally includes:
- a model ID;
- a maximum output-token limit;
- optional system instructions;
- and one or more user and assistant messages.
The response contains typed content blocks, usage data, a stop reason and identifiers useful for logging.
The API is not the same product as a Claude subscription. Claude Free, Pro, Max, Team and Enterprise pay for access to Anthropic’s user-facing apps. API use is metered separately through a developer account. Our
Claude pricing guide explains both systems without mixing them.
What you need before starting
Create an account in the
Claude Console, add billing or credits where required and create an API key.
Treat that key like a password:
- never place it in browser-side JavaScript;
- never commit it to Git;
- never paste it into a public issue or screenshot;
- store it in an environment variable or secrets manager;
- give production services separate keys;
- rotate a key immediately if it is exposed.
Set the environment variable in the shell or deployment platform rather than hard-coding it:
export ANTHROPIC_API_KEY="your-api-key"
The exact command differs on Windows and across hosting platforms. Do not include a real key in documentation or example files.
Make a first Claude API request with Python
Install Anthropic’s official Python SDK:
python -m pip install anthropic
Then create a request:
import os
from anthropic import Anthropic
client = Anthropic(
api_key=os.environ["ANTHROPIC_API_KEY"]
)
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=800,
system=(
"You are a concise product analyst. "
"Separate facts from assumptions."
),
messages=[
{
"role": "user",
"content": (
"Summarize the three main risks in this launch plan, "
"then propose one mitigation for each."
),
}
],
)
for block in message.content:
if block.type == "text":
print(block.text)
The SDK reads the API key, sends a Messages request and converts the JSON response into typed objects. Iterating over content blocks is safer than assuming every response contains only one text block; tool calls and other features can return different block types.
Make a first request with TypeScript
Install the official TypeScript SDK:
npm install @anthropic-ai/sdk
Then call the API from a trusted server environment:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
const message = await client.messages.create({
model: "claude-sonnet-5",
max_tokens: 800,
system:
"You are a concise product analyst. Separate facts from assumptions.",
messages: [
{
role: "user",
content:
"Summarize the three main risks in this launch plan, then propose one mitigation for each.",
},
],
});
for (const block of message.content) {
if (block.type === "text") {
console.log(block.text);
}
}
Do not run this code directly in a public web page. A frontend should call your own authenticated backend, and that backend should call Anthropic.
Understand the Messages API
The Messages API is stateless. Anthropic does not infer an application’s previous turns merely because requests use the same key. To continue a conversation, send the relevant history again:
history = [
{"role": "user", "content": "Suggest three names for a budgeting app."},
{"role": "assistant", "content": "Ledgerly, ClearCents and BudgetBeacon."},
{"role": "user", "content": "Make the second name sound more premium."},
]
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=300,
messages=history,
)
This design gives the application control over memory, but it also makes the application responsible for privacy, storage and context size.
In production:
- store only conversation data that the product genuinely needs;
- retrieve the relevant turns;
- summarize or remove stale context;
- send the bounded context to the model;
- save the new response under the correct user and tenant.
Do not use an unbounded transcript as memory. It raises costs, slows requests and can preserve obsolete instructions.
System instructions versus user messages
Use the top-level system field for stable role, policy and output instructions. Use messages for user requests and conversational context.
A useful system instruction defines:
- the task;
- the intended audience;
- the evidence standard;
- required output shape;
- forbidden behavior;
- and what to do when information is missing.
It should not contain secrets. A model may reproduce instructions in an output, tool call or error-adjacent workflow.
System instructions also do not create an absolute security boundary. If untrusted documents or web pages enter the context, treat their text as data and defend against prompt injection in application logic.
Which Claude model should you use?
Do not default every request to the most expensive model. Route work according to difficulty and value.
| Model | Strong fit | Main trade-off |
| Claude Haiku 4.5 | Classification, extraction, routing and fast high-volume work | Less capable on the hardest reasoning tasks |
| Claude Sonnet 5 | General production workloads, analysis, tools and coding | More expensive than Haiku |
| Claude Opus 5 | Difficult engineering, research and agentic enterprise work | Higher latency and cost |
| Claude Fable 5 | The hardest long-running agent tasks where completion quality dominates | Highest standard API price |
Anthropic also lists Mythos 5 for restricted defensive-cyber access. It is not a general default for ordinary applications.
See our complete
Claude models guide for current model IDs, context windows, output limits and knowledge cutoffs.
Prefer aliases or snapshots?
Current model families use stable-looking IDs such as:
- claude-sonnet-5;
- claude-opus-5;
- claude-fable-5;
- claude-haiku-4-5-20251001.
An alias can simplify upgrades. A dated snapshot can improve reproducibility when one exists. Anthropic’s newer model naming does not always follow the old dated-snapshot pattern, so consult the live model overview before hard-coding a policy.
Record the resolved model in production traces. A model migration should pass the same evaluation suite as any other material dependency change.
Thinking and effort in current Claude models
Claude Sonnet 5 and Opus 5 use adaptive thinking by default in the Claude API. The model decides when reasoning is useful, while the effort control adjusts how much work it should apply.
For example:
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=2000,
thinking={"type": "adaptive"},
output_config={"effort": "medium"},
messages=[
{
"role": "user",
"content": "Compare these two migration plans and identify hidden dependencies.",
}
],
)
Check the
official effort documentation before shipping because supported levels and defaults can differ by model.
Three migration traps matter:
- current Sonnet 5 does not accept manual thinking budgets;
- non-default temperature, top_p and top_k settings produce errors on current 4.7-and-later models;
- max_tokens covers reasoning and visible output, so a limit sized for an older non-thinking request may be too small.
Use prompts and effort controls instead of copying sampling settings from an old tutorial.
Stream long responses
Streaming lets an interface show output as it arrives instead of waiting for the entire answer.
Python:
with client.messages.stream(
model="claude-sonnet-5",
max_tokens=1600,
messages=[
{"role": "user", "content": "Draft a launch checklist for this product."}
],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Streaming improves perceived speed, not model accuracy. The application must still handle interruption, partial content and a final completion state. Do not trigger a consequential action from an incomplete stream.
Get reliable structured output
Asking for “valid JSON” is weaker than enforcing a schema. Anthropic’s structured-output feature can constrain the response format through output_config.format.
A production schema should be:
- as small as the task permits;
- explicit about required fields;
- strict about enumerations;
- bounded for arrays and strings;
- versioned alongside application code.
Validate the result in the application even when the model uses a constrained format. Business rules such as “refund cannot exceed original payment” belong in deterministic code, not only in a JSON schema.
Current models also reject assistant-message prefilling that older examples sometimes used to force a JSON opening brace. Use structured outputs or clear instructions instead.
Let Claude use tools
Tool use allows Claude to request a function defined by the application. A tool definition contains a name, description and JSON input schema.
A simplified tool:
tools = [
{
"name": "get_order_status",
"description": "Retrieve the current status of one customer order.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "The exact internal order identifier.",
}
},
"required": ["order_id"],
"additionalProperties": False,
},
}
]
Claude may return a tool_use block. Your application must then:
- validate the requested name and arguments;
- authorize the action for the current user;
- execute it in trusted code;
- return a tool_result block;
- let Claude produce the next response.
The model does not execute an application function by itself. Your code decides whether and how it runs.
Descriptions affect tool selection, so make them precise. Do not expose a broad “run anything” tool when three narrow read-only tools will do. Require confirmation for sending, buying, deleting or changing permissions.
Built-in web and code tools
Anthropic offers server-side tools such as web search and code execution in supported configurations. These can accelerate research and calculations, but each changes the risk and cost profile.
For web research:
- keep citations with the claims they support;
- distinguish search snippets from opened sources;
- block or isolate untrusted instructions inside pages;
- allow-list domains when the use case permits;
- record which sources informed an output.
For code execution:
- treat generated code as untrusted;
- isolate the runtime;
- restrict network and files;
- cap time, memory and output;
- never inject production credentials.
Tool fees are separate from model tokens. See the
official pricing page before estimating unit economics.
Work with files, images and PDFs
The Messages API accepts multimodal content in supported formats. An application can supply images or documents as encoded content, uploaded file references or supported URLs, depending on the feature.
Do not send an entire document collection by default. Retrieve the relevant passages, preserve source metadata and send enough surrounding context to interpret them.
For regulated or sensitive files:
- classify the data before upload;
- use the correct commercial agreement and region;
- remove unnecessary personal data;
- control application logs and backups;
- define deletion behavior;
- test prompt-injection defenses.
The model’s large context window is capacity, not a retrieval strategy.
Count tokens before sending
Anthropic’s
token-counting endpoint estimates input tokens without creating the full message. It includes messages, system instructions, tools, images and documents.
Use it to:
- reject or summarize inputs that will not fit;
- predict cost before an expensive request;
- route small work to a cheaper model;
- reserve room for the answer;
- detect sudden prompt growth.
Tokenization differs across model generations. Anthropic says current 4.7-and-later models can count the same text differently from earlier models, so do not rely on a fixed characters-per-token rule.
Reduce cost and latency
The largest savings usually come from product design rather than a clever prompt.
Route by difficulty
Use Haiku for bounded extraction or classification, Sonnet for general work and stronger models only when evaluations show a meaningful gain.
Keep context relevant
Remove stale messages, duplicate policies and unrelated documents. Summarize history carefully and retain source references.
Cache stable prompt prefixes
Prompt caching can reduce the cost and latency of repeatedly sending a long stable prefix, such as a handbook or tool catalog. Cache hits depend on an identical eligible prefix and its time-to-live.
Batch asynchronous work
The Message Batches API processes large non-interactive workloads asynchronously and offers a token discount. It fits evaluations, offline classification and backfills—not a live chat response.
Cap output intentionally
Set max_tokens high enough for the task but not arbitrarily high. Ask for a bounded number of items or fields when that matches the product.
Measure cost per successful outcome
A cheaper request that often needs repair can cost more than a stronger first pass. Track cost per accepted classification, resolved ticket or approved draft—not only cost per million tokens.
Calculate Claude API cost
The core estimate is:
input tokens × input rate + output tokens × output rate + tool and platform fees
Rates are normally quoted per million tokens. Cache writes, cache reads, batch requests, fast modes, regional endpoints and built-in tools can have different prices.
Our
Claude pricing guide maintains the cluster’s full price tables. Keep this technical article focused on implementation, and always verify a budget against Anthropic’s live pricing before signing a commitment.
Handle errors and rate limits
An application should distinguish error classes:
| Status | Typical meaning | Appropriate response |
| 400 | Invalid request or unsupported parameter | Fix the request; do not retry unchanged |
| 401 | Missing or invalid authentication | Check key configuration |
| 403 | Account or permission does not allow the action | Correct access or feature choice |
| 404 | Endpoint, resource or model not found | Check the current identifier |
| 413 | Request is too large | Reduce or partition content |
| 429 | Rate or acceleration limit reached | Honor retry-after, queue and back off |
| 5xx | Temporary service-side failure | Retry a limited number of times with jitter |
Only retry requests that are safe to repeat. Use exponential backoff with random jitter, cap attempts and surface a useful fallback.
Rate limits can include requests per minute, input tokens per minute and output tokens per minute. A queue protects both Anthropic and your own downstream systems from bursts.
Design for production
A prototype prints text. A production service also needs the following.
Timeouts and cancellation
Set connection and request timeouts. Cancel work when a user leaves or an upstream job expires.
Idempotency
Prevent a retried agent step from charging a card or sending a message twice. Give consequential operations application-level idempotency keys.
Observability
Log:
- internal request ID;
- tenant and workflow, using privacy-safe identifiers;
- model;
- latency;
- input and output tokens;
- stop reason;
- tool calls;
- error class;
- cost estimate;
- evaluation or user-feedback outcome.
Do not log raw prompts and files indiscriminately.
Evaluations
Maintain a versioned set of realistic cases, edge cases and adversarial inputs. Score correctness, format, citation quality, safety, latency and cost.
Run the suite when changing:
- model;
- prompt;
- tool descriptions;
- retrieval;
- schema;
- SDK;
- or application policy.
Fallbacks
Define what happens when the model is unavailable, slow, over limit or uncertain. The safe fallback may be a queue, a smaller deterministic feature or a human—not an invisible switch to a behaviorally different model.
API security and data use
Anthropic says it does not train generative models on commercial API inputs or outputs by default. Standard API inputs and outputs are generally removed from backend systems within 30 days unless an exception or different agreement applies. Contracted zero-data-retention arrangements are available for eligible use cases and features.
Model choice can override that general option. Claude Fable 5 and Claude Mythos 5 are designated Covered Models that require 30-day retention and are not available under ZDR. A direct-API request from an incompatible workspace can return a 400 invalid_request_error; eligible organizations can isolate the models in a workspace configured for the required retention.
That does not remove the application developer’s responsibilities. Your own database, logs, analytics, tracing vendor and backups may retain the same content longer.
Use:
- server-side secret storage;
- separate development and production workspaces;
- least-privilege service accounts;
- spend and rate limits;
- tenant isolation;
- encryption;
- audit logs;
- deletion workflows;
- and data-loss prevention where appropriate.
Read our full guide to
Claude privacy and security before processing confidential or regulated data.
Direct Claude API or a cloud platform?
Claude is also available through supported cloud platforms, including Amazon, Google Cloud and Microsoft services. The model may be similar, but the surrounding product is not identical.
Compare:
- model and feature availability;
- API shape and SDK;
- region;
- identity and network controls;
- billing and enterprise discounts;
- quotas;
- logging;
- data terms;
- support;
- migration effort.
Do not assume code written for Anthropic’s direct API can move unchanged. Use an abstraction only when the organization genuinely needs portability; a lowest-common-denominator wrapper can hide useful platform features.
Claude API versus Claude Code
Claude Code is a ready-made coding agent. It already understands repositories, shells, diffs and development workflows.
The API is a toolkit for building your own product or agent. Choose it when you need a custom interface, domain tools, workflow logic or customer-facing experience.
A team creating an internal coding workflow may use both: Claude Code for engineers and the API for a purpose-built service.
Production checklist
Before launch, confirm:
- the API key never reaches the browser or repository;
- model IDs and limits are current;
- context and output are bounded;
- schemas and tool arguments are validated;
- users are authorized for each data source and action;
- consequential actions require confirmation or deterministic policy;
- prompt injection is tested;
- retries are limited and idempotent;
- costs, rate limits and latency are monitored;
- evaluations cover real failure modes;
- data retention and deletion are documented;
- a graceful fallback exists.
Frequently asked questions
Is the Claude API free?
It may include promotional or evaluation credits, but normal use is metered. A Claude Free or Pro subscription does not create a general pool of API tokens.
How do I get a Claude API key?
Create a developer account in the Claude Console, configure billing as required and generate a key. Store it in a secret manager or environment variable.
Which Claude model is best for API development?
Sonnet is the usual general-purpose starting point. Haiku fits fast bounded work, while Opus or Fable can be justified for harder tasks. Test on representative data.
Does the Claude API remember conversations?
The Messages API is stateless. The application sends the relevant history with each request and owns storage and retrieval.
Can Claude return JSON?
Yes. Prefer structured outputs with a schema where supported, and validate the result in application code.
Can Claude call my API?
Claude can request a defined tool call. Your trusted application validates, authorizes and executes that call, then returns the result.
Does Anthropic train on API data?
Anthropic says commercial API inputs and outputs are not used for generative-model training by default. Exceptions and optional programs require careful reading of the current terms.
Is the Claude API HIPAA-ready?
Some enterprise configurations and agreements support regulated workloads. Eligibility depends on the product, contract, controls and use case; an API key alone is not a compliance program.
Bottom line
The Claude API is easy to start and deliberately flexible. The application supplies the durable state, authorization, tools, business rules and quality controls that turn a model response into a reliable product.
Begin with one narrow workflow and a representative evaluation set. Keep keys server-side, route models by difficulty, validate every structured result and tool call, and measure cost per successful outcome. Then expand only where the evidence supports it.