// frameworks and platforms
Via APIFastAPI email verification with pingutil
Pydantic's EmailStr validates the shape of an address, so a FastAPI signup endpoint accepts temp-mail domains and mailboxes that do not exist. A dependency that calls pingutil with an async client runs before your path operation, raises a 422 for throwaway or dead addresses, and hands the endpoint the category and status to store.
Where it connects: FastAPI dependency (Depends) on the signup path operation
What goes wrong without it
- EmailStr passes every disposable address, and our API is getting signups from scripts that rotate through them.
- We send a verification email on signup and a share of them bounce straight back.
- We added a blocking requests call to check emails and it stalled the event loop under load.
What you can do with FastAPI and pingutil
Reusable signup dependency
Declare Depends(screened_signup) on every endpoint that creates an account or a lead. The checks live in one function and the endpoint receives a ScreenedSignup.
Non-blocking checks
httpx.AsyncClient awaits pingutil without blocking the event loop, so a slow mail server delays one request, not the worker.
Return the typo suggestion to the client
The 422 detail includes did_you_mean, so your frontend can offer the corrected address.
Set it up
- 1
Create an API key in the pingutil dashboard and set PINGUTIL_KEY in the environment.
- 2
Install httpx and pydantic[email] (EmailStr needs the email-validator package).
- 3
Create one module-level httpx.AsyncClient with the base URL and Authorization header.
- 4
Write the screened_signup dependency: lookup with skip_enrichment, optional verify, HTTPException(422) on spam or invalid, None results passed through.
- 5
Inject it with Annotated[ScreenedSignup, Depends(screened_signup)] and store category and status with the user.
# app/main.py (FastAPI, httpx, Pydantic v2; pip install "pydantic[email]" httpx)
import os
import time
from dataclasses import dataclass
from typing import Annotated
import httpx
from fastapi import Depends, FastAPI, HTTPException
from pydantic import BaseModel, EmailStr
client = httpx.AsyncClient(
base_url="https://pingutil.com/v1",
headers={"Authorization": f"Bearer {os.environ['PINGUTIL_KEY']}"},
)
# domain -> (category, expires_at). Per worker process; use Redis to share it.
categories: dict[str, tuple[str, float]] = {}
async def pingutil(path: str, payload: dict, read_timeout: float) -> dict | None:
"""Parsed JSON, or None when pingutil is slow, down or rate limited (fail open)."""
try:
r = await client.post(path, json=payload, timeout=httpx.Timeout(read_timeout, connect=1.0))
except httpx.HTTPError: # includes TimeoutException
return None
return r.json() if r.is_success else None
class Signup(BaseModel):
email: EmailStr
password: str
@dataclass
class ScreenedSignup:
data: Signup
category: str | None # company, free, isp, educational, government...
status: str | None # valid, risky, unknown, or None when not checked
async def screened_signup(body: Signup) -> ScreenedSignup:
email = body.email.lower()
domain = email.rsplit("@", 1)[1]
cached = categories.get(domain)
if cached and cached[1] > time.time() and cached[0] == "disposable":
raise HTTPException(422, "Please use a permanent email address.")
lookup = await pingutil("/lookup", {"input": email, "skip_enrichment": True}, 2.0)
if lookup:
categories[lookup["domain"]] = (lookup["category"], time.time() + 86400)
if lookup["verdict"]["is_spam"]:
raise HTTPException(422, "This email address can't be used. Please use a different one.")
check = await pingutil("/verify", {"email": email}, 5.0)
if check and check["status"] == "invalid":
raise HTTPException(
422, {"message": "That mailbox does not exist.", "did_you_mean": check["did_you_mean"]}
)
return ScreenedSignup(
data=body,
category=lookup["category"] if lookup else None,
status=check["status"] if check else None,
)
app = FastAPI()
@app.post("/signup", status_code=201)
async def signup(signup: Annotated[ScreenedSignup, Depends(screened_signup)]):
# create the user from signup.data; store signup.category and signup.status with it
return {"needs_review": signup.status != "valid"}What to do with each result
| pingutil result | Action in FastAPI |
|---|---|
| verdict.is_spam: true | Raise HTTPException(422) from the dependency; the path operation never runs. |
| status: invalid | Raise HTTPException(422) with did_you_mean in the detail. |
| status: risky or unknown | Return normally; store needs_review and require email confirmation. |
| category: company | Enqueue a background task to create a CRM lead or fetch the company profile. |
Limits to plan for
- The in-process dict is per worker; with several Uvicorn workers or pods use Redis for the category cache.
- httpx timeouts are per operation (connect, read), so the read timeout is the practical ceiling for each call. Mailbox checks on slow servers can take seconds; the example stops at 5 s and fails open.
- Per-account defaults are 60 requests a minute, 300 verified addresses and 2,000 lookups a day (3,000 and 30,000 a month). Catch-all domains come back risky, never valid. Those are Free plan limits; Enterprise has custom limits.
FastAPI documentation
- fastapi.tiangolo.com/tutorial/dependencies/
- fastapi.tiangolo.com/tutorial/handling-errors/
- www.python-httpx.org/advanced/timeouts/
FastAPI is a trademark of its owner. This integration uses FastAPI's documented extension points; it is not an official FastAPI app.
Common questions
- Why a dependency and not a Pydantic validator?
- Pydantic validators are synchronous and run during parsing, which is the wrong place for a network call. A dependency is async, can raise HTTPException with a proper detail, and can be reused across endpoints.
- Should I verify in a background task instead?
- For the mailbox check, that is a good option when signup latency matters: create the user after the fast lookup, then run /v1/verify in a BackgroundTask and flag the account if the result is invalid.
Stop bad addresses in FastAPI today
Sign in with your email, create an API key and paste it into the step above. Test on a few real addresses first: the live demo shows exactly what your FastAPI setup will receive.