Claude API Rust Client Implementation Guide
Building a Claude API client in Rust means writing an HTTP layer on top of reqwest (or hyper directly), serializing requests with serde, and handling Anthropic's streaming format (server-sent events) if you need token-by-token responses. There's no official Anthropic SDK for Rust, so most teams either hand-roll a thin client against the Messages API or depend on one of a handful of community crates that wrap the same endpoints.
This guide walks through a working implementation: the request/response types, async streaming, error handling, and where to plug in retries or a gateway if you'd rather not maintain auth and rate-limit logic yourself.
Why Rust for a Claude Client
Rust is a reasonable choice when you're building a backend service, CLI tool, or embedded system that calls an LLM and needs predictable latency and memory usage. Typical use cases: a Rust web server (Axum, Actix) proxying requests to Claude, a CLI assistant, or a data pipeline that classifies records with structured outputs.
The tradeoff is that you own the HTTP plumbing: retry logic, rate-limit backoff, streaming parsing, and keeping request/response types in sync with API changes. None of this is hard, but it's maintenance surface that a managed layer can absorb.
Core Dependencies
A minimal client needs:
[dependencies]
reqwest = { version = "0.12", features = ["json", "stream"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"] }
futures-util = "0.3"
reqwest with the stream feature gives you access to the response body as a byte stream, which you need for server-sent events.
Request and Response Types
Model the Messages API shape with serde:
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
struct MessageRequest {
model: String,
max_tokens: u32,
messages: Vec<Message>,
}
#[derive(Serialize, Deserialize, Clone)]
struct Message {
role: String,
content: String,
}
#[derive(Deserialize)]
struct MessageResponse {
id: String,
content: Vec<ContentBlock>,
usage: Usage,
}
#[derive(Deserialize)]
struct ContentBlock {
#[serde(rename = "type")]
block_type: String,
text: Option<String>,
}
#[derive(Deserialize)]
struct Usage {
input_tokens: u32,
output_tokens: u32,
}
A Blocking-Style Async Call
use reqwest::Client;
async fn send_message(
client: &Client,
api_key: &str,
prompt: &str,
) -> Result<MessageResponse, reqwest::Error> {
let body = MessageRequest {
model: "claude-sonnet-4".to_string(),
max_tokens: 1024,
messages: vec![Message {
role: "user".to_string(),
content: prompt.to_string(),
}],
};
client
.post("https://api.anthropic.com/v1/messages")
.header("x-api-key", api_key)
.header("anthropic-version", "2023-06-01")
.json(&body)
.send()
.await?
.json::<MessageResponse>()
.await
}
This covers the happy path. Production code needs explicit error handling for rate limits (HTTP 429), overloaded errors (529), and malformed payloads — Anthropic's error responses include a type field you should match on rather than relying purely on status codes.
Streaming Responses
Claude's streaming API sends text/event-stream chunks. In Rust, you consume the response body as a byte stream and parse each data: {...} line as JSON:
use futures_util::StreamExt;
async fn stream_message(client: &Client, api_key: &str) -> Result<(), Box<dyn std::error::Error>> {
let mut stream = client
.post("https://api.anthropic.com/v1/messages")
.header("x-api-key", api_key)
.header("anthropic-version", "2023-06-01")
.json(&serde_json::json!({
"model": "claude-sonnet-4",
"max_tokens": 512,
"stream": true,
"messages": [{"role": "user", "content": "Explain ownership in Rust"}]
}))
.send()
.await?
.bytes_stream();
while let Some(chunk) = stream.next().await {
let bytes = chunk?;
let text = String::from_utf8_lossy(&bytes);
for line in text.lines() {
if let Some(data) = line.strip_prefix("data: ") {
if data == "[DONE]" {
break;
}
let event: serde_json::Value = serde_json::from_str(data)?;
if let Some(delta) = event["delta"]["text"].as_str() {
print!("{delta}");
}
}
}
}
Ok(())
}
This naive line-splitting approach works for most SSE payloads but breaks if a JSON chunk spans multiple TCP reads. For production use, buffer incomplete lines across chunks rather than assuming each bytes_stream() item aligns with a full SSE event.
Error Handling and Retries
Rust's Result type makes error propagation explicit, but you still need a retry strategy for transient failures. A common pattern:
async fn with_retry<F, Fut, T>(mut f: F, max_attempts: u32) -> Result<T, reqwest::Error>
where
F: FnMut() -> Fut,
Fut: std::future::Future<Output = Result<T, reqwest::Error>>,
{
let mut attempt = 0;
loop {
match f().await {
Ok(val) => return Ok(val),
Err(e) if attempt < max_attempts => {
attempt += 1;
tokio::time::sleep(std::time::Duration::from_millis(500 * attempt as u64)).await;
}
Err(e) => return Err(e),
}
}
}
Exponential backoff on 429/529 responses, combined with a jitter, keeps you within rate limits without hammering the API during transient overload.
Avoiding the Maintenance Overhead
If you're writing this client for a single internal tool, hand-rolled code like above is fine. If you're building a product that multiple team members or services will call, you'll end up re-implementing key rotation, per-service usage tracking, and streaming reconnection logic — all things that have nothing to do with your actual product.
SubToAPI sits in front of your Claude access and exposes a stable HTTPS API with sub_live_... application keys, so your Rust client only needs to point at a different base URL and auth header — streaming, tool use, and usage metadata work the same way. Check the quickstart and streaming docs for the exact request shapes, and pricing if you're evaluating it against maintaining your own client and billing dashboard.
questions
Is there an official Anthropic Rust SDK? No. Anthropic maintains official SDKs for Python and TypeScript. Rust developers either write a thin reqwest-based client against the Messages API or use a community crate, which may lag behind new API features.
How do I handle streaming in Rust without dropping partial JSON chunks? Buffer incoming bytes in a String or Vec<u8> across stream reads and only parse a line once you've seen a full \n\n delimiter. Don't assume each bytes_stream() item is a complete SSE event.
Can I use tool use (function calling) from a Rust client? Yes — tool definitions and tool_use/tool_result content blocks are just JSON fields in the request and response, so they serialize/deserialize with serde like any other field. See /docs/tools for the exact schema if you're routing calls through SubToAPI.