Skip to content

Integrations

Validate phone numbers and emails in Elixir

Check emails, phone numbers and IPs from Elixir with Req. A small module with retries on rate limits, a fail-open signup check and a Phoenix controller example.

Updated 2026-11-23

This recipe calls the API from Elixir with Req. It gives you an email, phone and IP check run in parallel, retries that respect the rate limit and a signup decision that never blocks on an API problem.

What you need

  • Elixir 1.15 or later and {:req, "~> 0.5"} in mix.exs.
  • A Qelka API key. Read it at runtime from the API_KEY environment variable in config/runtime.exs. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • Server-side code only: see Authentication.

Steps

1. Configure the key

elixir
import Config

config :my_app, :validate_api_key, System.get_env("API_KEY")

2. The client

elixir
defmodule MyApp.Validate do
  @base_url "https://api.qelka.com/v1"
  @retryable [429, 500, 502, 503]

  defmodule Error do
    defexception [:status, :type, :message, :request_id]
  end

  def verify_email(email), do: call("/email", %{email: email})

  def validate_phone(phone, country \\ nil) do
    body = if country in [nil, ""], do: %{phone: phone}, else: %{phone: phone, country: country}
    call("/phone", body)
  end

  def lookup_ip(ip), do: call("/ip", %{ip: ip})

  defp call(path, body, attempt \\ 1) do
    response =
      Req.post!(@base_url <> path,
        json: body,
        auth: {:bearer, Application.fetch_env!(:my_app, :validate_api_key)},
        receive_timeout: 12_000,
        retry: false
      )

    cond do
      response.status in 200..299 ->
        {:ok, response.body}

      response.status in @retryable and attempt < 4 ->
        Process.sleep(retry_delay(response, attempt))
        call(path, body, attempt + 1)

      true ->
        error = get_in(response.body, ["error"]) || %{}

        {:error,
         %Error{
           status: response.status,
           type: error["type"] || "unknown",
           message: error["message"] || "",
           request_id: response |> Req.Response.get_header("x-request-id") |> List.first()
         }}
    end
  rescue
    exception in [Req.TransportError] -> {:error, exception}
  end

  defp retry_delay(response, attempt) do
    case response |> Req.Response.get_header("retry-after") |> List.first() |> parse_seconds() do
      seconds when is_integer(seconds) and seconds > 0 -> seconds * 1000
      _ -> Integer.pow(2, attempt - 1) * 1000 + :rand.uniform(250)
    end
  end

  defp parse_seconds(nil), do: nil

  defp parse_seconds(value) do
    case Integer.parse(value) do
      {seconds, ""} -> seconds
      _ -> nil
    end
  end
end

Req.post! raises on a transport failure, which the rescue turns into an {:error, exception} tuple. The Retry-After header wins over the backoff on a 429. Every Error carries the documented error type and the X-Request-Id. See Errors and Rate limits.

3. Decide on a signup

elixir
defmodule MyApp.SignupCheck do
  alias MyApp.Validate

  require Logger

  def check(email, phone, country \\ nil, ip \\ nil) do
    tasks = [
      fn -> {:email, settle(Validate.verify_email(email))} end,
      fn -> {:phone, settle(Validate.validate_phone(phone, country))} end,
      fn -> {:ip, if(ip in [nil, ""], do: nil, else: settle(Validate.lookup_ip(ip)))} end
    ]

    results =
      tasks
      |> Task.async_stream(& &1.(), timeout: 12_000, on_timeout: :kill_task, ordered: false)
      |> Enum.flat_map(fn
        {:ok, {key, value}} -> [{key, value}]
        _ -> []
      end)
      |> Map.new()

    verdict = %{reject: false, reasons: [], review: false, e164: nil}

    verdict
    |> apply_email(results[:email])
    |> apply_phone(results[:phone])
    |> apply_ip(results[:ip])
  end

  defp apply_email(verdict, %{"status" => "undeliverable"} = result) do
    reason =
      case result["did_you_mean"] do
        nil -> "This email address cannot receive mail."
        suggestion -> "Did you mean #{suggestion}?"
      end

    %{verdict | reject: true, reasons: [reason | verdict.reasons]}
  end

  defp apply_email(verdict, %{"status" => "risky", "reason" => "disposable"}), do: %{verdict | review: true}
  defp apply_email(verdict, _), do: verdict

  defp apply_phone(verdict, %{"status" => "invalid"}),
    do: %{verdict | reject: true, reasons: ["This phone number is not valid." | verdict.reasons]}

  defp apply_phone(verdict, %{"status" => "valid", "e164" => e164}), do: %{verdict | e164: e164}
  defp apply_phone(verdict, _), do: verdict

  defp apply_ip(verdict, %{"risk" => %{"level" => "high"}}), do: %{verdict | review: true}
  defp apply_ip(verdict, %{"flags" => %{"tor" => true}}), do: %{verdict | review: true}
  defp apply_ip(verdict, _), do: verdict

  defp settle({:ok, body}), do: body
  defp settle({:error, %Validate.Error{type: "unprocessable_input"}}), do: nil

  defp settle({:error, %Validate.Error{} = error}) do
    Logger.warning("validation skipped: #{error.type} status=#{error.status} request_id=#{error.request_id}")
    nil
  end

  defp settle({:error, _}) do
    Logger.warning("validation skipped: unreachable")
    nil
  end
end

A failed call returns nil and changes nothing: the signup goes through and you check it again later. Only a clear negative answer sets reject.

4. Use it in a Phoenix controller

elixir
defmodule MyAppWeb.SignupController do
  use MyAppWeb, :controller

  def create(conn, %{"email" => email, "phone" => phone} = params) do
    ip = conn.remote_ip |> :inet.ntoa() |> to_string()
    verdict = MyApp.SignupCheck.check(email, phone, params["country"], ip)

    if verdict.reject do
      conn |> put_status(422) |> json(%{errors: verdict.reasons})
    else
      conn |> put_status(201) |> json(%{phone: verdict.e164 || phone, needs_review: verdict.review})
    end
  end
end

Behind a proxy, conn.remote_ip is the proxy unless you use RemoteIp or an equivalent plug configured with the proxies you trust. 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.

Frequently asked questions

Is there an official Elixir package?
No. The official client is the JavaScript SDK, so in Elixir you call the HTTP API directly. It is plain HTTPS and JSON with one Authorization header, and Req handles JSON encoding, decoding and retries for you. You can also generate a client from the public OpenAPI 3.1 document.
Can I use HTTPoison, Finch or Tesla instead of Req?
Yes. The API does not care which client sends the request. Keep the same three parts: the Bearer header read from the environment, a JSON body, and a retry that waits for Retry-After on a 429. The code that reads the result stays identical.
How do I run the checks in parallel?
Use Task.async_stream over the checks with a timeout and on_timeout: :kill_task. The three calls are independent, so the signup waits for the slowest one. Each task catches its own failure and returns nil, so one failed check never blocks the others.

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