← Blog

Claude API Rust Client Library Tutorial

2026-11-17 · 5 min read · SubToAPI Team

There's no official Rust SDK from Anthropic, so "Claude API Rust client library" searches usually lead to the same answer: write a thin HTTP client yourself using reqwest and serde. It's genuinely a 30-minute job, and this tutorial walks through it — a typed request/response struct, synchronous and streaming calls, and proper error handling you can drop into a production service.

If you'd rather skip maintaining auth headers, retries, and streaming parsers yourself, the same code below works unchanged against SubToAPI, which exposes Claude over a standard HTTPS API with sub_live_... keys. We'll cover both so you can decide per project.

Project setup

Start a new binary crate and add the dependencies you need: an async HTTP client, JSON serialization, and the Tokio runtime.

# Cargo.toml
[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"

Defining the message types

Model the Messages API shape with serde structs. This keeps your client type-safe instead of passing around raw serde_json::Value.

use serde::{Deserialize, Serialize};

#[derive(Serialize)]
struct MessageRequest<'a> {
    model: &'a str,
    max_tokens: u32,
    messages: Vec<Message>,
}

#[derive(Serialize, Deserialize, Clone)]
struct Message {
    role: String,
    content: String,
}

#[derive(Deserialize, Debug)]
struct MessageResponse {
    id: String,
    content: Vec<ContentBlock>,
    usage: Usage,
}

#[derive(Deserialize, Debug)]
struct ContentBlock {
    text: String,
}

#[derive(Deserialize, Debug)]
struct Usage {
    input_tokens: u32,
    output_tokens: u32,
}

Building the client struct

Wrap reqwest::Client with your base URL and API key so every call site doesn't repeat headers.

struct ClaudeClient {
    http: reqwest::Client,
    base_url: String,
    api_key: String,
}

impl ClaudeClient {
    fn new(api_key: String) -> Self {
        Self {
            http: reqwest::Client::new(),
            base_url: "https://api.subtoapi.app/v1".to_string(),
            api_key,
        }
    }

    async fn send_message(
        &self,
        model: &str,
        messages: Vec<Message>,
    ) -> Result<MessageResponse, reqwest::Error> {
        let body = MessageRequest {
            model,
            max_tokens: 1024,
            messages,
        };

        let resp = self
            .http
            .post(format!("{}/messages", self.base_url))
            .bearer_auth(&self.api_key)
            .json(&body)
            .send()
            .await?
            .error_for_status()?
            .json::<MessageResponse>()
            .await?;

        Ok(resp)
    }
}

This client targets SubToAPI's endpoint, so authentication is a plain Authorization: Bearer $SUBTOAPI_KEY header and the response shape matches the messages reference. If you point base_url at Anthropic's own API directly, swap .bearer_auth() for an x-api-key header and add the anthropic-version header manually — that's the main structural difference between the two.

Calling it from main

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("SUBTOAPI_KEY")?;
    let client = ClaudeClient::new(api_key);

    let messages = vec![Message {
        role: "user".to_string(),
        content: "Summarize the Rust ownership model in two sentences.".to_string(),
    }];

    let response = client.send_message("claude-sonnet-4", messages).await?;

    for block in &response.content {
        println!("{}", block.text);
    }
    println!(
        "tokens: {} in / {} out",
        response.usage.input_tokens, response.usage.output_tokens
    );

    Ok(())
}

Run it with SUBTOAPI_KEY=sub_live_xxx cargo run. If you don't have a key yet, sign up and copy one from the dashboard — the quickstart covers the same flow with curl if you want to sanity-check the request outside Rust first.

Adding streaming support

Rust doesn't have a built-in SSE parser, but server-sent events are line-delimited, so you can parse them by hand from a byte stream. This is the part most Rust tutorials skip, and it's where a raw reqwest client earns its keep.

use futures_util::StreamExt;

async fn stream_message(client: &ClaudeClient, prompt: &str) -> Result<(), Box<dyn std::error::Error>> {
    let body = serde_json::json!({
        "model": "claude-sonnet-4",
        "max_tokens": 1024,
        "stream": true,
        "messages": [{ "role": "user", "content": prompt }]
    });

    let resp = client
        .http
        .post(format!("{}/messages", client.base_url))
        .bearer_auth(&client.api_key)
        .json(&body)
        .send()
        .await?;

    let mut stream = resp.bytes_stream();
    let mut buffer = String::new();

    while let Some(chunk) = stream.next().await {
        let chunk = chunk?;
        buffer.push_str(&String::from_utf8_lossy(&chunk));

        while let Some(pos) = buffer.find('\n') {
            let line = buffer[..pos].trim().to_string();
            buffer.drain(..=pos);

            if let Some(data) = line.strip_prefix("data: ") {
                if data == "[DONE]" {
                    return Ok(());
                }
                let event: serde_json::Value = serde_json::from_str(data)?;
                if let Some(text) = event["delta"]["text"].as_str() {
                    print!("{}", text);
                }
            }
        }
    }

    Ok(())
}

This gives you token-by-token output in a terminal or lets you forward chunks over a WebSocket to a frontend. The event shapes (content block deltas, message_stop, etc.) are documented in the streaming guide — worth reading before you build anything that parses specific event types rather than just concatenating text deltas.

Error handling and retries

Production clients need to handle rate limits and transient failures without crashing. A simple retry wrapper with exponential backoff covers most cases:

async fn send_with_retry(
    client: &ClaudeClient,
    model: &str,
    messages: Vec<Message>,
    max_retries: u32,
) -> Result<MessageResponse, reqwest::Error> {
    let mut attempt = 0;
    loop {
        match client.send_message(model, messages.clone()).await {
            Ok(res) => return Ok(res),
            Err(e) if attempt < max_retries => {
                attempt += 1;
                let delay = std::time::Duration::from_millis(500 * 2u64.pow(attempt));
                tokio::time::sleep(delay).await;
            }
            Err(e) => return Err(e),
        }
    }
}

Check the status code before retrying blindly — a 401 won't fix itself with a backoff loop, but a 429 or 503 usually will.

Tool use in Rust

If your Rust service needs Claude to call functions (database lookups, calculators, internal APIs), the request/response pattern is the same MessageRequest/MessageResponse structs with an added tools array and a loop that feeds tool_result blocks back in. The tool use docs cover the JSON schema for tool definitions — once you've modeled that as a struct, the Rust side is just another field on MessageRequest.

Why go through SubToAPI instead of Anthropic directly

If your team already has Claude access through a subscription rather than a pay-as-you-go API account, SubToAPI turns that into the same REST interface this tutorial uses — sub_live_... keys, standard headers, streaming, and usage metadata per request, with plans starting at €9/month for solo use and per-seat pricing for teams. The Rust code above doesn't change either way; only the base URL and auth header format differ.

questions

Is there an official Anthropic Rust SDK? No. Anthropic maintains official SDKs for Python and TypeScript. For Rust, you build a thin HTTP client with reqwest and serde, which is straightforward since the API is plain JSON over HTTPS.

Can I use async-openai or similar crates for Claude? Those crates target OpenAI's API shape and won't work with Claude's message format without modification. It's simpler to write your own small client, as shown above, since Claude's API surface is compact.

How do I handle Claude's streaming format in Rust? Read the response as a byte stream, buffer it until you hit newlines, and parse lines prefixed with data: as JSON. Extract delta.text from content_block_delta events to reconstruct the output token by token.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →