Skip to content

Integrations

Validate phone numbers and emails in Swift

Check emails, phone numbers and IPs from server-side Swift with URLSession and Codable. Typed results, timeouts, retries on rate limits and a fail-open signup check.

Updated 2026-11-23

This recipe calls the API from server-side Swift with URLSession and Codable. You get typed results for email, phone and IP checks, 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

  • Swift 5.9 or later, on macOS 12 or later or on Linux.
  • A Qelka API key in the API_KEY environment variable. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • Server-side code only. Do not ship the key in an app: see Authentication.

Steps

1. The client

swift
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

struct ApiError: Error {
    let status: Int
    let type: String
    let message: String
    let requestId: String?
}

struct EmailResult: Decodable {
    let status: String
    let reason: String
    let didYouMean: String?

    enum CodingKeys: String, CodingKey {
        case status, reason
        case didYouMean = "did_you_mean"
    }
}

struct PhoneResult: Decodable {
    let status: String
    let e164: String?
}

struct IpResult: Decodable {
    struct Flags: Decodable { let tor: Bool }
    struct Risk: Decodable { let level: String }
    let flags: Flags
    let risk: Risk
}

struct ValidateClient {
    let baseURL = "https://api.qelka.com/v1"
    let apiKey: String
    let session: URLSession

    init(apiKey: String = ProcessInfo.processInfo.environment["API_KEY"] ?? "") {
        self.apiKey = apiKey
        let configuration = URLSessionConfiguration.ephemeral
        configuration.timeoutIntervalForRequest = 12
        self.session = URLSession(configuration: configuration)
    }

    private func call<T: Decodable>(_ path: String, _ body: [String: String], as type: T.Type) async throws -> T {
        let payload = try JSONSerialization.data(withJSONObject: body)
        for attempt in 1... {
            var request = URLRequest(url: URL(string: baseURL + path)!)
            request.httpMethod = "POST"
            request.httpBody = payload
            request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")

            let (data, response) = try await session.data(for: request)
            let http = response as! HTTPURLResponse
            if (200..<300).contains(http.statusCode) {
                return try JSONDecoder().decode(T.self, from: data)
            }

            let error = (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?["error"] as? [String: Any]
            let failure = ApiError(
                status: http.statusCode,
                type: error?["type"] as? String ?? "unknown",
                message: error?["message"] as? String ?? "",
                requestId: http.value(forHTTPHeaderField: "X-Request-Id")
            )
            let retryable = [429, 500, 502, 503].contains(http.statusCode)
            if !retryable || attempt == 4 { throw failure }

            var seconds = Double(1 << (attempt - 1)) + Double.random(in: 0..<0.25)
            if let header = http.value(forHTTPHeaderField: "Retry-After"), let value = Double(header), value > 0 {
                seconds = value
            }
            try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
        }
        fatalError("unreachable")
    }

    func verifyEmail(_ email: String) async throws -> EmailResult {
        try await call("/email", ["email": email], as: EmailResult.self)
    }

    func validatePhone(_ phone: String, country: String? = nil) async throws -> PhoneResult {
        var body = ["phone": phone]
        if let country, !country.isEmpty { body["country"] = country }
        return try await call("/phone", body, as: PhoneResult.self)
    }

    func lookupIp(_ ip: String) async throws -> IpResult {
        try await call("/ip", ["ip": ip], as: IpResult.self)
    }
}

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.

2. Decide on a signup

swift
struct Verdict {
    var reject = false
    var reasons: [String] = []
    var review = false
    var e164: String?
}

func checkSignup(client: ValidateClient, email: String, phone: String, country: String?, ip: String?) async -> Verdict {
    var verdict = Verdict()

    func skipped(_ error: Error) {
        if let api = error as? ApiError {
            print("validation skipped: \(api.type) status=\(api.status) request_id=\(api.requestId ?? "-")")
        } else {
            print("validation skipped: \(type(of: error))")
        }
    }

    do {
        let result = try await client.verifyEmail(email)
        if result.status == "undeliverable" {
            verdict.reject = true
            verdict.reasons.append(result.didYouMean.map { "Did you mean \($0)?" } ?? "This email address cannot receive mail.")
        } else if result.status == "risky" && result.reason == "disposable" {
            verdict.review = true
        }
    } catch { skipped(error) }

    do {
        let result = try await client.validatePhone(phone, country: country)
        if result.status == "invalid" {
            verdict.reject = true
            verdict.reasons.append("This phone number is not valid.")
        } else if result.status == "valid" {
            verdict.e164 = result.e164
        }
    } catch { skipped(error) }

    if let ip, !ip.isEmpty {
        do {
            let result = try await client.lookupIp(ip)
            if result.risk.level == "high" || result.flags.tor { verdict.review = true }
        } catch let api as ApiError where api.type == "unprocessable_input" {
        } catch { skipped(error) }
    }
    return verdict
}

A failed call never sets reject: the signup goes through and you check it again later. Only a clear negative answer blocks.

3. Use it

In a command-line tool or a Vapor route handler:

swift
let verdict = await checkSignup(client: ValidateClient(), email: "jane@example.com", phone: "+14155550123", country: nil, ip: "8.8.8.8")
if verdict.reject {
    print("422", verdict.reasons)
} else {
    print("ok", verdict.e164 ?? "no e164", verdict.review ? "needs review" : "")
}

Store e164 instead of what was typed. Behind a proxy, read the client address from the header your proxy sets and trust only proxies you control.

4. 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.

Frequently asked questions

Can I call the API from an iOS app?
Not with your secret key. A key inside an app can be extracted by anyone who has the app, and then spent by them. Call the API from your server, for example a Vapor or Hummingbird service, and let the app call that server. The code below is meant for server-side Swift or command-line tools.
Is there an official Swift package?
No. The official client is the JavaScript SDK, so in Swift you call the HTTP API directly. It is plain HTTPS and JSON with one Authorization header, and URLSession with Codable covers it. You can also generate a client from the public OpenAPI 3.1 document.
Does URLSession work on Linux?
Yes, through FoundationNetworking, which the code below imports when it is available. On Linux the async URLSession API is available in recent toolchains. If your toolchain is older, use a library such as AsyncHTTPClient, keeping the same header, body and retry logic.

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