OTP verification in Spring Boot with RestClient: a complete backend
Written by Vivek SinghReviewed by the DiOTP team Published 3 December 2026Last updated 3 December 2026
11 min read
OTP verification in Spring Boot needs one client bean and two endpoints: POST /api/otp/send asks DiOTP to text a code and saves the returned request_id in the HTTP session, and POST /api/otp/verify passes that request_id and the typed code to DiOTP. A 200 reply means the number is proven. This guide builds it with Spring's RestClient and no vendor SDK, maps every DiOTP error code in one controller advice, handles the 429 limits and the 30 second resend cooldown, and tests the client without a network.
How the flow works
DiOTP generates the code, sends it by SMS, stores it and checks it. Your Java code never sees the digits. You call POST /v1/otp/send with the number and get a request_id; later you call POST /v1/otp/verify with that request_id and the code the user typed. Codes expire after 5 minutes and allow 5 attempts. Both calls authenticate with your API key as a Bearer token.
- The client posts a phone number to /api/otp/send on your Spring Boot app.
- The controller validates it, calls DiOTP and stores the request_id in the HttpSession.
- The client posts the typed code to /api/otp/verify.
- The controller reads the request_id from the session, calls DiOTP and, on success, marks the user as signed in.
Keep the API key on the server. A key in a web bundle or an Android app can be extracted, and anyone holding it could send codes on your account.
You can go live without your own DLT registration: on DiOTP, codes go out on DiOTP's registered header and pre-approved OTP template. That is what OTP without DLT covers, and the code below does not change when you later move to your own sender ID.
Build it step by step
- Create a Spring Boot 3.2 or newer project with the Spring Web and Validation starters (spring-boot-starter-web, spring-boot-starter-validation). Java 17 or newer.
- Sign up for DiOTP, create an API key and set it as the DIOTP_API_KEY environment variable.
- Add the properties file, the exception and the DiotpClient bean.
- Add the controller and the controller advice that maps errors.
- Run the tests, then try the flow on your own number in test mode.
application.properties
# src/main/resources/application.properties
# The key comes from the environment. Spring fails to start if it is missing.
diotp.api-key=${DIOTP_API_KEY}
diotp.base-url=https://api-diotp.diorbit.com/v1
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true
server.servlet.session.cookie.same-site=laxThe placeholder ${DIOTP_API_KEY} resolves from the environment, so the key never sits in your repository. If it is missing, the application fails at start-up, which is the moment you want to find out.
A DiOTP client bean with RestClient
RestClient arrived in Spring Framework 6.1 (Spring Boot 3.2) and is the synchronous client to use for new code. The bean below sets the base URL and the Bearer header once, and installs a status handler that turns any 4xx or 5xx reply into a DiotpException carrying the status and the stable error code from DiOTP's error envelope.
DiotpException.java
// DiotpException.java
package com.example.otp;
/** An error reply from DiOTP. Branch on code(), never on the message text. */
public class DiotpException extends RuntimeException {
private final int status;
private final String code;
public DiotpException(int status, String code, String message) {
super(status + " " + code + ": " + message);
this.status = status;
this.code = code;
}
public int status() { return status; }
public String code() { return code; }
}DiotpClient.java
// DiotpClient.java (Spring Boot 3.2 or newer, for RestClient)
package com.example.otp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClient;
@Component
public class DiotpClient {
public record SendResult(String request_id, String channel, String expires_at) {}
public record VerifyResult(String request_id, boolean verified, String verified_at) {}
private final RestClient http;
public DiotpClient(RestClient.Builder builder, ObjectMapper mapper,
@Value("${diotp.base-url}") String baseUrl,
@Value("${diotp.api-key}") String apiKey) {
this.http = builder
.baseUrl(baseUrl)
.defaultHeader("Authorization", "Bearer " + apiKey)
.defaultStatusHandler(HttpStatusCode::isError, (req, res) -> {
byte[] raw = res.getBody().readAllBytes();
JsonNode body = raw.length == 0 ? MissingNode.getInstance() : mapper.readTree(raw);
JsonNode err = body.path("error");
throw new DiotpException(res.getStatusCode().value(),
err.path("code").asText("unknown"), err.path("message").asText(""));
})
.build();
}
/** Sends a code to a 10-digit Indian number. The code itself never reaches you. */
public SendResult send(String phone, String purpose) {
var body = Map.of("to", phone, "country_code", 91, "channel", "sms", "purpose", purpose);
String key = UUID.randomUUID().toString(); // one key per user action
try {
return post("/otp/send", body, key, SendResult.class);
} catch (ResourceAccessException e) {
// Timeout or dropped connection: retry once with the SAME key, so
// DiOTP returns the first result instead of sending a second code.
return post("/otp/send", body, key, SendResult.class);
} catch (DiotpException e) {
if (!"sending_unavailable".equals(e.code())) throw e;
return post("/otp/send", body, key, SendResult.class);
}
}
public VerifyResult verify(String requestId, String code) {
return post("/otp/verify", Map.of("request_id", requestId, "code", code), null, VerifyResult.class);
}
private <T> T post(String path, Object body, String idempotencyKey, Class<T> type) {
var spec = http.post().uri(path).contentType(MediaType.APPLICATION_JSON);
if (idempotencyKey != null) spec = spec.header("Idempotency-Key", idempotencyKey);
return spec.body(body).retrieve().body(type);
}
}HttpConfig.java
// HttpConfig.java: timeouts for the RestClient.Builder that Spring Boot injects.
package com.example.otp;
import java.time.Duration;
import org.springframework.boot.web.client.RestClientCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
@Configuration
class HttpConfig {
@Bean
RestClientCustomizer timeouts() {
return builder -> {
var factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(Duration.ofSeconds(5));
factory.setReadTimeout(Duration.ofSeconds(10));
builder.requestFactory(factory);
};
}
}The timeouts live in a RestClientCustomizer rather than inside the client. Spring Boot applies customizers to the RestClient.Builder it injects, so production calls give up after 10 seconds, while a test can hand the client a plain builder bound to a mock server. Note that a customizer applies to every RestClient built from the injected builder in your app.
The send body uses to as digits only, the 10-digit number without +91, and country_code as the integer 91. Each send gets a fresh Idempotency-Key. On a timeout or a 503 sending_unavailable, the client retries once with the same key; DiOTP sees the same key and body, returns the first answer and sends nothing new. Every field is described on the send OTP reference and the verify OTP reference.
The send and verify endpoints
The controller validates input with Jakarta Bean Validation and keeps the pending request in the HttpSession, so the browser holds only a session cookie and never the request_id.
OtpController.java
// OtpController.java
package com.example.otp;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import java.time.Instant;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/otp")
public class OtpController {
public record SendRequest(@NotBlank @Pattern(regexp = "[6-9]\\d{9}",
message = "Enter a 10-digit mobile number.") String phone) {}
public record VerifyRequest(@NotBlank @Pattern(regexp = "\\d{4,10}",
message = "Enter the code from the SMS.") String code) {}
/** What we keep in the server-side session between the two steps. */
record Pending(String requestId, String phone, Instant sentAt) implements java.io.Serializable {}
private static final String PENDING = "otp_pending";
private static final long COOLDOWN_SECONDS = 30;
private final DiotpClient diotp;
public OtpController(DiotpClient diotp) { this.diotp = diotp; }
@PostMapping("/send")
public ResponseEntity<?> send(@Valid @RequestBody SendRequest req, HttpSession session) {
// Mirror DiOTP's 30 second cooldown: an instant 429, no API call.
if (session.getAttribute(PENDING) instanceof Pending p && p.phone().equals(req.phone())) {
long waited = Instant.now().getEpochSecond() - p.sentAt().getEpochSecond();
if (waited < COOLDOWN_SECONDS) {
long wait = COOLDOWN_SECONDS - waited;
return ResponseEntity.status(429).header("Retry-After", String.valueOf(wait))
.body(Map.of("error", "resend_cooldown", "retry_after", wait));
}
}
var result = diotp.send(req.phone(), "login"); // DiotpException goes to OtpErrors
session.setAttribute(PENDING, new Pending(result.request_id(), req.phone(), Instant.now()));
return ResponseEntity.ok(Map.of("sent", true, "expires_at", result.expires_at(), "resend_in", COOLDOWN_SECONDS));
}
@PostMapping("/verify")
public ResponseEntity<?> verify(@Valid @RequestBody VerifyRequest req, HttpServletRequest http) {
HttpSession session = http.getSession();
if (!(session.getAttribute(PENDING) instanceof Pending p)) {
return ResponseEntity.badRequest().body(Map.of("error", "no_pending_code", "message", "Ask for a code first."));
}
try {
diotp.verify(p.requestId(), req.code());
} catch (DiotpException e) {
if (!"already_verified".equals(e.code())) { // a double tap counts as success
if (OtpErrors.FINISHED.contains(e.code())) session.removeAttribute(PENDING);
throw e;
}
}
session.removeAttribute(PENDING);
http.changeSessionId(); // new session id at login: no session fixation
session.setAttribute("verified_phone", p.phone());
return ResponseEntity.ok(Map.of("verified", true));
}
}The send endpoint keeps its own copy of the 30 second cooldown. A second tap within 30 seconds gets an instant 429 with a Retry-After header, without an API call. DiOTP enforces the real limit for every key and device, so this is a convenience, not the protection.
On verify, already_verified counts as success, because it usually means a double submit. When the request is finished (expired, not_pending, too_many_attempts or not_found), the pending entry is removed so the next attempt starts clean. changeSessionId() gives the visitor a new session id at the moment they gain access. If you use Spring Security, build an Authentication for the verified phone at that point and save it with your SecurityContextRepository instead of the plain session attribute.
With several instances behind a load balancer, store sessions in a shared store such as Spring Session with Redis or JDBC, so the verify request finds the pending entry whichever instance it reaches.
Map every error code in one place
DiOTP returns errors as {"error":{"code":"...","message":"...","request_id":"..."}}. The code is stable, so a @RestControllerAdvice can turn each one into a reply your front end understands. Codes the visitor can act on pass through with a friendly message; account and setup problems are logged and hidden behind otp_unavailable.
OtpErrors.java
// OtpErrors.java: every DiOTP error code becomes one clear reply.
package com.example.otp;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class OtpErrors {
private static final Logger log = LoggerFactory.getLogger(OtpErrors.class);
/** Verify codes after which this request_id can no longer be used. */
static final Set<String> FINISHED = Set.of("expired", "not_pending", "too_many_attempts", "not_found");
record Reply(int status, String message, Integer retryAfter) {}
private static final Map<String, Reply> USER = Map.ofEntries(
Map.entry("resend_cooldown", new Reply(429, "Please wait 30 seconds before asking again.", 30)),
Map.entry("phone_hourly_limit", new Reply(429, "Too many codes for this number. Try again in an hour.", 3600)),
Map.entry("phone_daily_limit", new Reply(429, "Too many codes for this number today. Try tomorrow.", null)),
Map.entry("api_key_minute_limit", new Reply(429, "We are busy. Please try again in a minute.", 60)),
Map.entry("rate_limited", new Reply(429, "We are busy. Please try again in a minute.", 60)),
Map.entry("invalid_code", new Reply(400, "That code is not right. Check the SMS and try again.", null)),
Map.entry("expired", new Reply(410, "This code has expired. Ask for a new one.", null)),
Map.entry("not_pending", new Reply(409, "This code is no longer valid. Ask for a new one.", null)),
Map.entry("not_found", new Reply(404, "We could not find that code. Ask for a new one.", null)),
Map.entry("too_many_attempts", new Reply(429, "Too many wrong tries. Ask for a new code.", null)),
Map.entry("invalid_request", new Reply(400, "Enter a valid 10-digit mobile number.", null))
);
@ExceptionHandler(DiotpException.class)
public ResponseEntity<Map<String, Object>> diotp(DiotpException e) {
Reply r = USER.get(e.code());
if (r == null) {
// unauthorized, trial_restricted, trial_used_up, insufficient_balance,
// account_suspended, channel_not_enabled, test_limit, sending_unavailable ...
log.error("DiOTP error status={} code={}", e.status(), e.code()); // never log the key
return ResponseEntity.status(503).body(Map.of("error", "otp_unavailable",
"message", "We could not send a code right now. Please try again shortly."));
}
var res = ResponseEntity.status(r.status());
if (r.retryAfter() != null) {
res.header("Retry-After", String.valueOf(r.retryAfter()));
return res.body(Map.of("error", e.code(), "message", r.message(), "retry_after", r.retryAfter()));
}
return res.body(Map.of("error", e.code(), "message", r.message()));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> invalid(MethodArgumentNotValidException e) {
var field = e.getBindingResult().getFieldError();
String message = field != null ? field.getDefaultMessage() : "Invalid input.";
return ResponseEntity.badRequest().body(Map.of("error", "invalid_input", "message", message));
}
}| Code | Status | What your endpoint does |
|---|---|---|
| resend_cooldown | 429 | Retry-After: 30. Disable resend and count down. |
| phone_hourly_limit | 429 | Retry-After: 3600. Ask the user to come back in an hour. |
| phone_daily_limit | 429 | Ask the user to try tomorrow. |
| api_key_minute_limit, rate_limited | 429 | Retry-After: 60. Alert yourself if it keeps happening. |
| test_limit | 429 | Your account's daily test allowance is used: logged, generic reply. |
| invalid_code | 400 | Let the user try again, up to 5 attempts. |
| expired | 410 | Offer a new code; codes last 5 minutes. |
| too_many_attempts | 429 | Start over with a new code. |
| unauthorized, trial_restricted, trial_used_up, insufficient_balance, account_suspended | 401, 402, 403 | Logged, generic reply. |
A 429 from DiOTP always means nothing was sent and nothing was charged. The Retry-After values come from DiOTP's published limits: one code per number every 30 seconds, 3 an hour, 10 a day, and 30 sends per API key per minute. The complete list is on the error codes page.
Protect the send endpoint
DiOTP's limits protect each phone number. A script that sends to a new number each time gets past per-number limits, and that is how SMS pumping runs up a bill. Add a per-IP limit on /api/otp/send in your app: a servlet filter with a small token bucket (for example Bucket4j), or the rate limiting in your API gateway. Ten requests per IP in fifteen minutes is a reasonable start. Put a bot check in front of public sign-up forms as well. The SMS pumping protection guide covers the full set of defences.
Test the client without sending an SMS
MockRestServiceServer can bind to a RestClient.Builder, so the real DiotpClient runs against canned replies. The tests check the request body and headers, and that a 429 reply becomes a DiotpException with the right code.
DiotpClientTest.java
// DiotpClientTest.java: no network, no SMS.
package com.example.otp;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.*;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
class DiotpClientTest {
private static final String BASE = "https://api-diotp.diorbit.com/v1";
@Test
void sendReturnsRequestId() {
var builder = RestClient.builder();
var server = MockRestServiceServer.bindTo(builder).build();
var client = new DiotpClient(builder, new ObjectMapper(), BASE, "test_key");
server.expect(requestTo(BASE + "/otp/send"))
.andExpect(method(HttpMethod.POST))
.andExpect(header("Authorization", "Bearer test_key"))
.andExpect(jsonPath("$.to").value("9876543210"))
.andExpect(jsonPath("$.country_code").value(91))
.andRespond(withSuccess("{\"request_id\":\"req_1\",\"channel\":\"sms\",\"expires_at\":\"2026-12-03T10:05:00Z\"}",
MediaType.APPLICATION_JSON));
assertThat(client.send("9876543210", "login").request_id()).isEqualTo("req_1");
server.verify();
}
@Test
void cooldownBecomesDiotpException() {
var builder = RestClient.builder();
var server = MockRestServiceServer.bindTo(builder).build();
var client = new DiotpClient(builder, new ObjectMapper(), BASE, "test_key");
server.expect(requestTo(BASE + "/otp/send"))
.andRespond(withStatus(HttpStatus.TOO_MANY_REQUESTS).contentType(MediaType.APPLICATION_JSON)
.body("{\"error\":{\"code\":\"resend_cooldown\",\"message\":\"wait\"}}"));
assertThatThrownBy(() -> client.send("9876543210", "login"))
.isInstanceOfSatisfying(DiotpException.class, e -> {
assertThat(e.status()).isEqualTo(429);
assertThat(e.code()).isEqualTo("resend_cooldown");
});
}
}Then test the live flow. A new DiOTP account has 10 free test messages, sent only to the mobile number you verified at sign-up; a send to any other number returns 403 trial_restricted. Ask twice within 30 seconds to see resend_cooldown, and verify after 5 minutes to see expired. Recharge your wallet from ₹100 and the same key sends to any Indian mobile number at ₹0.26 to ₹0.40 per OTP plus 18% GST.
