To send a text from Scala, make an HTTPS POST to the messaging API with the JDK's built-in java.net.http.HttpClient, put your API key in a header, and send the recipient and message as a small JSON body. You don't need an SDK, and you don't need circe, play-json or any other library for a payload this size. The part that takes care is the retry: if a request times out, you must resend with the same idempotency key so the customer isn't texted twice.

We make Ready, so the example uses the Ready REST API and only the request shape we document. The patterns carry over to any provider. The code is written to compile on Scala 2.13 and Scala 3 with no dependencies, and a note near the end shows how to swap in sttp if your project already uses it.

What you need before the first request

Four things stand between you and a delivered text:

  • An API key. Ready authenticates with an X-API-Key header. Read it from an environment variable or your secrets manager. Never commit it.
  • A card and a number. A card on file and a number of your own are required to send. The number is $2 a month, with the first month charged when it's activated.
  • Consent. Each request carries consent_attested: true, your promise that the recipient agreed to receive 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 covers why carriers require it.

Every text is charged from the first one: $0.0075 per segment plus a $0.0045 carrier fee per segment. Accounts opened before November 12, 2026 keep their signup prices, shown under Billing.

Send a text with the JDK HttpClient

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. Here's a complete program:

import java.net.URI
import java.net.http.{HttpClient, HttpRequest, HttpResponse}
import java.time.Duration
import java.util.UUID

object SendSms {
  private val client = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(5))
    .build()

  // Escape the characters JSON requires so a name with a quote
  // or a newline can't produce a broken payload.
  def jsonString(s: String): String = {
    val sb = new StringBuilder("\"")
    s.foreach {
      case '"'  => sb.append("\\\"")
      case '\\' => sb.append("\\\\")
      case '\n' => sb.append("\\n")
      case '\r' => sb.append("\\r")
      case '\t' => sb.append("\\t")
      case c if c < ' ' => sb.append(f"\\u${c.toInt}%04x")
      case c => sb.append(c)
    }
    sb.append('"').toString
  }

  def payload(to: String, body: String): String =
    s"""{"to":${jsonString(to)},"body":${jsonString(body)},"consent_attested":true}"""

  def send(to: String, body: String, key: String): HttpResponse[String] = {
    val request = HttpRequest.newBuilder()
      .uri(URI.create("https://api.tryready.com/v1/messages"))
      .timeout(Duration.ofSeconds(15))
      .header("X-API-Key", sys.env("READY_API_KEY"))
      .header("Content-Type", "application/json")
      .header("Idempotency-Key", key)
      .POST(HttpRequest.BodyPublishers.ofString(payload(to, body)))
      .build()
    client.send(request, HttpResponse.BodyHandlers.ofString())
  }

  def main(args: Array[String]): Unit = {
    val res = send("+12125550199", "Your order #1042 has shipped.", UUID.randomUUID().toString)
    println(s"${res.statusCode()} ${res.body()}")
  }
}

A few choices are worth explaining. The HttpClient is created once and reused, because it pools connections and is safe to share across threads. Both a connect timeout and a per-request timeout are set, so a stalled network call gives up instead of holding a thread forever. And the body is built through an escaping function rather than by pasting strings together, which is the one thing you owe the JSON format when you skip a library.

The example prints the status and the raw body. For the exact response fields and error bodies, use the messages API reference instead of a blog post's summary.

Optional fields

Two optional fields are worth knowing. from picks one of your own numbers, and media_url sends a picture as MMS. If you leave from out, Ready picks the number: the one this contact already texts with, otherwise your number closest to their area code. That keeps a conversation on one thread on the contact's phone. To add them, extend payload with extra optional parameters and append the keys only when they're set.

Retries without double-sending

Networks fail. If your request times out, you don't know whether the text went out, and retrying blindly can text a customer twice. Duplicate texts are a reliable way to collect opt-outs.

The fix is the Idempotency-Key header. Generate one UUID per logical message, store it with the message record, and send the same key on every attempt. A retried request with the same key never sends twice. This wrapper retries only the cases that are safe:

import java.io.IOException

