Claude API Ruby Client Library Tutorial
There is no official Anthropic-maintained Ruby SDK that ships alongside the Python and TypeScript libraries, so most Ruby developers either hand-roll a thin HTTP wrapper with Faraday or net/http, or use one of the community gems (like anthropic on RubyGems). This tutorial shows you how to do both: build a minimal client from scratch so you understand exactly what's happening on the wire, and then show the gem-based shortcut.
If you just want working Ruby code that talks to Claude today, skip to the "Minimal Ruby Client" section below. If you want a hosted alternative that gives you an OpenAI-shaped REST endpoint, streaming, and per-key usage tracking without managing SDKs at all, SubToAPI (https://subtoapi.app) turns your Claude access into a plain HTTPS API you can call from any language, including Ruby's standard net/http.
Why Ruby Needs a Thin Wrapper
Anthropic's API is a straightforward JSON-over-HTTPS interface. You send a POST request to /v1/messages with a model name, a list of messages, and a max_tokens value, and you get back a JSON response with the assistant's reply. Because it's just HTTP, you don't strictly need an SDK — but a small wrapper class saves you from repeating headers, retry logic, and error handling in every script.
What You'll Need
- Ruby 3.0+
- An HTTP client gem (
faradayorhttparty, or justnet/httpfrom the standard library) - An API key from your provider (Anthropic directly, or a proxy like SubToAPI)
gem install faraday
Minimal Ruby Client (No External SDK)
Here's a self-contained class using only net/http, so there are zero gem dependencies:
require "net/http"
require "json"
require "uri"
class ClaudeClient
BASE_URL = "https://api.anthropic.com/v1/messages"
def initialize(api_key:, model: "claude-sonnet-4-5")
@api_key = api_key
@model = model
end
def send_message(prompt, max_tokens: 1024)
uri = URI(BASE_URL)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request["x-api-key"] = @api_key
request["anthropic-version"] = "2023-06-01"
request["content-type"] = "application/json"
request.body = {
model: @model,
max_tokens: max_tokens,
messages: [{ role: "user", content: prompt }]
}.to_json
response = http.request(request)
parsed = JSON.parse(response.body)
raise "API error: #{parsed["error"]["message"]}" if parsed["error"]
parsed.dig("content", 0, "text")
end
end
client = ClaudeClient.new(api_key: ENV.fetch("ANTHROPIC_API_KEY"))
puts client.send_message("Explain Ruby's garbage collector in two sentences.")
This covers the 90% use case: send a prompt, get text back. Store your key in ENV, never hardcode it.
Adding Streaming Support
Chat UIs and CLIs usually want tokens as they arrive rather than waiting for the full response. With net/http you can read the response body as a stream of Server-Sent Events:
require "net/http"
require "json"
require "uri"
def stream_message(api_key, prompt)
uri = URI("https://api.anthropic.com/v1/messages")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri)
request["x-api-key"] = api_key
request["anthropic-version"] = "2023-06-01"
request["content-type"] = "application/json"
request.body = {
model: "claude-sonnet-4-5",
max_tokens: 1024,
stream: true,
messages: [{ role: "user", content: prompt }]
}.to_json
http.request(request) do |response|
response.read_body do |chunk|
chunk.each_line do |line|
next unless line.start_with?("data: ")
data = line.sub("data: ", "").strip
next if data.empty? || data == "[DONE]"
event = JSON.parse(data)
if event["type"] == "content_block_delta"
print event.dig("delta", "text")
end
end
end
end
end
stream_message(ENV.fetch("ANTHROPIC_API_KEY"), "Write a haiku about Ruby gems.")
Streaming in raw Ruby is doable but fiddly — line buffering across chunk boundaries is a common source of bugs. If you want streaming without maintaining this parsing logic, SubToAPI exposes the same SSE format documented at /docs/streaming, so this same loop works unchanged against https://api.subtoapi.app/v1/messages — you just swap the host and the Authorization: Bearer $SUBTOAPI_KEY header.
Using a Faraday-Based Wrapper
If you prefer a gem over raw net/http, Faraday gives you cleaner syntax, built-in retries, and middleware support:
require "faraday"
require "json"
conn = Faraday.new(url: "https://api.anthropic.com") do |f|
f.request :retry, max: 2, interval: 0.5
f.response :json
f.adapter Faraday.default_adapter
end
response = conn.post("/v1/messages") do |req|
req.headers["x-api-key"] = ENV.fetch("ANTHROPIC_API_KEY")
req.headers["anthropic-version"] = "2023-06-01"
req.headers["content-type"] = "application/json"
req.body = {
model: "claude-sonnet-4-5",
max_tokens: 500,
messages: [{ role: "user", content: "Summarize the Faraday gem in one line." }]
}.to_json
end
puts response.body.dig("content", 0, "text")
The retry middleware alone is worth the dependency — transient 429s and 503s are common at scale, and Faraday's backoff handles them without extra code.
Calling SubToAPI from Ruby
If you'd rather not manage Anthropic SDK versioning, rotate raw Anthropic keys across environments, or build your own usage dashboard, point the same Ruby code at SubToAPI instead. After signing up at /signup, you get a sub_live_... key and can hit the same /v1/messages shape:
request["authorization"] = "Bearer #{ENV.fetch("SUBTOAPI_KEY")}"
against https://api.subtoapi.app/v1/messages. Check /docs/quickstart for the full request/response schema and /docs/messages for parameter details, including tool use (/docs/tools) if your Ruby app needs function calling. Pricing starts at €9/month for Solo, €19/seat for Team, and €49/seat for Scale — see /pricing for details.
Error Handling and Retries
Whichever approach you choose, handle these cases explicitly in production Ruby code:
- Rate limits (429): back off and retry with jitter, don't hammer the endpoint
- Overloaded (529/503): treat as transient, retry with exponential backoff
- Invalid request (400): log the payload, don't retry — it will fail again
- Timeouts: set explicit
read_timeoutonNet::HTTPsince streaming responses can run long
http.read_timeout = 60
Questions
Is there an official Anthropic gem for Ruby? No. Anthropic officially supports Python and TypeScript SDKs. Ruby developers use community gems or a thin net/http/Faraday wrapper like the one above.
Can I use Faraday instead of net/http for Claude? Yes. Faraday adds cleaner syntax and retry middleware, which is useful once you're making Claude calls in production rather than a quick script.
Does streaming work the same way in Ruby as other languages? Conceptually yes — it's Server-Sent Events over HTTP. The difference is you must manually buffer and split lines in Ruby since there's no built-in SSE parser in the standard library.