Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.
What you will learn
- Build a Messages API call by hand as one HTTPS POST with a JSON body, and read the JSON reply and status
- Make the same call with the Python and TypeScript SDKs and see that the wire request is identical
- Map 401, 400 and 429 responses to the SDK's typed exceptions
- Send independent calls together with AsyncAnthropic and asyncio.gather
Before you start
- The Claude Messages API: your first call
- Basic Python (TypeScript helps)
A company has two services that need Claude. A billing service written in Python, and a web app server written in TypeScript. Both want one-line summaries of release notes.
Underneath, both talk to the same thing: a REST API. One HTTPS request, a JSON body going in, JSON coming back. The client SDKs are a layer on top of that request. In this article we send the same request three ways (by hand, with the Python SDK, with the TypeScript SDK), then read what the status code says when it fails, and finally send several calls at once with the async client.
All the output below comes from the lecture projects, where a stand-in model (an httpx mock transport) answers instead of the real API. Every reply starts with test model reply, and the token numbers are made up for the demo. No API key is used.
The SDK is the waiter
Think of a restaurant. You can walk into the kitchen yourself: write the order slip, stamp it the kitchen's way, and walk back again if the kitchen is busy. Or you can send a waiter, who writes the slip, adds the stamps and comes back when the kitchen is busy.
Same kitchen, same slip. Only who writes it changes. The Claude API is the kitchen, the HTTP request is the slip, and the SDK is the waiter.
raw_rest.py: the request built by hand
First, no SDK at all. One POST to /v1/messages, three headers set by hand, and a JSON body with the three fields every Messages call needs.
"""The Messages API with no SDK: one HTTPS request that we build ourselves."""
import httpx2 as httpx
import stand_in
URL = "https://api.anthropic.com/v1/messages"
ASK = "Summarise release 4.2 in one line."
def summarise(version):
headers = {
"authorization": "Bearer test-key",
"anthropic-version": version,
"content-type": "application/json",
}
body = {
"model": stand_in.MODEL,
"max_tokens": 256,
"messages": [{"role": "user", "content": ASK}],
}
with httpx.Client(transport=stand_in.mock_transport()) as http:
r = http.post(URL, headers=headers, json=body)
r.raise_for_status()
return r.json()["content"][0]["text"]
The project sends a placeholder Bearer test-key because a stand-in answers. Against the real API, a Console API key normally goes in the x-api-key header; the SDK sets that for you.
We read the JSON reply ourselves and dig the text out of content[0]. The project imports httpx2, the HTTP library that the 2.x Python SDK is built on.
sdk_call.py and sdk_call.ts: the same request through an SDK
Now the Python SDK. The key is set once on the client, and messages.create builds the headers, the version and the JSON for us. A typed Message comes back, and we read its text blocks.
"""The same request through the Python SDK: the client builds the HTTPS request."""
from anthropic import Anthropic, DefaultHttpxClient
import stand_in
def make_client():
http = DefaultHttpxClient(transport=stand_in.mock_transport())
return Anthropic(api_key="test-key", http_client=http)
def summarise(client):
message = client.messages.create(
model=stand_in.MODEL,
max_tokens=256,
messages=[{"role": "user", "content": "Summarise release 4.2 in one line."}],
)
for block in message.content:
if block.type == "text":
return block.text
And in TypeScript. new Anthropic gives the same client, await client.messages.create is the same call, with the same fields.
// The same request through the TypeScript SDK.
import Anthropic from "@anthropic-ai/sdk";
import { MODEL, WIRE, standInFetch } from "./stand_in.ts";
const client = new Anthropic({ apiKey: "test-key", fetch: standInFetch });
const message = await client.messages.create({
model: MODEL,
max_tokens: 256,
messages: [{ role: "user", content: "Summarise release 4.2 in one line." }],
});
for (const block of message.content) {
if (block.type === "text") console.log("reply:", block.text);
}
console.log(WIRE[0]);
The stand-in writes down what reached it, so we can compare the requests. Here is python run_all.py, then node --experimental-strip-types sdk_call.ts:
raw https
reply: test model reply: the release adds dark mode.
POST /v1/messages
headers: authorization, anthropic-version, content-type
body: max_tokens, messages, model
python sdk
reply: test model reply: the release adds dark mode.
POST /v1/messages
headers: authorization, anthropic-version, content-type
body: max_tokens, messages, model
same wire request: True
reply: test model reply: the release adds dark mode.
POST /v1/messages
headers: authorization, anthropic-version, content-type
body: max_tokens, messages, model
Same endpoint, same three headers, same three body fields. The SDKs add a few small headers of their own, but these three are the ones the API needs. The stand-in only prints those three.
The same app twice: tools and streaming
A single call is easy to line up. Does it still hold with a tool and a streamed answer? The second project is a small parcel tracker. A customer asks Where is parcel P-204?, Claude asks for the track_parcel tool, the app runs it, sends a tool_result back, and the answer streams in. One team writes it in Python, another in TypeScript. Think of sheet music: the notes (model, tools, messages) are written once, and you can play them on a piano or a guitar.
The Python version:
def ask(question, client):
messages = [{"role": "user", "content": question}]
first = client.messages.create(
model=MODEL, max_tokens=256, tools=TOOLS, messages=messages)
call = next(b for b in first.content if b.type == "tool_use")
result = track_parcel(**call.input)
messages.append({"role": "assistant", "content": first.content})
messages.append({"role": "user", "content": [
{"type": "tool_result", "tool_use_id": call.id,
"content": json.dumps(result)}]})
chunks = []
with client.messages.stream(model=MODEL, max_tokens=256, tools=TOOLS,
messages=messages) as stream:
for text in stream.text_stream:
chunks.append(text)
final = stream.get_final_message()
return first.stop_reason, call, chunks, final
The TypeScript version:
export async function ask(question: string, client: Anthropic) {
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: question }];
const first = await client.messages.create({
model: MODEL, max_tokens: 256, tools: TOOLS, messages,
});
const call = first.content.find(
(b): b is Anthropic.ToolUseBlock => b.type === "tool_use")!;
const { parcel_id } = call.input as { parcel_id: string };
const result = trackParcel(parcel_id);
messages.push({ role: "assistant", content: first.content });
messages.push({ role: "user", content: [
{ type: "tool_result", tool_use_id: call.id,
content: JSON.stringify(result) }] });
const chunks: string[] = [];
const stream = client.messages
.stream({ model: MODEL, max_tokens: 256, tools: TOOLS, messages })
.on("text", (text) => chunks.push(text));
const final = await stream.finalMessage();
return { stop: first.stop_reason, call, chunks, final };
}
| Step | Python | TypeScript |
|---|---|---|
| The call | client.messages.create(...) | await client.messages.create({...}) |
| Find the tool block | generator with next(...) | .find() with a type guard |
| The chunks | for text in stream.text_stream | .on("text", ...) |
| The whole message | stream.get_final_message() | await stream.finalMessage() |
| Everything else | Same fields (model, max_tokens, tools, messages), same tool_result block, same stop reasons | |
Both apps, one after the other (python run_all.py):
python | tool_use -> track_parcel P-204
4 chunks | end_turn | tokens 22
test model reply: out for delivery in Leeds, due Friday.
typescript | tool_use -> track_parcel P-204
4 chunks | end_turn | tokens 22
test model reply: out for delivery in Leeds, due Friday.
The language changes the spelling, not the request. A TypeScript team holding a guide written in Python doesn't need to port anything: the fields are the same.
What goes over the wire, and what the status says
Open one call and you see a normal HTTP exchange. The request has a method, a URL, headers and a body. The response has a status, headers (including a request-id) and a body. On a 200 the body holds content (a list of blocks), stop_reason and usage. Anything else means an error body, which is JSON as well, with an error type.
The third project, a SupportDesk slice, sends ticket T-401 by hand and checks the status before reading the body:
"""One call to Claude by hand: an HTTP POST, a JSON body, a JSON answer."""
from stand_in import MODEL
URL = "https://api.anthropic.com/v1/messages"
HEADERS = {"authorization": "Bearer test-key", "anthropic-version": "2026-10-21",
"content-type": "application/json"}
def ask(http, text, headers=HEADERS, model=MODEL):
body = {"model": model, "max_tokens": 256,
"messages": [{"role": "user", "content": text}]}
r = http.post(URL, headers=headers, json=body)
data = r.json()
if r.status_code != 200:
err = data["error"]["type"]
return f"{r.status_code} {err} | {data['request_id']}"
text = data["content"][0]["text"]
return f"{r.status_code} {text} | {r.headers['request-id']}"
Through the SDK, a bad status is no longer raw JSON. It is a typed exception, caught by class, and the request id is a property on the response:
"""The same call through the SDK: it writes the request, reads the answer."""
import anthropic
from stand_in import MODEL
def ask(client, text, model=MODEL):
try:
r = client.messages.create(model=model, max_tokens=256,
messages=[{"role": "user", "content": text}])
return f"{r.content[0].text} | {r._request_id}"
except anthropic.APIStatusError as err:
return f"{err.status_code} {type(err).__name__}"
The stand-in answers a bad key with a 401, an unknown model with a 400 and ticket T-402 with a 429:
raw REST (httpx)
T-401 ok -> 200 test model reply: T-401 answered. | req_test_01
T-401 bad key -> 401 authentication_error | req_test_02
T-401 bad model -> 400 invalid_request_error | req_test_03
T-402 rate -> 429 rate_limit_error | req_test_04
SDK (anthropic)
T-401 ok -> test model reply: T-401 answered. | req_test_01
T-401 bad key -> 401 AuthenticationError
T-401 bad model -> 400 BadRequestError
T-402 rate -> 429 RateLimitError
| Status | Error type in the body | SDK exception |
|---|---|---|
| 401 | authentication_error | AuthenticationError |
| 400 | invalid_request_error | BadRequestError |
| 429 | rate_limit_error | RateLimitError |
Retrying a 400 or a 401 just fails the same way again. How the SDK retries, and a policy per error class, are in SDK timeouts, retries and error classes.
Async: three tickets waiting together
A call spends most of its time waiting for the network. The async client is the same SDK with the same calls, but each one is awaited, which means wait here, and let other work run meanwhile.
"""Many tickets at once: AsyncAnthropic, an await per call, gather for all."""
import asyncio
import anthropic
from stand_in import MODEL, make_async_client
client = make_async_client()
async def ask(ticket):
try:
msgs = [{"role": "user", "content": ticket}]
r = await client.messages.create(model=MODEL, max_tokens=256, messages=msgs)
return r.content[0].text
except anthropic.APIStatusError as err:
return type(err).__name__
async def one_by_one(tickets):
return [await ask(t) for t in tickets]
async def together(tickets):
return await asyncio.gather(*(ask(t) for t in tickets))
The stand-in delays three tickets by 0.3, 0.2 and 0.1 seconds. These delays are made up: they show the overlap, not real speed. T-502 is rate limited.
async (AsyncAnthropic)
one by one | in flight max 1 | 0.6 s
finished: T-501 T-502 T-503
result: test model reply: T-501 answered.
result: RateLimitError
result: test model reply: T-503 answered.
together | in flight max 3 | 0.3 s
finished: T-503 T-502 T-501
result: test model reply: T-501 answered.
result: RateLimitError
result: test model reply: T-503 answered.
One by one, the waits add up. Together, all three wait at once. The shortest call finishes first, but gather still hands back the results in the order we asked. And because ask catches the error, the rate-limited ticket became a result instead of a crash, so the other two still answered.
Seven SDKs, one CLI, and where WebSockets fit
Python and TypeScript are two of seven official client SDKs: Python, TypeScript, C#, Go, Java, PHP and Ruby. Each speaks its own language's idioms (an async client in Python, builders in Java). Next to them sits ant, the command-line tool, which builds the request from typed flags so you don't write the JSON by hand. Libraries such as the OpenAI SDK compatibility layer are a different thing: they are not general-purpose Messages API clients.
What you get from an SDK is the work around the request: the headers, retries and a timeout (two retries and ten minutes by default), typed exceptions, a request id on every reply, and streaming built in.
Streaming from the Messages API uses server-sent events, which you ask for with stream: true. A WebSocket is not part of the Claude API call. It is one choice for the hop you build yourself, from your server to the browser, so the API key stays on your server and never lands in the page. (The TypeScript SDK refuses to run in a browser by default for that reason.) The event order and a working relay are in Claude streaming events and stop reasons.
Common mistakes
- Hand-writing the HTTP call in every service. You repeat headers, retries, error handling and streaming in every language. Use the official SDK for each language; the request underneath is the same.
- Opening a WebSocket to the Messages API. Its streaming is server-sent events. A WebSocket only belongs on your own hop to the browser.
- Calling Claude from the browser. That puts the secret key in the page. Call from your server and relay.
- Searching the reply text for the answer. The answer lives in JSON content blocks. Check the status, then read
content. - Retrying every non-200. A 400 or 401 fails the same way again. Fix the request or the key.
- Awaiting independent calls in a loop. They wait in line. Use
asyncio.gatherand catch errors per call.
Quick recap
| Idea | What to remember |
|---|---|
| REST | A Claude call is a POST to /v1/messages with a JSON body |
| Response | A status, a request-id header, then JSON: content, stop_reason, usage |
| SDK | Writes the headers and JSON, adds retries, a timeout, typed errors and streaming |
| Languages | Seven client SDKs plus the ant CLI, one API: the spelling changes, not the request |
| Async | await each call, gather independent ones |
| WebSocket | Your own relay to the browser; Claude streams SSE |
Try it yourself
Take async_calls.py and add a fourth ticket the stand-in answers with a 401. Run together again. Does the order of the results still match the order you asked? Then remove the try/except in ask and see what gather does when one call raises.
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
The Claude Messages API: Your First Call, Field by Field
One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.
Claude Tool Use: How tool_use and tool_result Work in the Messages API
Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.
Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.
Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
Read one streamed Claude reply event by event, relay its text deltas to a browser over a WebSocket, then fix four stream handlers from their event logs: the terminal event, tool arguments, stop reasons and the real token count.