Integrations
Validate phone numbers and emails in Rust
Check emails, phone numbers and IPs from Rust with reqwest, serde and tokio. Typed results, timeouts, retries on rate limits and a fail-open signup check.
Updated 2026-11-23
This recipe calls the API from Rust with reqwest, serde and tokio. It gives you typed results, a deadline on every call, retries that respect the rate limit and a signup decision that never blocks on an API problem.
What you need
- Rust 1.75 or later.
- 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. Dependencies
[dependencies]
reqwest = { version = "0.12", features = ["json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
2. The client
use std::time::Duration;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde_json::{json, Value};
const BASE_URL: &str = "https://api.qelka.com/v1";
#[derive(Debug)]
pub struct ApiError {
pub status: u16,
pub kind: String,
pub message: String,
pub request_id: Option<String>,
}
#[derive(Debug)]
pub enum Error {
Api(ApiError),
Transport(reqwest::Error),
}
impl From<reqwest::Error> for Error {
fn from(error: reqwest::Error) -> Self {
Error::Transport(error)
}
}
#[derive(Debug, Deserialize)]
pub struct EmailResult {
pub status: String,
pub reason: String,
pub did_you_mean: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct PhoneResult {
pub status: String,
pub e164: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct IpFlags {
pub tor: bool,
}
#[derive(Debug, Deserialize)]
pub struct IpRisk {
pub level: String,
}
#[derive(Debug, Deserialize)]
pub struct IpResult {
pub flags: IpFlags,
pub risk: IpRisk,
}
pub struct Client {
http: reqwest::Client,
api_key: String,
}
impl Client {
pub fn from_env() -> Self {
let http = reqwest::Client::builder()
.connect_timeout(Duration::from_secs(5))
.timeout(Duration::from_secs(12))
.build()
.expect("http client");
Client { http, api_key: std::env::var("API_KEY").unwrap_or_default() }
}
async fn call<T: DeserializeOwned>(&self, path: &str, body: Value) -> Result<T, Error> {
let mut attempt: u32 = 1;
loop {
let response = self
.http
.post(format!("{BASE_URL}{path}"))
.bearer_auth(&self.api_key)
.json(&body)
.send()
.await?;
let status = response.status().as_u16();
if response.status().is_success() {
return Ok(response.json::<T>().await?);
}
let request_id = response
.headers()
.get("x-request-id")
.and_then(|value| value.to_str().ok())
.map(String::from);
let retry_after = response
.headers()
.get("retry-after")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<u64>().ok())
.filter(|seconds| *seconds > 0);
let parsed: Value = response.json().await.unwrap_or(Value::Null);
let error = &parsed["error"];
if ![429, 500, 502, 503].contains(&status) || attempt == 4 {
return Err(Error::Api(ApiError {
status,
kind: error["type"].as_str().unwrap_or("unknown").to_string(),
message: error["message"].as_str().unwrap_or("").to_string(),
request_id,
}));
}
let wait = retry_after.unwrap_or(1u64 << (attempt - 1));
tokio::time::sleep(Duration::from_secs(wait)).await;
attempt += 1;
}
}
pub async fn verify_email(&self, email: &str) -> Result<EmailResult, Error> {
self.call("/email", json!({ "email": email })).await
}
pub async fn validate_phone(&self, phone: &str, country: Option<&str>) -> Result<PhoneResult, Error> {
let mut body = json!({ "phone": phone });
if let Some(country) = country.filter(|value| !value.is_empty()) {
body["country"] = json!(country);
}
self.call("/phone", body).await
}
pub async fn lookup_ip(&self, ip: &str) -> Result<IpResult, Error> {
self.call("/ip", json!({ "ip": ip })).await
}
}
The Retry-After header wins over the backoff on a 429. Every ApiError carries the documented error type and the X-Request-Id. See Errors and Rate limits.
3. Decide on a signup
use tokio::time::{timeout, Duration};
#[derive(Debug, Default)]
pub struct Verdict {
pub reject: bool,
pub reasons: Vec<String>,
pub review: bool,
pub e164: Option<String>,
}
fn settle<T>(result: Result<T, Error>) -> Option<T> {
match result {
Ok(value) => Some(value),
Err(Error::Api(error)) if error.kind == "unprocessable_input" => None,
Err(Error::Api(error)) => {
eprintln!(
"validation skipped: {} status={} request_id={}",
error.kind,
error.status,
error.request_id.as_deref().unwrap_or("-")
);
None
}
Err(Error::Transport(_)) => {
eprintln!("validation skipped: unreachable");
None
}
}
}
pub async fn check_signup(client: &Client, email: &str, phone: &str, country: Option<&str>, ip: Option<&str>) -> Verdict {
let checks = async {
let ip_check = async {
match ip {
Some(value) if !value.is_empty() => settle(client.lookup_ip(value).await),
_ => None,
}
};
tokio::join!(
async { settle(client.verify_email(email).await) },
async { settle(client.validate_phone(phone, country).await) },
ip_check
)
};
let Ok((email_result, phone_result, ip_result)) = timeout(Duration::from_secs(12), checks).await else {
return Verdict::default();
};
let mut verdict = Verdict::default();
if let Some(result) = email_result {
if result.status == "undeliverable" {
verdict.reject = true;
verdict.reasons.push(match result.did_you_mean {
Some(suggestion) => format!("Did you mean {suggestion}?"),
None => "This email address cannot receive mail.".to_string(),
});
} else if result.status == "risky" && result.reason == "disposable" {
verdict.review = true;
}
}
if let Some(result) = phone_result {
if result.status == "invalid" {
verdict.reject = true;
verdict.reasons.push("This phone number is not valid.".to_string());
} else if result.status == "valid" {
verdict.e164 = result.e164;
}
}
if let Some(result) = ip_result {
if result.risk.level == "high" || result.flags.tor {
verdict.review = true;
}
}
verdict
}
A failed call returns None and never adds a reason: the signup goes through and you check it again later. Only a clear negative answer blocks.
4. Use it
#[tokio::main]
async fn main() {
let client = Client::from_env();
let verdict = check_signup(&client, "jane@example.com", "+14155550123", None, Some("8.8.8.8")).await;
println!("{verdict:?}");
}
In axum or actix, call check_signup 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 Rust crate?
Which TLS backend should reqwest use?
How do I run the three checks at once?
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