Claude API Rust SDK Integration Example (No Official SDK)
Does Anthropic have an official Rust SDK for Claude?
No. As of now, Anthropic publishes official SDKs for Python and TypeScript, and the community maintains a handful of Rust crates (like anthropic-sdk or misanthropic), but none of them are officially supported, and coverage of newer features (tool use, extended thinking, batch requests) lags behind the HTTP API. If you're building a Rust service that needs Claude, the most reliable path is to call the REST API directly with reqwest and serde, which is exactly what every SDK does under the hood anyway.
This article walks through a complete, working integration: project setup, a basic chat request, streaming, and tool use, all in plain Rust with no third-party Claude-specific crate. At the end, we'll also look at pointing the same code at SubToAPI instead of Anthropic directly, which gives you a stable HTTPS endpoint, per-application API keys, and usage metadata without changing a line of your request logic.
Project setup
Add the dependencies you need to Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", features = ["json", "stream"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
futures-util = "0.3"
This is the full dependency list — no Claude-specific crate required.
A basic request
Define request and response structs that mirror the Messages API shape:
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
struct Message {
role: String,
content: String,
}
#[derive(Serialize)]
struct ChatRequest {
model: String,
max_tokens: u32,
messages: Vec<Message>,
}
#[derive(Deserialize, Debug)]
struct ContentBlock {
text: String,
}
#[derive(Deserialize, Debug)]
struct ChatResponse {
content: Vec<ContentBlock>,
}
Then the call itself:
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let api_key = std::env::var("ANTHROPIC_API_KEY")?;
let body = ChatRequest {
model: "claude-3-5-sonnet-20241022".to_string(),
max_tokens: 1024,
messages: vec![Message {
role: "user".to_string(),
content: "Explain ownership in Rust in two sentences.".to_string(),
}],
};
let res = 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::<ChatResponse>()
.await?;
println!("{}", res.content[0].text);
Ok(())
}
This is the entire integration. No SDK, no generated client, just reqwest and two structs. The pattern works identically whether you're calling Anthropic directly or a gateway that proxies the same request shape.
Streaming responses
Streaming in Rust means consuming server-sent events (SSE) from the response body as a byte stream and parsing data: lines yourself, since reqwest doesn't parse SSE natively:
use futures_util::StreamExt;
async fn stream_chat(client: &reqwest::Client, api_key: &str) -> Result<(), Box<dyn std::error::Error>> {
let body = serde_json::json!({
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"stream": true,
"messages": [{ "role": "user", "content": "Write a haiku about Rust." }]
});
let res = client
.post("https://api.anthropic.com/v1/messages")
.header("x-api-key", api_key)
.header("anthropic-version", "2023-06-01")
.json(&body)
.send()
.await?;
let mut stream = res.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
let text = String::from_utf8_lossy(&chunk);
for line in text.lines() {
if let Some(data) = line.strip_prefix("data: ") {
if data != "[DONE]" {
println!("{}", data);
}
}
}
}
Ok(())
}
This gets you raw SSE frames. In production you'd deserialize each data: line into the appropriate event type (content_block_delta, message_stop, etc.) rather than just printing it.
Tool use
Tool use just means adding a tools array to the request body and handling tool_use content blocks in the response — structurally no different in Rust than in any other language:
let body = serde_json::json!({
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"tools": [{
"name": "get_weather",
"description": "Get current weather for a city",
"input_schema": {
"type": "object",
"properties": { "city": { "type": "string" } },
"required": ["city"]
}
}],
"messages": [{ "role": "user", "content": "What's the weather in Lisbon?" }]
});
You then inspect the response content array for a block with "type": "tool_use", run your function, and send the result back in a follow-up message with "type": "tool_result".
Why reach for a gateway instead of raw Anthropic calls
The pattern above works fine for a prototype, but once you're shipping a Rust service to production you'll likely want things the raw API doesn't give you out of the box: per-application keys instead of one shared secret, usage breakdowns by key, and team access without sharing root credentials.
This is where SubToAPI fits. It wraps Claude behind a stable HTTPS endpoint and gives you sub_live_... keys scoped per application or environment, with streaming and tool use supported the same way as above. Since it speaks the same Messages-style schema, the Rust code barely changes — swap the host and header:
let res = client
.post("https://api.subtoapi.app/v1/messages")
.header("Authorization", format!("Bearer {}", std::env::var("SUBTOAPI_KEY")?))
.json(&body)
.send()
.await?;
Or test it quickly from the command line before wiring up Rust:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"claude-3-5-sonnet-20241022","max_tokens":256,"messages":[{"role":"user","content":"ping"}]}'
Full request/response details are in the docs, streaming specifics in /docs/streaming, and tool schemas in /docs/tools. If you want to go from zero to a working call in a few minutes, /docs/quickstart covers key creation and your first request, and you can start on a free trial at /signup — plans start at Solo €9/month, with Team and Scale tiers detailed on /pricing.
Keeping the integration maintainable
A few practical notes for Rust services calling Claude long-term:
- Wrap the client in a struct. Store the base URL, API key, and
reqwest::Clienttogether so you can swap endpoints (direct Anthropic vs. a gateway) with one config change. - Use
serde_json::Valuefor flexibility. Strongly typed structs are nice for the request, but Claude's response content blocks vary by type (text, tool_use, thinking), so a loosely typed enum orValueis often easier to maintain than hand-rolled structs for every block type. - Set timeouts explicitly.
reqwest::Client::builder().timeout(...)matters more for LLM calls than typical HTTP requests, since generation can legitimately take tens of seconds. - Retry on 429 and 5xx only. Don't retry on 4xx validation errors — fix the payload instead.
Questions
Is there an official Anthropic Rust crate? No. Anthropic maintains official SDKs for Python and TypeScript only. Community crates exist but aren't officially supported and may not cover the latest API features.
Can I use reqwest alone without any extra crates for Claude integration? Yes. reqwest plus serde/serde_json for (de)serialization is all you need to call the Messages API, including streaming via SSE and tool use via JSON schemas.
Why use SubToAPI instead of calling Anthropic directly from Rust? SubToAPI gives you per-application API keys, usage metadata, and team seat management on top of the same request shape, so your Rust client code stays nearly identical while you gain operational controls the raw Anthropic API doesn't provide.