anthropic/client
HTTP client wrapper for Anthropic API calls
This module provides a client for making requests to the Anthropic Messages API, handling headers, timeouts, and response parsing.
Quick Start
For most use cases, use the simple init functions:
import anthropic/client
import anthropic/api
import anthropic/types/request
import anthropic/types/message.{user_message}
// Read API key from ANTHROPIC_API_KEY environment variable
let assert Ok(client) = client.init()
// Or provide the key explicitly
let assert Ok(client) = client.init_with_key("sk-ant-...")
// Create a request and chat
let req = request.new("claude-sonnet-4-20250514", [user_message("Hello!")], 1024)
api.chat(client, req)
Advanced Configuration
For custom base URLs, timeouts, or retry settings, use the config builders:
import anthropic/config
import anthropic/client
let assert Ok(cfg) = config.config_options()
|> config.with_api_key("sk-ant-...")
|> config.with_base_url("https://custom-endpoint.example.com")
|> config.with_timeout_ms(120_000)
|> config.load_config()
let client = client.new(cfg)
Types
Client for making Anthropic API requests
pub type Client {
Client(config: config.Config)
}
Constructors
-
Client(config: config.Config)Arguments
- config
-
Configuration including API key and base URL
Values
pub fn handle_response(
response: response.Response(String),
) -> Result(String, error.AnthropicError)
Handle an API response, parsing success or error
pub fn init() -> Result(Client, error.AnthropicError)
Initialize a client using the ANTHROPIC_API_KEY environment variable
This is the simplest way to create a client when you have your API key set in the environment.
Example
// Ensure ANTHROPIC_API_KEY is set in your environment
let assert Ok(client) = client.init()
api.create_message(client, request)
pub fn init_with_key(
api_key: String,
) -> Result(Client, error.AnthropicError)
Initialize a client with an explicit API key
Use this when you want to provide the API key directly rather than reading from environment variables.
Example
let assert Ok(client) = client.init_with_key("sk-ant-api03-...")
api.create_message(client, request)
pub fn new(config: config.Config) -> Client
Create a new client from configuration
For advanced use cases where you need custom configuration.
For simple use cases, prefer init() or init_with_key().
pub fn post_and_handle(
client: Client,
path: String,
body: String,
) -> Result(String, error.AnthropicError)
Make a POST request and handle the response
pub fn post_json(
client: Client,
path: String,
body: String,
) -> Result(response.Response(String), error.AnthropicError)
Make a POST request with JSON body to the specified path