def sendWithRetry(to: String, body: String, key: String, maxAttempts: Int = 4): Either[String, HttpResponse[String]] = {
  var backoffMs = 500L
  var attempt = 1
  var last: Either[String, HttpResponse[String]] = Left("not attempted")
  while (attempt <= maxAttempts) {
    last =
      try {
        val res = SendSms.send(to, body, key)
        if (res.statusCode() == 429) Left("rate limited") else Right(res)
      } catch {
        case e: IOException => Left(e.getMessage) // timeout, reset, DNS
      }
    last match {
      case Right(_) => return last
      case Left(_) if attempt < maxAttempts =>
        Thread.sleep(backoffMs)
        backoffMs *= 2
      case _ =>
    }
    attempt += 1
  }
  last
}

The rules behind it:

  1. Retry with the same key on connection errors, timeouts and HTTP 429.
  2. Keep the key constant across attempts. A fresh UUID per attempt defeats the whole purpose.
  3. Don't retry other 4xx responses. A malformed number or a bad key fails the same way on attempt four.
  4. For a 5xx or any answer that says the outcome is unknown, check the error codes page and GET /v1/messages before you resend with a new key, because the first attempt may have gone out.

Ready also refuses some sends up front without charging you: opted-out numbers and numbers on your Ban list. Treat those as final, not as something to retry. Our posts on idempotency keys and duplicate texts and retries and failure handling go deeper on each status.

A blocking Thread.sleep is fine for a batch job or a worker on its own thread. If you're inside an Akka, Pekko or cats-effect application, run the same logic through your effect type's sleep instead, so you don't block a dispatcher thread.

Using sttp instead

If sttp is already in your build, the request is the same four things: URL, headers, body and a timeout. In sttp client 3 it reads roughly like this, with the same string body from payload:

import sttp.client3._

val backend = HttpURLConnectionBackend()
val response = basicRequest
  .post(uri"https://api.tryready.com/v1/messages")
  .header("X-API-Key", sys.env("READY_API_KEY"))
  .header("Idempotency-Key", key)
  .contentType("application/json")
  .body(SendSms.payload("+12125550199", "Your order #1042 has shipped."))
  .readTimeout(scala.concurrent.duration.Duration(15, "seconds"))
  .send(backend)

Everything about idempotency and retry applies unchanged. Don't add a dependency only for this call, though. The JDK client does the same job.

Sending to many numbers

For the same message to many recipients, POST /v1/messages/bulk takes to as an array, with at most 100 recipients per call. Split a bigger list with grouped(100) and give each batch its own persisted idempotency key, so a crash and restart reuses the key instead of resending. The bulk messages docs have the details.

A worked cost example

Say a job sends 2,000 order updates, each one segment, and none of them carries an emoji. That's 2,000 segments, so the cost is 2,000 × ($0.0075 + $0.0045) at the rates above. Screening, the optional scrub and validation checks, is extra when you switch it on. Replies from customers are billed like a sent text.

Ready's all-in prices per segment include the carrier fee but not screening: Scrub lists and Number validation, the two switches in Settings under Compliance, each add $0.003 per segment when switched on, shown as screening on your bill, and both are off by default. Unless you turn the opt-out footer off, the first text to each contact, and one again from time to time, also gets "Reply STOP to opt out" and your business name if the message does not already have them, so a text close to the segment limit can bill one more segment.

Frequently asked questions

Do I need circe or another JSON library to send an SMS from Scala?

No. The body has three fields, so a small escaping function and string interpolation are enough. Add a library when you start parsing larger responses or building many different payloads.

Should I use sttp or the JDK HttpClient?

Use whichever your project already has. The JDK client adds no dependency and is fine for most services. sttp is a good fit when you want one API across several backends or need its effect-library integrations.

What if the same job runs twice?

Derive the idempotency key from something stable, such as the order ID and the message type, and store it. The same logical message then always carries the same key, even across a redeploy.

Where to go next

The practical takeaway is short: one shared client, timeouts on every call, an escaped JSON body, and one stored idempotency key per message. If you're sending from another JVM language, the Java and Kotlin guides use the same request shape. When you're ready to try it, start from the API quickstart.