To send a text from Spring Boot, define a RestClient bean with your provider's base URL and API key header, then POST a small JSON body from a service class. No SDK is needed. Spring's own HTTP client, Jackson for JSON and @ConfigurationProperties for the key cover the whole job. What takes care is retries: reuse one idempotency key per logical message, or a retry can text the same person twice.
If you want the framework-free version built on java.net.http, our plain Java guide covers it. This one is for Spring Boot 3.2 or later, where RestClient is available. We make Ready, so the examples use the Ready REST API and only the request shape we document. The patterns carry over to any provider.
What you need before the first request
- An API key, sent in an
X-API-Keyheader. Keep it in an environment variable or a secrets manager, never inapplication.ymlin source control. - 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. See what 10DLC is.
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 switched on.
Typed configuration
Bind the settings to a record so the rest of the code never touches raw property strings:
package com.example.sms;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "ready")
public record ReadyProperties(String baseUrl, String apiKey) {} # application.yml
ready:
base-url: https://api.tryready.com
api-key: ${READY_API_KEY} Enable it with @ConfigurationPropertiesScan on your application class. The ${READY_API_KEY} placeholder reads the environment, so the key never lives in the file.
The RestClient bean
Build one client with the base URL and the two headers every call shares, and set timeouts so a stalled connection can't pin a thread:
package com.example.sms;
import java.time.Duration;
import org.springframework.boot.web.client.ClientHttpRequestFactories;
import org.springframework.boot.web.client.ClientHttpRequestFactorySettings;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestClient;
@Configuration
public class ReadyClientConfig {
@Bean
RestClient readyRestClient(ReadyProperties props) {
var settings = ClientHttpRequestFactorySettings.DEFAULTS
.withConnectTimeout(Duration.ofSeconds(5))
.withReadTimeout(Duration.ofSeconds(15));
return RestClient.builder()
.baseUrl(props.baseUrl())
.requestFactory(ClientHttpRequestFactories.get(settings))
.defaultHeader("X-API-Key", props.apiKey())
.defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
.build();
}
} The service
The endpoint is POST /v1/messages. The body takes to in E.164 format (a 10-digit US number is treated as +1), body and consent_attested. A record serialized by Jackson builds the JSON, so a name with a quote or newline can't break the payload:
package com.example.sms;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
@Service
public class ReadySmsService {
record SendRequest(String to, String body, boolean consent_attested) {}
private final RestClient client;
public ReadySmsService(RestClient readyRestClient) {
this.client = readyRestClient;
}
public ResponseEntity<String> send(String to, String body, String idempotencyKey) {
return client.post()
.uri("/v1/messages")
.header("Idempotency-Key", idempotencyKey)
.body(new SendRequest(to, body, true))
.retrieve()
.onStatus(status -> true, (req, res) -> { /* let the caller decide */ })
.toEntity(String.class);
}
} By default RestClient throws on a 4xx or 5xx. The empty onStatus handler turns that off, so the method returns the status and body and the caller decides what each one means. The result is a raw string on purpose: for the exact response fields and error bodies, read the messages API reference and map only what you use.
Call it from a controller or a listener: sms.send("+12125550199", "Your order #1042 has shipped.", UUID.randomUUID().toString()).
Retries without double-sending
Networks fail. If a request times out, you don't know whether the text went out, and a blind retry can send twice. Duplicate texts are a dependable source of opt-outs.
The fix is the Idempotency-Key header. Generate one UUID per logical message, save it with your own record, and send the same key on every attempt. A retried request with the same key doesn't send twice. Here's a loop that retries only when that's safe:
public ResponseEntity<String> sendWithRetry(String to, String body, String key)
throws InterruptedException {
long backoffMs = 500;
for (int attempt = 1; ; attempt++) {
try {
var res = send(to, body, key);
int s = res.getStatusCode().value();
boolean retryable = s == 429
|| (s == 409 && String.valueOf(res.getBody()).contains("idempotency_in_progress"));
if (!retryable || attempt == 4) return res;
} catch (org.springframework.web.client.ResourceAccessException e) {
if (attempt == 4) throw e; // connect or read timeout
}
Thread.sleep(backoffMs + java.util.concurrent.ThreadLocalRandom.current().nextLong(250));
backoffMs *= 2;
}
} A note on @Retryable from Spring Retry: it works, but it re-invokes the annotated method, so the key must be a parameter that the caller created, never a value generated inside the method. Otherwise every attempt gets a fresh key and the protection is gone.
| 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 |
Ready also refuses opted-out numbers, numbers on your Ban list and known landlines up front, without charging. Treat those as final. Our posts on idempotency keys and retries and failure handling explain the reasoning.
Keep slow sends off the request thread
A controller that waits on an SMS call ties up a servlet thread for as long as the API takes. Put the send behind @Async, a message queue or a scheduled outbox table. The outbox is the sturdiest: write the message row and its idempotency key in the same database transaction as your business change, then let a worker send pending rows. If the app crashes mid-send, the row is still pending and the retry reuses the saved key.
Test it without texting anyone
MockRestServiceServer binds to a RestClient.Builder, so a test asserts on the outgoing request without any network:
@Test
void sendsKeyAndConsent() {
var builder = RestClient.builder().baseUrl("https://api.tryready.com");
var server = MockRestServiceServer.bindTo(builder).build();
var service = new ReadySmsService(builder.build());
server.expect(requestTo("https://api.tryready.com/v1/messages"))
.andExpect(method(HttpMethod.POST))
.andExpect(header("Idempotency-Key", "key-123"))
.andExpect(jsonPath("$.consent_attested").value(true))
.andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));
service.send("+12125550199", "Test", "key-123");
server.verify();
} A mocked test proves your code builds the right request and reads each status. It doesn't prove a text reaches a phone, so send a few real texts to numbers you own before launch. The sandbox and test numbers guide lays out each layer. Keep fixtures to 555-01xx numbers in E.164 form.
Receiving replies and delivery reports
To learn whether a text was delivered, and to receive replies, add a @PostMapping the provider calls. Take the body as a byte[] or String so you can verify the signature over the exact bytes before Jackson parses anything. Hand the payload to a queue and return ResponseEntity.ok().build() quickly. If you use Spring Security, permit that one path without a session and rely on signature verification instead.
Payload fields and the signature header are in the docs. Our guides on inbound webhooks and testing SMS webhooks locally with a tunnel cover the pattern and how to try it on your machine.
Wrapping up
A Spring Boot integration is one properties record, one RestClient bean and one service. The decisions that matter are a key created once per logical message, retrying only safe failures, timeouts on every client and a webhook endpoint that acknowledges fast. If you text on behalf of your own customers, our multi-tenant SMS architecture post covers keeping tenants apart. When you're ready to try it, sign up and follow the API quickstart.