← Blog

Claude API Rust SDK Integration Guide

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

If you're searching for a "Claude API Rust SDK," the short answer is: Anthropic does not publish an official Rust SDK. Official SDKs exist for Python and TypeScript/JavaScript only. For Rust, you integrate directly against the HTTPS API using an HTTP client crate like reqwest, combined with serde for JSON serialization. This is not a workaround — it's the standard pattern for any language without first-party SDK support, and it works reliably in production.

This guide walks through a complete integration: making a request, handling streaming responses, parsing tool use, and structuring the code so it's maintainable as your Rust service grows. We'll also cover community crates and a simpler alternative if you want to skip HTTP plumbing entirely.

Why there's no official Rust SDK

Anthropic prioritizes SDKs for the languages most AI application developers use day to day. Rust shows up more in infrastructure, CLI tools, and performance-critical backends — common targets for integrating an LLM API, but not common enough yet to justify a maintained first-party client. That gap is filled by:

  1. Direct HTTP calls with reqwest + serde_json — full control, zero extra dependencies to trust.
  2. Community crates — unofficial wrappers exist on crates.io, but quality and maintenance vary; vet them before depending on them in production.
  3. A hosted API layer that normalizes the interface and gives you a stable REST contract to build a thin Rust client around.

Most production Rust services end up doing option 1, because it's a small amount of code and avoids a dependency on an unofficial crate's update cadence.

Setting up the project

Add the core dependencies:

[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"

A basic non-streaming request

use serde::{Deserialize, Serialize};

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

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

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

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

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

    let body = MessageRequest {
        model: "claude-sonnet-4".to_string(),
        max_tokens: 1024,
        messages: vec![Message {
            role: "user".to_string(),
            content: "Summarize the benefits of Rust for backend services.".to_string(),
        }],
    };

    let resp: MessageResponse = client
        .post("https://api.example.com/v1/messages")
        .header("x-api-key", api_key)
        .header("content-type", "application/json")
        .json(&body)
        .send()
        .await?
        .json()
        .await?;

    for block in resp.content {
        if let Some(text) = block.text {
            println!("{}", text);
        }
    }

    Ok(())
}

This pattern — define request/response structs with serde, call .json() both ways — is the entire SDK, functionally speaking. No hidden magic to replicate.

Handling streaming in Rust

Streaming is where a Rust integration gets more interesting, because Claude's API streams responses as Server-Sent Events (SSE), and Rust doesn't have a batteries-included SSE parser in reqwest. You consume the byte stream and parse data: lines yourself:

use futures_util::StreamExt;

async fn stream_response(client: &reqwest::Client, api_key: &str) -> Result<(), reqwest::Error> {
    let mut stream = client
        .post("https://api.example.com/v1/messages")
        .header("x-api-key", api_key)
        .header("content-type", "application/json")
        .json(&serde_json::json!({
            "model": "claude-sonnet-4",
            "max_tokens": 512,
            "stream": true,
            "messages": [{"role": "user", "content": "Write a haiku about Rust."}]
        }))
        .send()
        .await?
        .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: ") {
                println!("{}", data);
            }
        }
    }

    Ok(())
}

In production you'd parse each data: payload as JSON and match on the event type (content_block_delta, message_stop, etc.) rather than printing raw strings.

Tool use from Rust

Tool/function calling works the same way — you serialize a tools array into the request body and deserialize tool_use blocks from the response:

#[derive(Serialize)]
struct Tool {
    name: String,
    description: String,
    input_schema: serde_json::Value,
}

Map incoming tool_use content blocks to your own enum, dispatch to the matching Rust function, then send the result back as a tool_result message in the next request. This round-trip pattern is identical across every language — Rust just requires you to write the struct definitions yourself instead of importing them.

A simpler path: skip the HTTP plumbing

If you'd rather not maintain SSE parsing, retry logic, and auth headers by hand across every Rust service you build, routing requests through SubToAPI gives you a single stable REST endpoint (https://api.subtoapi.app/v1/messages) with an application API key (sub_live_...), consistent streaming format, and usage metadata — the same reqwest + serde code above works against it with just the base URL and header changed:

.post("https://api.subtoapi.app/v1/messages")
.header("Authorization", format!("Bearer {}", std::env::var("SUBTOAPI_KEY").unwrap()))

Check the quickstart, messages reference, streaming guide, and tools documentation for request/response shapes. Plans start at Solo €9/month, with Team (€19/seat) and Scale (€49/seat) tiers for shared dashboards and team key management — all with a free trial at signup. See pricing for details.

Structuring a real integration

For anything beyond a script, wrap the HTTP calls in a small client module:

This gets you most of what an official SDK would provide — type safety, retries, streaming helpers — without waiting for Anthropic to ship one.

Questions

Is there an official Claude Rust SDK? No. Anthropic maintains official SDKs for Python and TypeScript only. Rust integrations use reqwest and serde directly against the HTTPS API, or an unofficial community crate.

Can I use community Rust crates for Claude instead of writing my own client? Yes, several exist on crates.io, but check maintenance activity and API coverage before relying on one in production — unofficial crates can lag behind API changes.

Does streaming work the same way in Rust as in Python/JS SDKs? Functionally yes — it's Server-Sent Events — but Rust requires you to parse the byte stream and data: lines manually since there's no built-in SSE client bundled with reqwest.

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 →