Understanding Claude API Architecture
Before you write a wrapper, a retry loop or a chat feature, you need a clear picture of what happens between your code and Claude. This lesson walks through the Claude API from the outside in: where requests go, what a request and a response contain, why you must resend the conversation every time, and how to organise the code in a real Laravel or Python application.
Independent educational resource, not an official Anthropic course. API details were checked against Anthropic's documentation on 15 November 2026. The API version header and model IDs change over time, so confirm them in the linked docs.
Learning objectives
- Describe the path of a request from your user to Claude and back.
- Write a raw HTTP request to
POST /v1/messages and read each field of the response.
- Explain why the API is stateless and what that means for chat features.
- Handle every documented
stop_reason.
- Map API errors to the correct reaction.
- Structure a back-end client class in Python and in Laravel.
Prerequisites
- Lessons 1.1 and 1.2.
- An API key in the
ANTHROPIC_API_KEY environment variable.
The big picture
Browser / mobile app
| your own API (auth, rate limits, validation)
v
Your back end (Laravel, FastAPI, Node, ...)
| HTTPS POST https://api.anthropic.com/v1/messages
| headers: x-api-key, anthropic-version, content-type
v
Claude API --> model runs --> JSON message
^ |
|------------------------------|
Your back end reads content, stop_reason, usage
| validates, stores, logs
v
Response to your user
Two design rules fall out of this diagram:
- Your back end sits in the middle. It holds the API key, decides what the user may ask, and checks what comes back. Anthropic's errors documentation states that an organisation that cannot call the API from a browser should send requests from its own back end, and that is the right design anyway: a key in browser code is a key anyone can copy.
- The model call is just an HTTPS request. It can be slow, it can fail, and it costs money. Treat it like a payment gateway call, not like a local function.
The request
The Messages API is one endpoint: POST https://api.anthropic.com/v1/messages. A minimal call with curl:
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2026-10-21" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"max_tokens": 300,
"system": "You are a concise technical tutor.",
"messages": [
{"role": "user", "content": "In two sentences, what is a stop_reason?"}
]
}'
| Part | Purpose |
x-api-key header | Authenticates your request with your API key. Anthropic's authentication page documents Authorization: Bearer <key> as the primary form and also accepts x-api-key as a legacy header; the examples in this series use x-api-key, and the SDKs send the key for you (lesson 2.2). |
anthropic-version header | Pins the API version. The current docs examples send 2026-10-21. The official SDKs set the header for you. |
model | Which model runs the request (lesson 1.2). |
max_tokens | Upper limit on generated tokens for this request. |
system | Instructions that frame the whole conversation (lesson 1.6). |
messages | The conversation: a list of {"role": "user" | "assistant", "content": ...}. content is a string, or a list of content blocks (for example text and images). |
Other optional fields you will meet later include tools and tool_choice (module 4), stream (lesson 2.6), stop_sequences and output_config (structured output and effort). A note for people copying older tutorials: on Claude 4.7 and later models, and for any model from API version 2026-10-21, setting temperature, top_p or top_k to a non-default value returns a 400 error. Leave them out and steer with the prompt.
The response
A successful call returns a JSON message. This is the shape shown in Anthropic's documentation:
{
"id": "msg_01XFDUDYJgAACzvnptvVoYEL",
"type": "message",
"role": "assistant",
"content": [
{ "type": "text", "text": "Hello!" }
],
"model": "claude-opus-5-5",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": { "input_tokens": 12, "output_tokens": 6 }
}
content is always a list of blocks, not a string. Text is a block of type text. With tools or thinking, other block types appear. Never write content[0].text and assume it exists; loop over blocks and keep the text ones.
usage holds the billable token counts.
stop_reason says why generation ended. See below.
- The response header
request-id (and the request_id field in error bodies) identifies the request. Log it; Anthropic support asks for it.
Stateless conversations
The Messages API is stateless: it remembers nothing between calls. To continue a conversation you send the whole history each time, including earlier assistant replies:
{
"model": "claude-sonnet-5-5",
"max_tokens": 300,
"messages": [
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"}
]
}
Two consequences matter in production. First, your database owns the conversation: store messages yourself and rebuild the list on each request. Second, cost grows with length: every turn re-sends, and re-bills, the earlier turns as input tokens. Long chats need trimming or summarising (lessons 1.5 and 2.9). Anthropic also documents a beta feature called message threads that can hold the conversation server-side; it is in beta, so this series treats the stateless pattern as the baseline.
Also note: the last message you send must come from the user on Claude 4.6 and later. Ending with an assistant message (prefill) returns a 400 error on those models.
Stop reasons
Always read stop_reason. Anthropic documents seven values:
| stop_reason | Meaning | Your code should |
end_turn | Claude finished naturally. | Use the response. |
max_tokens | Hit your max_tokens limit. | Raise the limit or continue; the text may be incomplete. |
stop_sequence | Claude produced one of your stop sequences. | Read stop_sequence to see which. |
tool_use | Claude wants to call a tool. | Run the tool, send the result back (module 4). |
pause_turn | A server-tool loop reached its iteration limit. | Send the assistant content back to continue. |
refusal | Claude declined to respond. Returned as a normal HTTP 200. | Read stop_details; fall back or show a safe message. |
model_context_window_exceeded | The response filled the context window. | Treat the output as truncated. |
A refusal is not an HTTP error, so code that only checks the status code will miss it.
Errors
Errors are JSON with a top-level error object holding type and message, plus a request_id. Anthropic's documented status codes:
| HTTP | Type | Typical reaction |
| 400 | invalid_request_error | Fix the request. Do not retry unchanged. Also returned when a spend limit you set is reached. |
| 401 | authentication_error | Check or rotate the key. |
| 402 | billing_error | Fix billing in the Console. |
| 403 | permission_error | Check key permissions and workspace. |
| 404 | not_found_error | Check endpoint and model ID. |
| 413 | request_too_large | Send less data. |
| 429 | rate_limit_error | Back off and retry (honour retry-after). A spend-cap 429 has no retry-after and keeps failing. |
| 500 | api_error | Retry with exponential backoff. |
| 504 | timeout_error | Use streaming for long requests. |
| 529 | overloaded_error | Retry later; the API is temporarily overloaded. |
The official SDKs retry connection errors, rate limits and 5xx errors automatically, twice by default, with exponential backoff. If you call the API with raw HTTP (as the Laravel example below does), retries are your responsibility. Remember too that a streamed response can fail after the API has already returned 200; streaming error handling is covered in lesson 2.6.
Step by step: a Python client
Put the call behind one small function so the rest of your app never touches the SDK directly. Save as claude_client.py:
import anthropic
MODEL = "claude-sonnet-5-5" # keep in one place; see lesson 1.2
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
def ask(messages: list[dict], system: str | None = None, max_tokens: int = 500) -> dict:
"""Send a conversation and return text plus the facts you should log."""
kwargs = {"model": MODEL, "max_tokens": max_tokens, "messages": messages}
if system:
kwargs["system"] = system
try:
message = client.messages.create(**kwargs)
except anthropic.RateLimitError:
# The SDK already retried twice; tell the caller to try later.
return {"ok": False, "error": "rate_limited"}
except anthropic.APIConnectionError:
return {"ok": False, "error": "network"}
except anthropic.APIStatusError as e:
return {"ok": False, "error": f"api_{e.status_code}"}
text = "".join(b.text for b in message.content if b.type == "text")
return {
"ok": message.stop_reason in ("end_turn", "stop_sequence"),
"text": text,
"stop_reason": message.stop_reason,
"input_tokens": message.usage.input_tokens,
"output_tokens": message.usage.output_tokens,
"request_id": message._request_id,
}
if __name__ == "__main__":
history = [{"role": "user", "content": "What is a stop_reason? Two sentences."}]
first = ask(history, system="You are a concise technical tutor.")
print(first)
# Stateless: to continue, append the reply and the next question yourself.
history.append({"role": "assistant", "content": first["text"]})
history.append({"role": "user", "content": "Which value means my reply was cut short?"})
print(ask(history, system="You are a concise technical tutor."))
Notes on the code: more specific exception classes are caught first, because the SDK raises typed errors; message._request_id is the SDK's way to read the request ID; and the function returns ok only for normal endings, so a max_tokens or refusal result is never silently treated as a success.
Step by step: a Laravel client
This version uses Laravel's HTTP client directly. Add the settings to config/services.php:
'anthropic' => [
'key' => env('ANTHROPIC_API_KEY'),
'version' => env('ANTHROPIC_VERSION', '2026-10-21'),
'model' => env('ANTHROPIC_MODEL', 'claude-sonnet-5-5'),
],
And a .env.example that contains no real key:
ANTHROPIC_API_KEY=
ANTHROPIC_VERSION=2026-10-21
ANTHROPIC_MODEL=claude-sonnet-5-5
Create app/Services/ClaudeClient.php:
<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use RuntimeException;
class ClaudeClient
{
private const ENDPOINT = 'https://api.anthropic.com/v1/messages';
/**
* @param array<int, array{role: string, content: string}> $messages
* @return array{text: string, stop_reason: string, input_tokens: int, output_tokens: int, request_id: ?string}
*/
public function ask(array $messages, ?string $system = null, int $maxTokens = 500): array
{
$payload = [
'model' => config('services.anthropic.model'),
'max_tokens' => $maxTokens,
'messages' => $messages,
];
if ($system !== null) {
$payload['system'] = $system;
}
try {
$response = Http::withHeaders([
'x-api-key' => config('services.anthropic.key'),
'anthropic-version' => config('services.anthropic.version'),
])
->acceptJson()
->timeout(60)
// 3 attempts in total (Laravel counts the first try). Retry transient failures only: 429, 500, 529.
->retry(2, 1000, fn ($e) => $e instanceof ConnectionException
|| ($e instanceof RequestException && in_array($e->response->status(), [429, 500, 529], true)),
throw: false)
->post(self::ENDPOINT, $payload);
} catch (ConnectionException $e) {
throw new RuntimeException('Could not reach the Claude API.', 0, $e);
}
if ($response->failed()) {
// Log the request id so the failure can be traced; never log the API key.
logger()->warning('Claude API error', [
'status' => $response->status(),
'type' => $response->json('error.type'),
'request_id' => $response->header('request-id'),
]);
throw new RuntimeException('Claude API request failed with status '.$response->status());
}
$blocks = collect($response->json('content', []));
return [
'text' => $blocks->where('type', 'text')->pluck('text')->implode(''),
'stop_reason' => (string) $response->json('stop_reason'),
'input_tokens' => (int) $response->json('usage.input_tokens'),
'output_tokens' => (int) $response->json('usage.output_tokens'),
'request_id' => $response->header('request-id') ?: null,
];
}
}
Use it from a controller or job:
$result = app(\App\Services\ClaudeClient::class)->ask(
[['role' => 'user', 'content' => 'In two sentences, what is a stop_reason?']],
system: 'You are a concise technical tutor.',
);
if ($result['stop_reason'] !== 'end_turn') {
// max_tokens, refusal, ... decide what your product does; do not show half an answer silently.
}
Test it without spending money by faking the HTTP layer:
use App\Services\ClaudeClient;
use Illuminate\Support\Facades\Http;
it('reads text, usage and request id from a Claude response', function () {
Http::fake([
'api.anthropic.com/*' => Http::response([
'content' => [['type' => 'text', 'text' => 'Hello!']],
'stop_reason' => 'end_turn',
'usage' => ['input_tokens' => 12, 'output_tokens' => 6],
], 200, ['request-id' => 'req_test']),
]);
$r = app(ClaudeClient::class)->ask([['role' => 'user', 'content' => 'Hi']]);
expect($r['text'])->toBe('Hello!')
->and($r['input_tokens'])->toBe(12)
->and($r['request_id'])->toBe('req_test');
Http::assertSent(fn ($req) => $req->hasHeader('anthropic-version') && $req['messages'][0]['content'] === 'Hi');
});
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A Laravel help-desk adds "suggest a reply". The controller loads the ticket thread from MySQL, turns it into the messages list, calls ClaudeClient::ask() in a queued job, stores the suggestion with its token counts and request ID, and shows it to an agent who edits and sends it. The statelessness of the API is invisible to the agent, because the database already holds the thread. The token counts feed a cost report. If stop_reason is max_tokens, the job retries once with a larger limit; if it is refusal, the UI shows "No suggestion available" and the agent writes the reply.
Common errors and solutions
| Symptom | Cause | Fix |
| 401 right after deployment | Env var missing on the server, or config cached with an empty value. | Set the variable, then run php artisan config:clear and re-cache. |
400 mentioning messages | Empty content, or the last message is from the assistant on a model that rejects prefill. | End with a user message; validate input before sending. |
Undefined array key on content.0.text | First block was not text (tools, thinking). | Filter blocks by type, as in both clients above. |
| Replies suddenly cut off | stop_reason is max_tokens. | Raise max_tokens; check the reason in code. |
| Timeouts on long answers | A non-streaming request waited too long. | Use streaming (lesson 2.6) or the Batch API for long jobs. |
Security considerations
- The key lives only on your server, in environment variables or a secret manager. Rotate it if it ever appears in a log, a screenshot or Git history.
- Authenticate and rate-limit your own endpoint. Otherwise anyone who finds it can spend your money.
- Validate user input length before sending it; you pay for every token.
- Never log full prompts that may contain personal data unless your privacy policy covers it. Log the request ID, model, token counts and status.
- Treat the response as untrusted text: escape it before putting it in HTML, and never run it as code or SQL.
Performance and cost considerations
- Put model calls in queued jobs when the user does not need to watch the answer arrive.
- Resent history is billed again every turn. Trim or summarise old turns.
- Set a sensible
max_tokens per feature rather than one huge default.
- Record
usage for every call so cost is visible per feature, per user, per day.
Key takeaways
- Your back end calls
POST /v1/messages with x-api-key, anthropic-version and a JSON body.
- The API is stateless; you store and resend the conversation.
content is a list of blocks; read text blocks, not content[0].
- Check
stop_reason and handle max_tokens and refusal explicitly.
- Map errors by HTTP status; retry 429, 500 and 529 with backoff, never 400.
Lesson recap: the request path, how to read a response, and how to react to errors.
Knowledge check
- Why does a chat feature built on the Messages API need its own database table for messages?
- Your code reads
content[0].text and sometimes crashes. What is the correct approach?
- A response has HTTP status 200 and
stop_reason of refusal. Is that an error? How do you detect it?
- Which of these should you retry with backoff: 400, 401, 429, 529?
- Why should the API key never be placed in front-end JavaScript?
Answers and explanations
- The API is stateless. It remembers nothing, so your application must store the history and send it with every request.
- Loop over
content and keep blocks whose type is text. Other block types (tool use, thinking) can appear first.
- It is not an HTTP error; the call succeeded. You detect it only by reading
stop_reason (and stop_details), so always check it.
- 429 and 529 are transient and worth retrying with backoff. 400 means the request is wrong and will fail again unchanged; 401 means the key is wrong.
- Anyone can read it from the page or network tab and spend your money. Calls belong on your back end, which also lets you add authentication and limits.
Related tutorials
Official references and further reading