Users Pricing

articles

Home Articles Getting Started With the Claude API, A Complete Developer Guide – MindStick
Getting Started With the Claude API, A Complete Developer Guide

Getting Started With the Claude API, A Complete Developer Guide

Chinmay Kale 124 25 Nov 2026

Claude, the family of AI models built by Anthropic, is available in the Claude apps and also through an API that lets you build Claude into your own software. Developers use it for chatbots, document analysis, coding assistants, content pipelines, data extraction and autonomous agents.

This guide takes you from zero to a working, production-minded integration. It covers setup, the core Messages API, conversations, system prompts, streaming, choosing a model, handling errors and the habits that save you trouble later.

What you need before you start

- An account on the Claude Console, Anthropic's developer platform.
- An API key, created in the Console under API keys.
- Some credit or a billing plan on the account.
- Python 3.8 or later, or Node.js, depending on your language.

Treat the API key like a password. Store it in an environment variable or a secrets manager, never in source code, and never in a front-end app where users can see it.

On Linux or macOS you can set it for the current shell session with an export command, giving the variable the name ANTHROPIC_API_KEY. On Windows, use the System Properties environment variables dialog or the setx command. The official SDKs read this variable automatically.

Install the SDK

Anthropic provides official SDKs for several languages, including Python, TypeScript, Java, Go, Ruby, C# and PHP. The two most common are:

- Python: install the anthropic package with pip.
- TypeScript and JavaScript, install the anthropic-ai sdk package with npm.

You can also call the API directly over HTTPS with any HTTP client, which is useful for languages without an SDK.

Your first request

The core endpoint is the Messages API. You send a model name, a maximum output length and a list of messages, and Claude replies.

import anthropic

client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY

message = client.messages.create(
model="claude-sonnet-5-5",
matokens=1024,
messages=[{"role": "user", "content": "Explain recursion in two sentences."}],
)
print(message.content[0].text)

That is a complete, working program. Let us look at what each part does.

- model: which Claude model to use. Model IDs look like claude-sonnet-5-5 or claude-haiku-5-5.
- matokens: the maximum number of tokens Claude may generate. It is required. If Claude reaches it, the response stops early.
- messages: the conversation so far, as a list of objects with a role (user or assistant) and content.

Understanding the response

The response object contains several useful fields:

- content: a list of content blocks. For a plain text answer it contains one text block. With tool use or thinking, it may contain several blocks of different types.
- stop_reason: why generation stopped. Common values are end_turn (finished naturally), matokens (hit your limit), stop_sequence and tool_use.
- usage: input and output token counts, plus cache figures if you use prompt caching.
- id and model: useful for logging.

Always check stop_reason. If it says matokens, the answer was cut off, and you should either raise the limit or handle the partial result.

Adding a system prompt

The system parameter sets Claude's role, rules and context for the whole conversation. It is separate from the messages list.

message = client.messages.create(
model="claude-sonnet-5-5",
matokens=800,
system="You are a senior .NET mentor. Answer briefly with one code example.",
messages=[{"role": "user", "content": "How do I read a JSON file in C#?"}],
)

Good system prompts describe who the assistant is, who the user is, the goal, the rules and the output format. Our article on writing effective system prompts for Claude goes deeper.

Multi-turn conversations

The API is stateless. Claude does not remember previous requests. To hold a conversation, your application keeps the history and sends it every time, alternating user and assistant messages.

history = []

def chat(user_text):
history.append({"role": "user", "content": user_text})
reply = client.messages.create(model="claude-sonnet-5-5",
matokens=1024, messages=history)
text = reply.content[0].text
history.append({"role": "assistant", "content": text})
return text

For long conversations, history grows and so do cost and latency. Trim or summarise older turns, as described in our article on context windows.

Streaming responses

For chat interfaces, streaming lets users see text as it is generated instead of waiting for the full answer. The SDKs provide a streaming helper that yields text chunks as they arrive.

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

Streaming is also recommended for long outputs, because very long non-streaming requests can hit network timeouts. Our article on streaming responses from Claude in a web app shows how to pass the stream through to a browser.

Sending images and documents

Claude models can read images and PDFs. You include them as content blocks alongside text in a user message, either as base64-encoded data or, in some cases, by referencing a file uploaded through the Files API. This makes it straightforward to build invoice readers, screenshot analysers or document question-answering tools.

Large files consume many tokens, so check usage figures when working with long PDFs.

Choosing a model

Anthropic offers several model tiers, which trade capability against speed and cost. At the time of writing, the current lineup includes:

