Integrations
Validate phone numbers and emails in Flask
Check emails, phone numbers and IPs in a Flask route with requests. Return a 422 with field errors, flag risky signups and fail open when the API is unavailable.
Updated 2026-11-23
This recipe validates a signup in a Flask route. The email, phone number and client IP are checked, field errors go back as a 422 and an API outage never blocks a signup.
What you need
- Python 3.9 or later, Flask 2 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: see Test mode. - Server-side code only: see Authentication.
Steps
1. The client
Save as validate.py:
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(path, body, timeout=12):
for attempt in range(1, 5):
response = requests.post(
BASE_URL + path,
json=body,
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
timeout=timeout,
)
if response.ok:
return response.json()
error = response.json().get("error", {})
if response.status_code not in RETRYABLE or attempt == 4:
raise ApiError(response.status_code, error.get("type", "unknown"), error.get("message", ""), response.headers.get("X-Request-Id"))
retry_after = response.headers.get("Retry-After", "")
wait = int(retry_after) if retry_after.isdigit() and int(retry_after) > 0 else 2 ** (attempt - 1) + random.random() / 4
time.sleep(wait)
def verify_email(email):
return call("/email", {"email": email})
def validate_phone(phone, country=None):
body = {"phone": phone}
if country:
body["country"] = country
return call("/phone", body)
def lookup_ip(ip):
return call("/ip", {"ip": ip})
2. The decision
Add this to the same file:
def check_signup(email, phone, country=None, ip=None):
verdict = {"errors": {}, "checked": True, "e164": None, "review": False}
def settle(task):
try:
return task()
except ApiError as error:
if error.type != "unprocessable_input":
verdict["checked"] = False
print(f"validation skipped: {error.type} status={error.status} request_id={error.request_id}")
except requests.RequestException:
verdict["checked"] = False
print("validation skipped: unreachable")
return None
result = settle(lambda: verify_email(email)) if email else None
if result:
if result["status"] == "undeliverable":
suggestion = result.get("did_you_mean")
verdict["errors"]["email"] = f"Did you mean {suggestion}?" if suggestion else "This email address cannot receive mail."
elif result["status"] == "risky" and result["reason"] == "disposable":
verdict["review"] = True
result = settle(lambda: validate_phone(phone, country)) if phone else None
if result:
if result["status"] == "invalid":
verdict["errors"]["phone"] = "This phone number is not valid."
elif result["status"] == "valid":
verdict["e164"] = result["e164"]
result = settle(lambda: lookup_ip(ip)) if ip else None
if result and (result["risk"]["level"] == "high" or result["flags"]["tor"]):
verdict["review"] = True
return verdict
A failed call never adds an error: the signup goes through and checked is False, so a background job can check it again later. Only a clear negative answer blocks.
3. The route
from flask import Flask, jsonify, request
from werkzeug.middleware.proxy_fix import ProxyFix
from validate import check_signup
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
@app.post("/signup")
def signup():
data = request.get_json(silent=True) or {}
verdict = check_signup(data.get("email"), data.get("phone"), data.get("country"), request.remote_addr)
if verdict["errors"]:
return jsonify(errors=verdict["errors"]), 422
user = create_user(
email=data["email"],
phone=verdict["e164"] or data.get("phone"),
needs_review=verdict["review"],
needs_recheck=not verdict["checked"],
)
return jsonify(id=user.id), 201
create_user is your own function. Set x_for to the number of proxies in front of the app. Store e164 instead of what was typed. Put a rate limiter such as Flask-Limiter on the route so a bot cannot spend your credits through it.
Read the result
| Result | Action |
|---|---|
Email undeliverable |
Reject with 422, show did_you_mean |
Email risky, reason disposable |
Flag, or reject if you block disposable inboxes |
Email unknown |
Accept and confirm by email |
Phone valid |
Store e164 |
Phone unknown |
No + and no country: send the country |
IP high risk or Tor |
Flag for review, add friction |
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, and Retry-After says how long to wait. Each email check costs 1 credit. See Errors and Rate limits.
Related
Frequently asked questions
Should I call the API in the route or in a background task?
How do I get the real client IP in Flask?
What happens if the API is down?
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