Integrations
Validate phone numbers and emails in FastAPI
Check emails, phone numbers and IPs in a FastAPI endpoint with httpx and asyncio. Run the three checks in parallel, return a 422 and fail open on API errors.
Updated 2026-11-23
This recipe validates a signup in a FastAPI endpoint. The email, phone number and client IP are checked in parallel with httpx, clear negatives answer 422 and an API outage never blocks a signup.
What you need
- Python 3.10 or later, FastAPI and
pip install httpx. - 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 and the decision
Save as validate.py:
import asyncio
import os
import random
import httpx
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
async def call(http, path, body):
for attempt in range(1, 5):
response = await http.post(BASE_URL + path, json=body, headers={"Authorization": f"Bearer {os.environ['API_KEY']}"})
if response.is_success:
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
await asyncio.sleep(wait)
async def settle(verdict, task):
try:
return await 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 httpx.HTTPError:
verdict["checked"] = False
print("validation skipped: unreachable")
return None
async def check_signup(http, email, phone, country=None, ip=None):
verdict = {"errors": {}, "checked": True, "e164": None, "review": False}
async def nothing():
return None
email_result, phone_result, ip_result = await asyncio.gather(
settle(verdict, call(http, "/email", {"email": email})) if email else nothing(),
settle(verdict, call(http, "/phone", {"phone": phone, **({"country": country} if country else {})})) if phone else nothing(),
settle(verdict, call(http, "/ip", {"ip": ip})) if ip else nothing(),
)
if email_result:
if email_result["status"] == "undeliverable":
suggestion = email_result.get("did_you_mean")
verdict["errors"]["email"] = f"Did you mean {suggestion}?" if suggestion else "This email address cannot receive mail."
elif email_result["status"] == "risky" and email_result["reason"] == "disposable":
verdict["review"] = True
if phone_result:
if phone_result["status"] == "invalid":
verdict["errors"]["phone"] = "This phone number is not valid."
elif phone_result["status"] == "valid":
verdict["e164"] = phone_result["e164"]
if ip_result and (ip_result["risk"]["level"] == "high" or ip_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.
2. The endpoint
from contextlib import asynccontextmanager
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from validate import check_signup
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.http = httpx.AsyncClient(timeout=12)
yield
await app.state.http.aclose()
app = FastAPI(lifespan=lifespan)
class Signup(BaseModel):
email: str
phone: str | None = None
country: str | None = None
@app.post("/signup", status_code=201)
async def signup(body: Signup, request: Request):
ip = request.client.host if request.client else None
verdict = await check_signup(request.app.state.http, body.email, body.phone, body.country, ip)
if verdict["errors"]:
return JSONResponse({"errors": verdict["errors"]}, status_code=422)
return {"phone": verdict["e164"] or body.phone, "needs_review": verdict["review"], "needs_recheck": not verdict["checked"]}
Behind a proxy, request.client.host is the proxy unless you run uvicorn with --proxy-headers and --forwarded-allow-ips set to the proxies you control. Store e164 instead of what was typed.
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
Why httpx and not requests?
How do I run the three checks in parallel?
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