- Claude Haiku 5.5: the fastest and most affordable, ideal for high-volume tasks, classification, routing and quick replies.
- Claude Sonnet 5.5: a strong balance of intelligence, speed and cost, a sensible default for most applications.
- Claude Opus 5.5: Anthropic's most capable widely available model for complex reasoning, difficult coding and agentic work.
- Claude Fable 5.2: a newer, more capable tier for the hardest problems, at a higher price.

Models change, so do not hard-code assumptions. The Models API lets your code list available models with their context window and output limits. Our article on choosing the right Claude model compares them in more detail.

Key parameters worth knowing

- temperature: controls randomness. Lower for factual and extraction tasks. Check the current docs, as some newer models and thinking modes restrict sampling parameters.
- stop_sequences: strings that end generation when produced.
- tools: lets Claude call your functions. See our article on tool use.
- thinking: enables extended reasoning on supported models for harder problems, at the cost of more tokens.
- metadata: lets you pass a user identifier to help with abuse detection.

Handling errors

Production code must handle failures gracefully. The main HTTP error codes are:

- 400 invalid request: something is wrong with your request, such as a bad parameter or a prompt that is too long.
- 401 authentication error: missing or invalid API key.
- 403 permission error: the key lacks access to the resource.
- 404 not found: wrong model name or endpoint.
- 413 request too large: the request body exceeded the size limit.
- 429 rate limit error: you sent too many requests or tokens, or reached a spend limit.
- 500 API error: an unexpected problem on Anthropic's side.
- 529 overloaded: the service is temporarily under heavy load.

The official SDKs retry certain errors automatically, by default twice with exponential backoff, and respect the retry-after header when it is present. You can configure the number of retries and the timeout when creating the client.

client = anthropic.Anthropic(maretries=4, timeout=60.0)

try:
reply = client.messages.create(model="claude-haiku-5-5", matokens=300,
messages=[{"role": "user", "content": "Ping"}])
except anthropic.RateLimitError:
print("Slow down and retry later")
except anthropic.APIStatusError as e:
print("API error", e.status_code)

Log the request ID from responses and errors. It helps Anthropic support investigate problems. Our article on fixing Claude API rate limit and overloaded errors covers this topic in depth.

Rate limits and usage tiers

Anthropic applies limits on requests per minute and tokens per minute, which increase as your organisation moves up usage tiers. The Console shows your current limits. Response headers also report remaining capacity, which you can use to throttle your own traffic.

Cost control from day one

- Log usage from every response.
- Start with a smaller model and move up only where quality requires it.
- Use prompt caching for long, repeated system prompts and documents.
- Use the Message Batches API for non-urgent bulk work at a discount.
- Set spend limits and alerts in the Console.

Security checklist

- Keep API keys on the server side only.
- Use separate keys for development and production.
- Rotate keys periodically and immediately if exposed.
- Validate and limit user input length before sending it.
- Treat model output as untrusted when it is used to run code, build queries or render pages.
- Follow Anthropic's usage policies for your use case.

Where to go next

Once your first integration works, explore:

1. Tool use, so Claude can call your APIs and databases.
2. Structured outputs, for reliable JSON.
3. Prompt caching, for lower cost and latency.
4. Agents, for multi-step tasks.
5. Model Context Protocol, for connecting Claude to external systems in a standard way.

Key takeaways

- The Messages API is the core: model, max tokens and messages.
- The API is stateless, so your app manages conversation history.
- Use system prompts for roles and rules.
- Stream for responsiveness and long outputs.
- Check stop_reason and usage on every response.
- Handle errors with retries and logging.
- Keep keys secret and costs visible from the start.

With these fundamentals in place, you can build almost any Claude-powered feature with confidence.

Related articles on MindStick

- Tool Use in Claude, Letting the Model Call Your Functions
- Streaming Responses From Claude in a Web App
- Choosing the Right Claude Model for Speed, Cost and Quality
- Fixing Claude API Rate Limit and Overloaded Errors

Model names, parameters, pricing and limits change over time. Refer to Anthropic's official Claude documentation for the latest details.


Chinmay Kale

Cybersecurity Engineer at Cognizant

Hi, I am Chinmay. I work as a Cybersecurity Engineer at Cognizant, Bengaluru and my work is mostly about security controls, SIEM and endpoint protection. Before this I spent 3 years at EY. I studied B.Tech in Computer Science from Veermata Jijabai Technological Institute, Mumbai. I am originally from Mumbai, Maharashtra. Weekends are for cooking.


Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md