Skip to main content

Crate claude_api

Crate claude_api 

Source
Expand description

Type-safe Rust client for the Anthropic API.

Every documented Anthropic endpoint is reachable through a typed namespace handle off Client. Forward-compatible by design – unknown content blocks, stream events, citations, and similar discriminated unions round-trip through Other(Value) arms so new server-side variants don’t break older SDK builds.

§Quick start

use claude_api::{Client, messages::CreateMessageRequest, types::ModelId};

let client = Client::new(std::env::var("ANTHROPIC_API_KEY").unwrap());

let resp = client
    .messages()
    .create(
        CreateMessageRequest::builder()
            .model(ModelId::SONNET_4_6)
            .max_tokens(256)
            .user("Hello!")
            .build()?,
    )
    .await?;

for block in &resp.content {
    if let claude_api::messages::ContentBlock::Known(
        claude_api::messages::KnownBlock::Text { text, .. },
    ) = block
    {
        println!("{text}");
    }
}

§Module map

Endpoints are organized by Anthropic resource. Each namespace handle is reached via a method on Client:

ModuleNamespaceDefault?
messagesclient.messages()yes
modelsclient.models()yes
batchesclient.batches()yes
filesclient.files()yes
skillsclient.skills()feature skills
user_profilesclient.user_profiles()feature user-profiles
managed_agentsclient.managed_agents()feature managed-agents-preview
adminclient.admin()feature admin

Cross-cutting machinery:

ModulePurpose
authAPI-key wrapper + auth::RequestSigner trait
bedrockAWS sigv4 bedrock::BedrockSigner (feature bedrock)
vertexGCP OAuth2 vertex::VertexSigner (feature vertex)
betaBetaHeader open-string enum for the anthropic-beta header
retryretry::RetryPolicy honoring Retry-After
errorError with request_id, retry classification
paginationPaginated and PaginatedNextPage
typesShared primitives: ModelId, Role, Usage, StopReason
conversationMulti-turn helper with cumulative usage (feature conversation)
tool_dispatchToolRegistry, agent loop, parallel dispatch, approval gates
pricingPricingTable (feature pricing)
cost_previewPre-flight USD estimates (features async + pricing)
dry_runRender the would-be HTTP request without sending
sseSSE wrapper used by streaming endpoints (feature streaming)

§Forward compatibility

Every wire-level discriminated union has an Other arm:

When Anthropic adds a new variant, your code that pattern-matches on Known(...) continues to compile; the new variant lands in Other(...) until you upgrade. See the upgrade contract in the README before bumping past a release that promotes an Other to Known.

§Error handling

All endpoint methods return Result<T> where Error carries:

  • HTTP status (when the API responded)
  • request-id (always populated when the server sent one)
  • Retry classification (is_retryable()) and parsed Retry-After (retry_after())
  • Structured kind (error::ApiErrorKind) for known error types

The retry::RetryPolicy applied by the client respects Retry-After by default and uses jittered exponential backoff otherwise. Disable retries with RetryPolicy::none() if your caller wraps its own retry logic.

§Observability

Every HTTP request emits a tracing span at debug level with method, path, and request_id fields. Retries log at warn with attempt, retry_in_ms, and status. No env-var gating is required; install a tracing-subscriber to capture the events.

Re-exports§

pub use beta::BetaHeader;
pub use client::Client;async
pub use client::ClientBuilder;async
pub use error::Error;
pub use error::Result;

Modules§

adminadmin
Anthropic Admin API.
auth
Authentication primitives and the RequestSigner hook.
batches
The Batches API: submit a batch of message requests, poll for completion, stream per-request results.
bedrockbedrock
AWS Bedrock support: a RequestSigner that signs HTTP requests with sigv4.
beta
Typed anthropic-beta header values.
blockingsync
Blocking (synchronous) variants of the HTTP surface.
clientasync
HTTP client and builder.
conversationconversation
Multi-turn conversation helper.
cost_previewasync and pricing
CostPreview – estimate the USD cost of a request before sending it.
derivederive
Procedural-macro re-exports for the derive feature.
dry_runasync
DryRun – preview the HTTP request that would be sent, without firing it.
error
Error type, result alias, and wire-format error payload.
files
The Files API (beta).
managed_agentsmanaged-agents-preview
Anthropic Managed Agents API (preview).
messages
The Messages API.
models
The Models API.
pagination
Generic pagination wrapper used across paginated endpoints.
pricingpricing
Per-model pricing and cost calculation.
retryasync or sync
Retry policy honoring Retry-After.
skillsskills
The Skills API (beta).
ssestreaming
Low-level Server-Sent Events parsing.
tool_dispatchasync
Tool-dispatch: the Tool trait, registry, typed inputs, and the agent loop runner.
types
Foundational shared types used across every API resource.
user_profilesuser-profiles
The User Profiles API (beta).
vertexvertex
Google Cloud Vertex AI support: a RequestSigner that attaches an OAuth2 bearer token so requests are authenticated against the Vertex AI Anthropic endpoint.