Integrations
Validate phone numbers and emails in Kotlin
Check emails, phone numbers and IPs from Kotlin with coroutines, the JDK HttpClient and Jackson. Timeouts, retries on rate limits and a fail-open signup check.
Updated 2026-11-23
This recipe calls the API from Kotlin with coroutines. It checks the email, the phone number and the IP of a signup in parallel, gives every call a deadline, retries on rate limits and never blocks a signup because of an API problem.
What you need
- Kotlin 1.9 or later on JDK 17 or later.
kotlinx-coroutines-coreand Jackson (jackson-databind).- A Qelka API key in the
API_KEYenvironment variable. Ask_test_key returns simulated results and never spends credits: see Test mode. - Server-side code only: see Authentication.
Steps
1. Add the dependencies
With Gradle (Kotlin DSL):
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.1")
implementation("com.fasterxml.jackson.core:jackson-databind:2.17.2")
}
2. The client
package app
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import kotlin.random.Random
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
class ApiException(val status: Int, val type: String, message: String, val requestId: String?) :
RuntimeException("$type: $message")
class ValidateClient(private val apiKey: String = System.getenv("API_KEY") ?: "") {
private val json = ObjectMapper()
private val http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build()
private val retryable = setOf(429, 500, 502, 503)
private suspend fun call(path: String, body: Map<String, Any>): JsonNode {
val payload = json.writeValueAsString(body)
var attempt = 1
while (true) {
val request = HttpRequest.newBuilder(URI.create("https://api.qelka.com/v1$path"))
.timeout(Duration.ofSeconds(12))
.header("Authorization", "Bearer $apiKey")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build()
val response = withContext(Dispatchers.IO) { http.send(request, HttpResponse.BodyHandlers.ofString()) }
if (response.statusCode() in 200..299) return json.readTree(response.body())
val error = json.readTree(response.body()).path("error")
val requestId = response.headers().firstValue("X-Request-Id").orElse(null)
if (response.statusCode() !in retryable || attempt == 4) {
throw ApiException(response.statusCode(), error.path("type").asText("unknown"), error.path("message").asText(""), requestId)
}
val retryAfter = response.headers().firstValue("Retry-After").orElse("").toLongOrNull()
val waitMillis = if (retryAfter != null && retryAfter > 0) retryAfter * 1000 else (1000L shl (attempt - 1)) + Random.nextLong(250)
delay(waitMillis)
attempt += 1
}
}
suspend fun verifyEmail(email: String): JsonNode = call("/email", mapOf("email" to email))
suspend fun validatePhone(phone: String, country: String?): JsonNode =
call("/phone", if (country.isNullOrBlank()) mapOf("phone" to phone) else mapOf("phone" to phone, "country" to country))
suspend fun lookupIp(ip: String): JsonNode = call("/ip", mapOf("ip" to ip))
}
The Retry-After header wins over the backoff on a 429. Every ApiException carries the documented error type and the X-Request-Id. See Errors and Rate limits.
3. Decide on a signup
package app
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withTimeoutOrNull
data class Verdict(val reject: Boolean, val reasons: List<String>, val review: Boolean, val e164: String?)
class SignupCheck(private val client: ValidateClient) {
suspend fun check(email: String, phone: String, country: String?, ip: String?): Verdict =
withTimeoutOrNull(12_000) {
coroutineScope {
val emailCheck = async { settle { client.verifyEmail(email) } }
val phoneCheck = async { settle { client.validatePhone(phone, country) } }
val ipCheck = async { if (ip.isNullOrBlank()) null else settle { client.lookupIp(ip) } }
val reasons = mutableListOf<String>()
var review = false
var e164: String? = null
emailCheck.await()?.let { result ->
val status = result.path("status").asText()
if (status == "undeliverable") {
val suggestion = result.path("did_you_mean")
reasons += if (suggestion.isTextual) "Did you mean ${suggestion.asText()}?" else "This email address cannot receive mail."
} else if (status == "risky" && result.path("reason").asText() == "disposable") {
review = true
}
}
phoneCheck.await()?.let { result ->
when (result.path("status").asText()) {
"invalid" -> reasons += "This phone number is not valid."
"valid" -> e164 = result.path("e164").asText(null)
}
}
ipCheck.await()?.let { result ->
if (result.path("risk").path("level").asText() == "high" || result.path("flags").path("tor").asBoolean()) review = true
}
Verdict(reasons.isNotEmpty(), reasons, review, e164)
}
} ?: Verdict(false, emptyList(), false, null)
private suspend fun <T> settle(task: suspend () -> T): T? =
try {
task()
} catch (error: ApiException) {
if (error.type != "unprocessable_input") {
System.err.println("validation skipped: ${error.type} status=${error.status} request_id=${error.requestId}")
}
null
} catch (error: java.io.IOException) {
System.err.println("validation skipped: ${error.javaClass.simpleName}")
null
}
}
A failed call returns null and never adds a reason: the signup goes through and you check it again later. If the overall twelve seconds run out, the verdict is "no objection". Only a clear negative answer blocks.
4. Use it
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val verdict = SignupCheck(ValidateClient()).check("jane@example.com", "+14155550123", null, "8.8.8.8")
if (verdict.reject) println("422: ${verdict.reasons}") else println("ok, phone ${verdict.e164}, review ${verdict.review}")
}
In Ktor or Spring, call check from your handler and answer 422 with verdict.reasons. Store e164 instead of what was typed.
5. What the fields mean
| Field | Value | Action |
|---|---|---|
Email status |
undeliverable |
Reject, show did_you_mean |
Email status |
risky |
Accept and flag, or reject disposable inboxes |
Email status |
unknown |
Accept |
Phone status |
valid |
Store e164 |
Phone status |
unknown |
Send country or ask for the + format |
IP risk.level |
high |
Ask for extra verification |
A 422 unprocessable_input on the IP is a private or loopback address, normal in local development, so the code ignores it. For many values at once, POST /batch takes up to 100 items in one request: see the batch reference.
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. Each email check costs 1 credit.
Related
Frequently asked questions
Is there an official Kotlin library?
Can I use OkHttp or Ktor client instead?
How do I run the three checks in parallel?
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