← Blog

Claude API Rust Integration: Example Code & Setup

2026-11-14 · 4 min read · SubToAPI Team

Anthropic doesn't publish an official Rust SDK for Claude, so if you're building a Rust service — a CLI tool, a backend microservice, an embedded agent — you'll be calling the Claude API directly over HTTPS using reqwest and serde. That's actually fine: the API is a plain JSON REST interface, and Rust's HTTP ecosystem handles it cleanly with a handful of dependencies.

This guide walks through a complete, working Rust integration: sending a message, parsing the response, streaming tokens, and handling tool use, using idiomatic async/await with Tokio.

Setting up the project

Add these dependencies 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"

A basic message request

The Claude Messages API expects a JSON body with model, max_tokens, and a messages array. Here's a minimal non-streaming call:

use serde::{Deserialize, Serialize};
use std::env;

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

#[derive(Serialize)]
struct MessagesRequest {
    model: String,
    max_tokens: u32,
    messages: Vec<Message>,
}

#[derive(Deserialize, Debug)]
struct MessagesResponse {
    content: Vec<ContentBlock>,
}

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

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

    let body = MessagesRequest {
        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 resp = client
        .post("https://api.anthropic.com/v1/messages")
        .header("x-api-key", api_key)
        .header("anthropic-version", "2023-06-01")
        .header("content-type", "application/json")
        .json(&body)
        .send()
        .await?;

    let parsed: MessagesResponse = resp.json().await?;
    if let Some(text) = parsed.content.first().and_then(|b| b.text.clone()) {
        println!("{}", text);
    }

    Ok(())
}

This is the raw pattern. In production you'll want retry logic for rate limits (HTTP 429) and transient 5xx errors, plus proper struct coverage for every content block type (text, tool_use, tool_result).

Streaming responses in Rust

For chat UIs or long completions, streaming avoids making the user wait for the full response. Claude's streaming endpoint returns server-sent events (SSE). With reqwest's bytes_stream() and futures-util, you can parse chunks as they arrive:

use futures_util::StreamExt;

async fn stream_message(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 concurrency."}]
    });

    let resp = 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 = resp.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]" {
                    break;
                }
                // Parse the SSE JSON event here with serde_json
                print!("{}", data);
            }
        }
    }

    Ok(())
}

In a real implementation, parse each data: line into the event schema (content_block_delta, message_stop, etc.) rather than printing raw JSON.

Tool use from Rust

Tool use (function calling) works the same way in Rust as any other language: you define a tools array in your request describing the function schema, and when Claude wants to call it, the response contains a tool_use content block with the tool name and input. Your Rust code executes the actual function, then sends the result back as a tool_result message in the next request. This is a multi-turn loop, so structure your request/response types to hold a Vec<ContentBlock> with a tagged enum (#[serde(tag = "type")]) covering text, tool_use, and tool_result variants — that's the cleanest way to model Claude's content blocks in Rust's type system.

Where SubToAPI fits in

If you'd rather skip writing and maintaining the retry, streaming-parser, and error-handling plumbing yourself — especially across multiple Rust services — SubToAPI gives you a single HTTPS endpoint that wraps Claude access behind a standard API key (sub_live_...). The request/response shape mirrors Claude's Messages API closely, so the Rust structs above work with only the base URL and auth header changed:

let resp = client
    .post("https://api.subtoapi.app/v1/messages")
    .header("Authorization", format!("Bearer {}", subtoapi_key))
    .json(&body)
    .send()
    .await?;

SubToAPI adds usage metadata per request, team seats for shared billing, and a dashboard for tracking consumption across services — useful if several Rust microservices in your stack are all calling Claude and you want one place to see spend. See the quickstart, messages endpoint docs, streaming docs, and tool use docs for the full request/response reference. Plans start at €9/month on the pricing page, with a free trial at signup.

Error handling checklist

Whatever client you call, build these into your Rust integration from day one:

Questions

Is there an official Anthropic Rust SDK for Claude? No. Anthropic maintains official SDKs for Python and TypeScript; Rust integrations call the REST API directly with reqwest or similar HTTP crates, as shown above.

Can I stream Claude responses in Rust without a dedicated SSE crate? Yes — reqwest's bytes_stream() combined with futures-util::StreamExt is enough to read and split SSE data: lines manually, as in the example above.

Does SubToAPI change how I write Rust code against Claude? Barely. You swap the base URL and auth header for an sub_live_... key; the Messages, streaming, and tool-use payload shapes stay compatible, documented at /docs/messages.

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 →