Integrations
Validate phone numbers and emails in Python
Verify emails, phone numbers and IP addresses from Python with requests. Read the result, reject bad input, flag risky signups and retry on rate limits.
Updated 2026-11-23
This recipe validates an email, a phone number and an IP address from Python, using requests. It works in a Django view, a Flask route, a FastAPI handler or a plain script.
What you need
- Python 3.9 or later and
pip install requests. - A Qelka API key in the
API_KEYenvironment variable. Ask_test_key returns simulated results and never spends credits, which is right for development: see Test mode. - Server-side code only. A key in a browser or mobile app can be read and spent by anyone: see Authentication.
Steps
1. A small client
import os
import random
import time
import requests
BASE_URL = "https://api.qelka.com/v1"
RETRYABLE = {429, 500, 502, 503}
class ApiError(Exception):
def __init__(self, status, error_type, message, request_id):
super().__init__(f"{error_type}: {message}")
self.status = status
self.type = error_type
self.request_id = request_id
def call_api(path, body, max_attempts=4, timeout=10):
headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
for attempt in range(1, max_attempts + 1):
response = requests.post(f"{BASE_URL}{path}", headers=headers, json=body, timeout=timeout)
if response.ok:
return response.json()
if response.status_code in RETRYABLE and attempt < max_attempts:
retry_after = response.headers.get("Retry-After", "")
delay = int(retry_after) if retry_after.isdigit() else min(2 ** (attempt - 1), 16) + random.random() / 4
time.sleep(delay)
continue
failure = response.json()["error"]
raise ApiError(response.status_code, failure["type"], failure["message"], response.headers.get("X-Request-Id"))
Every failure raises ApiError with the documented error.type and the X-Request-Id to quote to support. A 429 waits for Retry-After seconds. A 500 or 502 backs off with a little jitter. Other errors fail at once, since retrying them fails the same way. See Errors and Rate limits.
2. Check a signup
def check_signup(email, phone, country=None, ip=None):
errors = []
checked = True
e164 = None
review = False
try:
result = call_api("/email", {"email": email})
if result["status"] == "undeliverable":
suggestion = result["did_you_mean"]
errors.append({"field": "email", "message": f"Did you mean {suggestion}?" if suggestion else "This email address cannot receive mail."})
elif result["status"] == "risky" and result["reason"] == "disposable":
review = True
except (ApiError, requests.RequestException) as error:
checked = False
log_failure(error)
try:
body = {"phone": phone}
if country:
body["country"] = country
result = call_api("/phone", body)
if result["status"] == "valid":
e164 = result["e164"]
elif result["status"] == "invalid":
errors.append({"field": "phone", "message": "This phone number is not valid."})
except (ApiError, requests.RequestException) as error:
checked = False
log_failure(error)
if ip:
try:
result = call_api("/ip", {"ip": ip})
review = review or result["risk"]["level"] == "high" or result["flags"]["tor"]
except ApiError as error:
if error.type != "unprocessable_input":
checked = False
log_failure(error)
except requests.RequestException as error:
checked = False
log_failure(error)
return {"ok": not errors, "errors": errors, "checked": checked, "e164": e164, "review": review}
def log_failure(error):
request_id = getattr(error, "request_id", None)
print(f"validation skipped: {error} request_id={request_id}")
3. Read the result
| Field | Meaning | What to do |
|---|---|---|
email.status = undeliverable |
Bad syntax, no such domain or mailbox | Reject, show did_you_mean |
email.status = risky |
Disposable inbox, catch-all domain, full mailbox | Accept and flag, or reject disposables |
email.status = unknown |
The checks could not conclude | Accept, confirm by email |
phone.status = valid |
Valid in its numbering plan | Store e164 |
phone.status = unknown |
No + prefix and no country sent |
Send country |
ip.risk.level = high |
Hosting, VPN, proxy or Tor signals | Ask for extra verification |
The fail open rule matters: when checked is False, accept the signup and re-check in a background job. Only a clear negative answer should block a person.
An IP such as 127.0.0.1 returns 422 unprocessable_input. In local development this is normal, so the code above ignores it. Behind a proxy, read the client address from the right header: see Flag VPN and data center traffic.
4. Many values at once
For lists, send up to 100 items in one request, which counts as a single request for rate limiting:
items = [
{"type": "email", "email": "jane@example.com"},
{"type": "phone", "phone": "+14155550123"},
{"type": "ip", "ip": "8.8.8.8"},
]
batch = call_api("/batch", {"items": items})
for entry in batch["data"]:
if entry["object"] == "error":
print(entry["index"], entry["error"]["type"])
A failed item comes back as an error object inside data; the rest still run. For whole files, use a bulk job.
Related
Frequently asked questions
Is there an official Python package?
Which timeout should I set?
Can I use httpx or aiohttp instead of requests?
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