To send a text from Ruby on Rails, POST JSON to your SMS provider's REST endpoint with Ruby's built-in Net::HTTP and an API key in a header. You don't need a gem. Wrap the call in a small service object, run it from an ActiveJob, and the part to get right is retries: a job that retries must reuse the same idempotency key, or a retry can text the same person twice.
We make Ready, so the examples use the Ready REST API and only the request shape we document. The patterns hold for any provider. This guide covers credentials, the request, the job, which failures to retry, a test, and the webhook controller for replies.
What you need before the first request
- An API key, sent in an
X-API-Keyheader. Store it in Rails credentials or an environment variable, never in the repository. - A card and a number. Both are required to send. The number is $2 a month. To build and test first, create a test key (Settings, Developers, Environment: Test): it simulates every send, with no card, number or charge. Add the card and number before you go live.
- Consent. Each request carries
consent_attested: true, your promise that the recipient agreed to texts. Set it only when it's true. - A registration plan. An account can send up to 500 texts a month before it registers for 10DLC, at its normal per-text rate. After that it has to register, and most approvals take 2 to 7 days. Our 10DLC explainer has the background.
Every text is charged from the first one: a segment costs $0.0075 plus a $0.0045 carrier fee, passed through at cost. Screening is extra when you switch it on.
Store the key
Add the key to encrypted credentials with bin/rails credentials:edit:
ready:
api_key: <your key> Read it with Rails.application.credentials.dig(:ready, :api_key). If you deploy with environment variables, ENV.fetch("READY_API_KEY") works the same way, and it raises loudly when the variable is missing, which beats a silent nil.
A service object with Net::HTTP
The endpoint is POST https://api.tryready.com/v1/messages. The body takes to in E.164 format (a 10-digit US number is treated as +1), body and consent_attested. Put the call in app/services/ready_sms.rb:
require "net/http"
require "json"
require "uri"
class ReadySms
Result = Struct.new(:status, :body, keyword_init: true) do
def success? = status.between?(200, 299)
end
ENDPOINT = URI("https://api.tryready.com/v1/messages")
def self.send_text(to:, body:, idempotency_key:)
request = Net::HTTP::Post.new(ENDPOINT)
request["X-API-Key"] = Rails.application.credentials.dig(:ready, :api_key)
request["Content-Type"] = "application/json"
request["Idempotency-Key"] = idempotency_key
request.body = { to: to, body: body, consent_attested: true }.to_json
response = Net::HTTP.start(
ENDPOINT.host, ENDPOINT.port,
use_ssl: true, open_timeout: 5, read_timeout: 15
) { |http| http.request(request) }
Result.new(status: response.code.to_i, body: response.body)
end
end Try it in the console: ReadySms.send_text(to: "+12125550199", body: "Your order #1042 has shipped.", idempotency_key: SecureRandom.uuid).
to_json builds the payload, so a name with a quote or a newline can't break it. The two timeouts matter more than they look. Without them, a stalled connection holds a Puma thread or a Sidekiq worker until something else gives up. For the exact response fields and error bodies, use the messages API reference rather than a guess from a blog post.
If you'd rather use Faraday, the shape is the same: three headers and a JSON body.
An ActiveJob that can't double-send
Send from a background job so a slow API call never blocks a web request. The trap is that job backends retry. If the key is generated inside perform, every retry gets a new key, and a text that actually went out gets sent again. Generate the key when you enqueue and pass it as an argument:
class SendOrderTextJob < ApplicationJob
queue_as :default
class Retryable < StandardError; end
retry_on Retryable, wait: :polynomially_longer, attempts: 4
retry_on Net::OpenTimeout, Net::ReadTimeout, SocketError,
wait: :polynomially_longer, attempts: 4
def perform(to, body, idempotency_key)
result = ReadySms.send_text(to: to, body: body, idempotency_key: idempotency_key)
return if result.success?
if result.status == 429 ||
(result.status == 409 && result.body.to_s.include?("idempotency_in_progress"))
raise Retryable, "retry with the same key"
end
Rails.logger.error("SMS not sent: #{result.status} #{result.body}")
end
end Enqueue it with a key you create once: SendOrderTextJob.perform_later(order.phone, "Your order ##{order.number} has shipped.", SecureRandom.uuid). ActiveJob serializes the arguments, so every retry runs with the same key. Better still, save the key on your own record for the message, so an accidental second enqueue of the same logical text reuses it.
Notice what the job does with other failures: it logs and stops. That's deliberate, and the table below says why.
Which failures to retry
| Response | What to do |
|---|---|
| Network error or timeout | Retry with the same key |
| 429 | Back off, retry with the same key |
409 idempotency_in_progress | Wait, retry with the same key |
| 503 | Not sent and not charged. Resend with a new key |
504, or a code ending in OUTCOME_UNKNOWN | Check GET /v1/messages before resending |
| Other 4xx | Don't retry. Log the body and fix the input |
A malformed number or a bad key fails the same way on every attempt, so retrying only wastes time. Ready also refuses opted-out numbers, numbers on your Ban list and known landlines up front, without charging you. Treat those as final. Our posts on idempotency keys and retries and failure handling explain the reasoning.
Test it without texting anyone
WebMock stops real network calls and lets you assert on the request. Add gem "webmock", group: :test and write:
require "test_helper"
require "webmock/minitest"
class ReadySmsTest < ActiveSupport::TestCase
test "sends the key, the headers and consent" do
stub = stub_request(:post, "https://api.tryready.com/v1/messages")
.with(
headers: { "Idempotency-Key" => "key-123", "Content-Type" => "application/json" },
body: { to: "+12125550199", body: "Test", consent_attested: true }.to_json
)
.to_return(status: 200, body: "{}")
result = ReadySms.send_text(to: "+12125550199", body: "Test", idempotency_key: "key-123")
assert result.success?
assert_requested stub
end
end A stubbed test proves your code builds the right request and reads each status. It doesn't prove a text reaches a handset. Before launch, send a few real texts to phones you own. The sandbox and test numbers guide lays out each layer. Keep fixtures to 555-01xx numbers in E.164 form, like +12125550199.
Sending to many numbers
To send the same message to many recipients, POST /v1/messages/bulk takes to as an array, with at most 100 recipients per call. In Rails, phones.each_slice(limit) gives you batches, with limit set to that maximum. Make each batch its own job with its own stored key, so a crash and restart doesn't resend a batch that already went out. The bulk messages docs cover the request and response.
Segments are what's metered, not messages. An emoji cuts a segment to 70 characters, so a 140-character text with one emoji is 3 segments instead of 1. A 429 means slow down, so back off rather than adding workers.
Receiving replies and delivery reports
To learn whether a text was delivered, and to receive replies, add a route the provider calls. A Rails controller needs two adjustments. Skip CSRF protection for that action, since the caller has no session, and read the raw body with request.raw_post so you can verify the signature over the exact bytes. Enqueue a job, then head :ok right away. Don't do database or CRM work inside the action.
Payload fields and the signature header are in the docs, so follow them there. Our guides on inbound webhooks and testing SMS webhooks locally with a tunnel cover the pattern and how to try it from your machine.
Wrapping up
Sending an SMS from Rails takes one service object and one job. The decisions that matter are a key created once per logical message, retrying only safe failures, timeouts on every call and a webhook action that acknowledges fast. Comparing stacks? The Node.js and Python guides use the same request. When you're ready, sign up and follow the API quickstart.