Anthropic's Claude API lets you embed Claude models in your website, app, or support service through a single endpoint, the Messages API. In this guide we build a complete integration step by step, pointing out the practices you need before going to production.
1. Setup
- Create an account in the Anthropic Console and generate an API key.
- Store the key in the
ANTHROPIC_API_KEYenvironment variable and never put it in frontend code or your repository. - Install the official package.
pip install anthropic # Python
npm install @anthropic-ai/sdk # JavaScript / TypeScript2. Your first request
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
message = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
system="You are a support assistant for Mit AI. Answer in English and keep it brief.",
messages=[{"role": "user", "content": "What services does the company offer?"}],
)
print(message.content[0].text)import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // reads ANTHROPIC_API_KEY
const message = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 1024,
system: "You are a support assistant for Mit AI. Answer in English and keep it brief.",
messages: [{ role: "user", content: "What services does the company offer?" }],
});
console.log(message.content[0].text);systemis where persona instructions and rules go. It is a separate field frommessages.max_tokensis an upper bound on the reply length; if it is too small, the reply is cut off mid-sentence.- Model IDs and capabilities change quickly. Check the models page in the Anthropic documentation to choose the best fit for your case in terms of quality, speed, and cost.
- Some newer models do not accept parameters such as
temperature; if you get a 400 error, check the model-specific documentation.
3. Multi-turn conversations
The API is stateless: you send the full conversation history with every request, alternating the user and assistant roles. Keep the history in your database and trim it (the last N messages, or a summary) to control cost.
history = [
{"role": "user", "content": "I want a voice assistant for my store."},
{"role": "assistant", "content": "Great! Roughly how many products do you have?"},
{"role": "user", "content": "About 300 products."},
]
reply = client.messages.create(model="claude-opus-5-5", max_tokens=600, messages=history)4. Streaming
For chat interfaces, streaming shows the reply word by word so the user perceives it as fast, and it protects you from timeouts on long responses.
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Explain RAG simply"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message() # the full message and the tokens consumed5. Tool use
You define your tools (functions in your code) with a description and a JSON schema. When Claude needs a tool, it returns a tool_use block; you execute it and send the result back in a tool_result. This is how the assistant looks up an order status or books an appointment.
tools = [{
"name": "get_order_status",
"description": "Returns the customer's order status by order number.",
"input_schema": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
}]
messages = [{"role": "user", "content": "Where is my order A-1042?"}]
response = client.messages.create(
model="claude-opus-5-5", max_tokens=1024, tools=tools, messages=messages
)
while response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
output = lookup_order(block.input["order_id"]) # your function
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": output,
})
messages.append({"role": "user", "content": results})
response = client.messages.create(
model="claude-opus-5-5", max_tokens=1024, tools=tools, messages=messages
)
print(response.content[0].text)6. Prompt caching
If you have a long system prompt or fixed documents sent with every request, enable caching to pay less for the repeated part and get faster responses. Put cache_control on the last static block and keep the variable content after it.
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=600,
system=[{
"type": "text",
"text": LONG_COMPANY_KNOWLEDGE, # constant across requests
"cache_control": {"type": "ephemeral"},
}],
messages=[{"role": "user", "content": user_question}],
)
print(response.usage.cache_read_input_tokens) # > 0 means the cache is workingAny change in the prefix (such as a timestamp inside the system prompt) invalidates the cache. There is also a minimum cacheable content length that varies by model.
7. Errors and reliability
import anthropic
try:
message = client.messages.create(...)
except anthropic.RateLimitError:
... # 429: retry with exponential backoff
except anthropic.APIConnectionError:
... # network problem
except anthropic.APIStatusError as e:
... # all other API errors (e.status_code)- The SDK automatically retries twice by default on network errors, 429, and 5xx.
- Check
stop_reasonbefore using the reply:refusalmeans the model declined the request, andmax_tokensmeans the reply was cut off. - Log
usage(input and output tokens) for every request to monitor cost. - Set a limit on user message length and on the request rate per session to protect your budget.
How we use it in the Mit assistant
The backend of this website supports Claude as an AI provider: just set AI_PROVIDER=anthropic and an AI_API_KEY in the .env file, and if the connection fails, the assistant automatically falls back to the local knowledge base. To compare it with the other provider, read Integrating the OpenAI API and Building a unified gateway for multiple providers.
FAQ
Can I call the Claude API directly from the browser?
It is not recommended because it exposes your API key. The right approach is for the browser to call your server, and your server calls Claude.
How do I reduce the cost of using the Claude API?
Enable Prompt Caching for repeated content, trim the conversation history, tune max_tokens, choose the model best suited to the task, and monitor usage on every request.
Want an AI assistant for your business without writing code?
We build you an assistant powered by the strongest models, trained on your prices and services, and connected to your website or WhatsApp. Your first consultation is free.