Integrations
Validate phone numbers and emails in Spring Boot
Check emails, phone numbers and IPs in Spring Boot with RestClient. A validation service, retries on rate limits, a 422 with field errors and a fail-open signup.
Updated 2026-11-23
This recipe adds a validation service and a signup endpoint to a Spring Boot app. Clear negatives answer 422 with the field errors, and an API outage never blocks a signup.
What you need
- Spring Boot 3.2 or later on Java 17 or later, with
spring-boot-starter-web. - A Qelka API key in the
API_KEYenvironment variable, bound tovalidate.api-key. Ask_test_key returns simulated results and never spends credits: see Test mode. - Server-side code only: see Authentication.
Steps
1. Configuration
validate:
api-key: ${API_KEY}
2. The service
package app.validation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;
@Service
public class ValidationService {
private static final Logger LOG = LoggerFactory.getLogger(ValidationService.class);
private static final Set<Integer> RETRYABLE = Set.of(429, 500, 502, 503);
private static final ObjectMapper JSON = new ObjectMapper();
public record Verdict(Map<String, String> errors, boolean checked, String e164, boolean review) {}
private static final class Failure extends RuntimeException {
final int status;
final String type;
final String requestId;
Failure(int status, String type, String requestId) {
super(type);
this.status = status;
this.type = type;
this.requestId = requestId;
}
}
private final RestClient http;
public ValidationService(@Value("${validate.api-key}") String apiKey) {
this.http = RestClient.builder()
.baseUrl("https://api.qelka.com/v1")
.defaultHeader("Authorization", "Bearer " + apiKey)
.build();
}
private record Reply(int status, String requestId, String retryAfter, JsonNode json) {}
private JsonNode call(String path, Map<String, Object> body) throws InterruptedException {
for (int attempt = 1; ; attempt++) {
Reply reply = http.post().uri(path).body(body).exchange((request, response) -> new Reply(
response.getStatusCode().value(),
response.getHeaders().getFirst("X-Request-Id"),
response.getHeaders().getFirst("Retry-After"),
JSON.readTree(response.getBody())));
if (reply.status() >= 200 && reply.status() < 300) {
return reply.json();
}
String type = reply.json().path("error").path("type").asText("unknown");
if (!RETRYABLE.contains(reply.status()) || attempt == 4) {
throw new Failure(reply.status(), type, reply.requestId());
}
long wait = (1L << (attempt - 1)) * 1000;
if (reply.retryAfter() != null && reply.retryAfter().matches("\\d+") && Long.parseLong(reply.retryAfter()) > 0) {
wait = Long.parseLong(reply.retryAfter()) * 1000;
}
Thread.sleep(wait);
}
}
public Verdict signup(String email, String phone, String country, String ip) {
Map<String, String> errors = new LinkedHashMap<>();
boolean checked = true;
boolean review = false;
String e164 = null;
try {
if (email != null && !email.isBlank()) {
JsonNode result = call("/email", Map.of("email", email));
String status = result.path("status").asText();
if (status.equals("undeliverable")) {
JsonNode suggestion = result.path("did_you_mean");
errors.put("email", suggestion.isTextual() ? "Did you mean " + suggestion.asText() + "?" : "This email address cannot receive mail.");
} else if (status.equals("risky") && result.path("reason").asText().equals("disposable")) {
review = true;
}
}
} catch (Failure | RestClientException | InterruptedException error) {
checked = skipped(error);
}
try {
if (phone != null && !phone.isBlank()) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("phone", phone);
if (country != null && !country.isBlank()) {
body.put("country", country);
}
JsonNode result = call("/phone", body);
String status = result.path("status").asText();
if (status.equals("invalid")) {
errors.put("phone", "This phone number is not valid.");
} else if (status.equals("valid")) {
e164 = result.path("e164").asText(null);
}
}
} catch (Failure | RestClientException | InterruptedException error) {
checked = skipped(error);
}
try {
if (ip != null && !ip.isBlank()) {
JsonNode result = call("/ip", Map.of("ip", ip));
if (result.path("risk").path("level").asText().equals("high") || result.path("flags").path("tor").asBoolean()) {
review = true;
}
}
} catch (Failure error) {
if (!error.type.equals("unprocessable_input")) {
checked = skipped(error);
}
} catch (RestClientException | InterruptedException error) {
checked = skipped(error);
}
return new Verdict(errors, checked, e164, review);
}
private boolean skipped(Exception error) {
if (error instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
if (error instanceof Failure failure) {
LOG.warn("validation skipped: {} status={} request_id={}", failure.type, failure.status, failure.requestId);
} else {
LOG.warn("validation skipped: {}", error.getClass().getSimpleName());
}
return false;
}
}
The service retries 429, 500, 502 and 503 up to four attempts, and Retry-After wins over the backoff. A failed call sets checked to false and adds no error.
3. The controller
package app.validation;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SignupController {
public record Signup(String email, String phone, String country) {}
private final ValidationService validation;
public SignupController(ValidationService validation) {
this.validation = validation;
}
@PostMapping("/signup")
public ResponseEntity<?> signup(@RequestBody Signup body, HttpServletRequest request) {
var verdict = validation.signup(body.email(), body.phone(), body.country(), request.getRemoteAddr());
if (!verdict.errors().isEmpty()) {
return ResponseEntity.unprocessableEntity().body(Map.of("errors", verdict.errors()));
}
return ResponseEntity.status(201).body(Map.of(
"phone", verdict.e164() != null ? verdict.e164() : String.valueOf(body.phone()),
"needsReview", verdict.review(),
"needsRecheck", !verdict.checked()));
}
}
Store e164 instead of what was typed. Add a rate limiter in front of the route so a bot cannot spend your credits through it.
Read the result
| Result | Action |
|---|---|
Email undeliverable |
Reject with 422, show did_you_mean |
Email risky, reason disposable |
Flag, or reject if you block disposable inboxes |
Email unknown |
Accept and confirm by email |
Phone valid |
Store e164 |
Phone unknown |
No + and no country: send the country |
IP high risk or Tor |
Flag for review, add friction |
Handle errors and rate limits
No error is billed. 401 invalid_api_key and 403 forbidden mean a wrong or restricted key. 402 insufficient_credits means an empty balance: alert yourself and keep failing open. A key allows 200 requests per 10 seconds, then you get 429 rate_limited, and Retry-After says how long to wait. Each email check costs 1 credit. See Errors and Rate limits.
Related
Frequently asked questions
Which HTTP client should I use in Spring Boot?
Where does the API key go?
How do I get the client IP behind a proxy?
Put this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time