Skip to content
Connect Media Connect Media

Send SMS with Ruby and Rails: Kenya Bulk SMS API Tutorial

This tutorial shows how to send SMS from Ruby – a plain script, a Rails app or a background job – using the Connect Media bulk SMS API. It uses only Ruby’s standard library (net/http and json), so there is no gem to install. By the end you will be able to send a message, check your balance, read replies, and handle errors properly in production.

Before you start

  • Ruby 2.7 or newer (the examples also run on Ruby 3.x).
  • A Connect Media account. Sign up on the dashboard; there is no minimum top-up and credit never expires.
  • An API key from your dashboard profile. Store it in an environment variable called CM_API_KEY. Never commit it to Git.
  • Optional: a registered sender ID so messages show your brand name.

The API is a single endpoint: POST https://dashboard.connectmedia.co.ke/api.php. You authenticate with the header Authorization: Bearer <API_KEY> (an X-Api-Key header also works) and choose what to do with the action parameter: send, balance, history or inbox. The full OpenAPI spec is at /wp-json/connectmedia/v1/openapi.

Send your first SMS in Ruby

require "net/http"
require "json"
require "uri"

CM_ENDPOINT = URI("https://dashboard.connectmedia.co.ke/api.php")

def cm_request(params)
  http = Net::HTTP.new(CM_ENDPOINT.host, CM_ENDPOINT.port)
  http.use_ssl = true
  http.open_timeout = 5
  http.read_timeout = 15

  req = Net::HTTP::Post.new(CM_ENDPOINT)
  req["Authorization"] = "Bearer #{ENV.fetch('CM_API_KEY')}"
  req["Content-Type"]  = "application/json"
  req.body = params.to_json

  res = http.request(req)
  JSON.parse(res.body)
rescue JSON::ParserError
  { "code" => res&.code.to_i, "raw" => res&.body }
end

result = cm_request(
  action:  "send",
  sender:  "MYBRAND",            # your registered sender ID
  to:      "254712345678",       # 2547XXXXXXXX format
  message: "Your order #1042 has shipped. Thank you!"
)

if result["code"].to_i == 201
  puts "Sent"
else
  warn "Send failed: #{result.inspect}"
end

A successful send returns code 201. Anything in the range 100–106 is a request problem (for example a missing parameter, bad number or authentication issue) and 500 is a server-side error. Check the OpenAPI spec for the meaning of each code before you map them to user-facing messages.

Format Kenyan numbers before you send

Most send failures in Kenyan apps come from phone numbers stored as 0712 345 678, +254712345678 or 712345678. Normalise them first:

def ke_msisdn(raw)
  digits = raw.to_s.gsub(/\D/, "")
  digits = digits.sub(/\A0/, "254")              # 0712... -> 254712...
  digits = "254#{digits}" if digits.length == 9  # 712...  -> 254712...
  digits.match?(/\A254[17]\d{8}\z/) ? digits : nil
end

ke_msisdn("0712 345 678")   # => "254712345678"
ke_msisdn("+254 110 000000") # => "254110000000"
ke_msisdn("12345")          # => nil

The pattern accepts the 07xx and 01xx ranges used by Safaricom, Airtel and Telkom. For international recipients (the API reaches 190+ countries, including Uganda and Tanzania) skip this helper and send the full international number without the plus sign.

Check balance, history and replies

balance = cm_request(action: "balance")   # success code 200
history = cm_request(action: "history")   # success code 202
inbox   = cm_request(action: "inbox")     # success code 302

puts balance.inspect

Note that each action has its own success code: balance returns 200, history 202, inbox 302 and send 201. Write your success check per action instead of treating only 200 as success. The inbox action returns replies sent to you, which is useful for two-way flows such as “reply YES to confirm”.

Sending from Rails

A small service object

# app/services/sms_sender.rb
class SmsSender
  Error = Class.new(StandardError)

  def self.deliver(to:, message:, sender: ENV["CM_SENDER_ID"])
    number = ke_msisdn(to) or raise Error, "Invalid number: #{to}"
    res = cm_request(action: "send", to: number, message: message, sender: sender)
    raise Error, "SMS failed: #{res}" unless res["code"].to_i == 201
    res
  end
end

Put cm_request and ke_msisdn in a module under lib/ or in the service class itself.

Send in the background with Active Job

Never send SMS inside a web request. A slow network call blocks the request thread, and a failure becomes an error page for your user. Use a job:

# app/jobs/send_sms_job.rb
class SendSmsJob < ApplicationJob
  queue_as :sms
  retry_on Net::OpenTimeout, Net::ReadTimeout, wait: :polynomially_longer, attempts: 5
  discard_on SmsSender::Error

  def perform(to, message)
    SmsSender.deliver(to: to, message: message)
  end
end

# usage, e.g. after an order is paid
SendSmsJob.perform_later(order.phone, "Order ##{order.id} confirmed. We will text you when it ships.")

Retry only on timeouts, not on validation errors (100–106): retrying a bad number just costs time. If you are on an older Rails version, replace :polynomially_longer with :exponentially_longer.

Sending to many recipients

For campaigns, loop over your list in a job, pausing briefly between calls, and record each result in your database so you can resume if the job is interrupted. Keep each message under 160 characters where possible: longer texts are split into 153-character parts and each part is billed as one SMS. Emoji switch the message to Unicode, which drops the limit to 70 characters per part. Estimate costs with the bulk SMS cost calculator; rates start at KES 1.0 per SMS with lower volume rates on the pricing page.

If your list is a spreadsheet rather than a database, the dashboard upload may be quicker than code; see sending bulk SMS from Excel.

Production checklist

  • Keep the API key in environment variables or Rails credentials, never in source.
  • Set open and read timeouts (as above) so a network problem cannot hang a worker.
  • Log the response code for every send, but do not log full message bodies if they contain personal data.
  • Validate numbers before queueing, and deduplicate recipient lists.
  • Only message people who opted in, and honour opt-out requests.
  • Use your registered sender ID for every message so recipients recognise you.

Using another language? See the Python, PHP and Node.js guides, or the full developer documentation.

Frequently asked questions

Do I need a gem to send SMS from Ruby?

No. The examples use only net/http and json from Ruby's standard library. You can wrap them in your own small service class.

What phone number format does the API expect?

Kenyan numbers should be in 2547XXXXXXXX or 2541XXXXXXXX format, with no plus sign or leading zero. The ke_msisdn helper in this guide converts common formats.

What does a successful send return?

The send action returns code 201. Balance returns 200, history 202 and inbox 302. Codes 100 to 106 indicate request problems and 500 a server error.

Should I send SMS inside a Rails controller?

No. Queue it with Active Job or another background worker so slow network calls do not block web requests, and retry only on timeouts.