← Blog

Claude API Ruby on Rails Gem Setup Guide

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

Setting up Claude in a Rails app means picking an HTTP client, storing your API key safely, and wiring a controller that sends messages and handles the response format Anthropic's API expects. There is no official Anthropic gem for Ruby, so most Rails developers either use the community anthropic gem or call the REST API directly with Net::HTTP or Faraday. Both approaches are straightforward — this guide covers both, plus how to do it through SubToAPI if you want OpenAI-style simplicity with usage dashboards and team keys.

The short answer: add a gem (or use Faraday directly), store your key in Rails credentials, create a service object, and call it from a controller or background job. Below is a complete setup you can drop into a Rails app today.

Option 1: Using the community anthropic gem

The anthropic gem (maintained independently, not by Anthropic) wraps the REST API in a Ruby-friendly client.

# Gemfile
gem "anthropic"
bundle install

Store your key with Rails encrypted credentials:

EDITOR="code --wait" bin/rails credentials:edit
anthropic:
  api_key: sk-ant-xxxxxxxx

Create a service object:

# app/services/claude_client.rb
class ClaudeClient
  def initialize
    @client = Anthropic::Client.new(
      access_token: Rails.application.credentials.dig(:anthropic, :api_key)
    )
  end

  def ask(prompt, model: "claude-sonnet-4-5", max_tokens: 1024)
    response = @client.messages(
      parameters: {
        model: model,
        max_tokens: max_tokens,
        messages: [{ role: "user", content: prompt }]
      }
    )
    response.dig("content", 0, "text")
  end
end
# app/controllers/chats_controller.rb
class ChatsController < ApplicationController
  def create
    answer = ClaudeClient.new.ask(params[:prompt])
    render json: { answer: answer }
  end
end

Gem APIs change between major versions, so pin a version in your Gemfile and check the gem's changelog before upgrading — breaking changes in parameter names are common with community-maintained wrappers.

Option 2: Plain Faraday, no gem dependency

If you'd rather avoid depending on a third-party gem that isn't officially supported, call the REST endpoint directly:

# Gemfile
gem "faraday"
# app/services/claude_client.rb
class ClaudeClient
  ENDPOINT = "https://api.anthropic.com/v1/messages"

  def ask(prompt, model: "claude-sonnet-4-5", max_tokens: 1024)
    conn = Faraday.new do |f|
      f.request :json
      f.response :json
      f.adapter Faraday.default_adapter
    end

    response = conn.post(ENDPOINT) do |req|
      req.headers["x-api-key"] = Rails.application.credentials.dig(:anthropic, :api_key)
      req.headers["anthropic-version"] = "2023-06-01"
      req.headers["content-type"] = "application/json"
      req.body = {
        model: model,
        max_tokens: max_tokens,
        messages: [{ role: "user", content: prompt }]
      }
    end

    response.body.dig("content", 0, "text")
  end
end

This avoids gem churn entirely — you control the exact request shape and only need to update code if Anthropic changes the API itself.

Option 3: Through SubToAPI with an HTTP API key

If you're already using Claude through your Anthropic subscription rather than a pay-per-token API key, you don't technically have programmatic API access — Anthropic's consumer plans don't expose one. SubToAPI turns that subscription into a normal HTTPS API with its own sub_live_... key, so the same Rails setup above works, just pointed at a different host:

class ClaudeClient
  ENDPOINT = "https://api.subtoapi.app/v1/messages"

  def ask(prompt, model: "claude-sonnet-4-5", max_tokens: 1024)
    conn = Faraday.new do |f|
      f.request :json
      f.response :json
      f.adapter Faraday.default_adapter
    end

    response = conn.post(ENDPOINT) do |req|
      req.headers["Authorization"] = "Bearer #{Rails.application.credentials.dig(:subtoapi, :api_key)}"
      req.headers["content-type"] = "application/json"
      req.body = {
        model: model,
        max_tokens: max_tokens,
        messages: [{ role: "user", content: prompt }]
      }
    end

    response.body.dig("content", 0, "text")
  end
end

Store the key the same way:

subtoapi:
  api_key: sub_live_xxxxxxxx

This is the right path if your team already pays for Claude access and wants an API without separately metered billing. Signup and key generation are at /signup, request/response shapes for messages are documented at /docs/messages, and /docs/quickstart has a five-minute setup that maps directly onto the Faraday snippet above.

Handling streaming responses in Rails

Rails controllers can stream Claude's SSE output using ActionController::Live, but it requires careful handling of the response buffer and thread-safety since response.stream isn't reentrant across requests. If you're building a chat UI, background job + WebSocket (ActionCable) broadcasting is usually more reliable than holding an HTTP connection open in a Puma thread. The streaming payload format itself (whether via direct Anthropic calls or SubToAPI) is documented at /docs/streaming.

Background jobs for longer requests

For anything beyond a quick synchronous reply, push the Claude call into a Sidekiq or Solid Queue job rather than blocking a web worker:

class ClaudeJob < ApplicationJob
  queue_as :default

  def perform(chat_id, prompt)
    answer = ClaudeClient.new.ask(prompt)
    Chat.find(chat_id).update!(response: answer)
    ChatChannel.broadcast_to(chat_id, answer: answer)
  end
end

This keeps request/response times predictable and avoids Puma thread starvation when Claude calls take several seconds, which is common with longer prompts or large max_tokens values.

Tool use and function calling

If your Rails app needs Claude to call functions (database lookups, order status, etc.), the request body needs a tools array alongside messages. This works identically whether you're hitting Anthropic directly or through SubToAPI — see /docs/tools for the schema and a worked example of handling tool_use blocks in the response.

questions

Is there an official Anthropic gem for Ruby on Rails? No. Anthropic maintains official SDKs for Python and TypeScript/JavaScript. Ruby developers use community-maintained gems like anthropic or call the REST API directly with Faraday or Net::HTTP.

Where should I store my Claude API key in a Rails app? Use Rails encrypted credentials (rails credentials:edit) or environment variables loaded via dotenv-rails in development. Never commit keys to version control or hardcode them in controllers.

Can I use my Claude subscription instead of a pay-per-token API key in Rails? Not directly — Anthropic's consumer subscriptions don't include API access. Services like SubToAPI convert that subscription into a standard HTTPS API key you can call from Rails the same way you'd call Anthropic's own endpoint. See /pricing for plan details.

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 →