Skip to Content
ExamplesPython

Python Examples

VerifNow provides an official Python SDK, verifnow. You can also call the API directly with requests or httpx if you would rather not add a dependency.

Official SDK: 📦 verifnow on PyPI  — typed client for all seven validators 💻 verifnowio/verifnow-python  — source, changelog and issues


The SDK has zero runtime dependencies, is fully typed (py.typed, checked with mypy --strict), and runs on Python 3.10+. What it does for you that a hand-written request does not:

  • typed, frozen results — email_details, vat_details, iban_details, phone_details, with the API’s field names mapped to snake_case throughout;
  • typed exceptions, so you can tell a bad key from a spent quota from an outage without parsing strings;
  • retries on connection failures and 5xx, with backoff — never on a 400 or 401, which would fail the same way twice;
  • a timeout on every call (5 seconds by default);
  • an asyncio client, AsyncVerifNow, with the same methods.

Install and configure

pip install verifnow
from verifnow import VerifNow client = VerifNow() # reads the VERIFNOW_API_KEY environment variable # or, explicitly: # client = VerifNow("vn_...", timeout=5.0) # retry=None disables retries

Create one client and share it: it holds no per-request state and is safe across threads.

Validate an email

result = client.validate_email("user@gmial.com") if not result.valid: # A hard fact: malformed, no mail records, or a blocked domain. The message says which. print(result.message) signals = result.email_details.signals if result.email_details else None if signals and signals.typo_detected: print(f"Did you mean user@{signals.suggested_domain}?") # gmail.com print(signals.disposable) # True for a throwaway inbox print(signals.role_based) # True for contact@, info@ — a signal, not a rejection print(signals.free_provider) # None on FREE and STARTER: not computed at that depth

Signals are reported, not enforced: valid rests on hard facts only, and is the same on every plan. A signal your plan does not compute is None, never False. See Validate Email for which signals each plan returns.

Validate a VAT number

VAT is the one validator where the answer can be unknown rather than yes or no, because it depends on VIES — a registry that goes down. Handle that third case explicitly.

vat = client.validate_vat("IE6388047V").vat_details print(vat.format_valid) # True — decided locally, never depends on VIES print(vat.registered) # True | False | None — None means VIES could not be asked print(vat.source) # "LIVE" | "CACHE" | "STALE" | "UNVERIFIED" | "NOT_APPLICABLE" print(vat.trader_name) # "GOOGLE IRELAND LIMITED", when the member state discloses it print(vat.checked_at) # a timezone-aware datetime if vat.registered is None: # Not a rejection: accept, record that it is unconfirmed, and re-check later. ...

Test with is False and is None, not with not vat.registered: that would lump “not registered” and “VIES was down” together, and reject real businesses during someone else’s outage. See Validate VAT for the full degradation contract.

Validate an IBAN

result = client.validate_iban("FR23111111111111111111111") print(result.valid) # False print(result.message) # "A FR IBAN is 27 characters long" print(result.iban_details.checksum_valid) # True — the check digits are fine… print(result.iban_details.structure_valid) # False — …the length is impossible for France

On a valid IBAN, store normalized_value and show iban_details.formatted back to the user. See Validate IBAN.

Validate a phone number

result = client.validate_phone("+33 6 12 34 56 78") print(result.normalized_value) # "+33612345678" — E.164, the form to store print(result.phone_details.country_code) # "FR" print(result.phone_details.line_type) # "MOBILE"

The number must include its country code. See Validate Phone.

Handle errors

The SDK raises instead of returning valid=True when a call fails, so that accepting unverified input is a decision you make rather than an accident.

import logging from verifnow import ( VerifNow, VerifNowAuthError, VerifNowConnectionError, VerifNowRateLimitError, VerifNowRequestError, ) log = logging.getLogger(__name__) client = VerifNow() def is_email_acceptable(email: str) -> bool: try: result = client.validate_email(email) except VerifNowAuthError: # A missing, invalid or revoked key. Retrying will not help: fix the configuration. raise except VerifNowRateLimitError: # Monthly quota spent, or too many requests in flight. The SDK already retried the ones # worth retrying; this one is not going to clear in the next second. raise except VerifNowRequestError: # The request itself was malformed (400). raise except VerifNowConnectionError as error: # Unreachable or timed out, after retries. Accepting the address unverified is a # reasonable choice — make it deliberately, and log it. log.warning("VerifNow unreachable, accepting unverified (timed_out=%s)", error.timed_out) return True signals = result.email_details.signals if result.email_details else None return result.valid and not (signals and signals.disposable)

An error the API returned carries its HTTP status and the request_id — quote the request id if you contact support. A connection error has neither: it never reached the API. All of them inherit from VerifNowError.

In a FastAPI route

AsyncVerifNow runs each call in a worker thread, so a validation never blocks the event loop — retries included.

from fastapi import FastAPI, HTTPException from pydantic import BaseModel from verifnow import AsyncVerifNow, VerifNowConnectionError app = FastAPI() verifnow = AsyncVerifNow() class Registration(BaseModel): email: str @app.post("/register", status_code=201) async def register(body: Registration) -> dict[str, bool]: try: result = await verifnow.validate_email(body.email) except VerifNowConnectionError: # Unreachable after retries: this example lets registration through, unverified. # Any other VerifNowError — a bad key, a spent quota — propagates as a 500: it is your # problem, not the user's, and must not be shown to them as "invalid email". result = None if result is not None: signals = result.email_details.signals if result.email_details else None if signals and signals.typo_detected: local = body.email.split("@")[0] raise HTTPException( 400, { "error": "Please check your email address.", "suggestion": f"{local}@{signals.suggested_domain}", }, ) if not result.valid: raise HTTPException(400, {"error": result.message}) if signals and signals.disposable: raise HTTPException(400, {"error": "Please use a permanent email address."}) # …create the user return {"ok": True}

In a Django form

# forms.py import logging from django import forms from verifnow import VerifNow, VerifNowConnectionError log = logging.getLogger(__name__) verifnow = VerifNow() # module level: one client for the whole process class SupplierForm(forms.Form): company_name = forms.CharField(max_length=200) vat_number = forms.CharField(max_length=20) def clean(self): cleaned = super().clean() number = cleaned.get("vat_number") if not number: return cleaned try: result = verifnow.validate_vat(number, trader_name=cleaned.get("company_name")) except VerifNowConnectionError: log.warning("VerifNow unreachable, VAT number %s accepted unverified", number) cleaned["vat_verified"] = False return cleaned vat = result.vat_details if not vat.format_valid: self.add_error("vat_number", "That VAT number is not correctly formed.") elif vat.registered is False: self.add_error("vat_number", "That VAT number is not registered in VIES.") else: cleaned["vat_number"] = result.normalized_value or number cleaned["vat_verified"] = vat.registered is True # MISMATCH is a question for a human, not a rejection: route it to review. cleaned["vat_name_check"] = vat.trader_name_match return cleaned

registered is None passes the form unverified, which is the point: VIES being down is not the supplier’s fault. Re-check those later. See Onboarding suppliers: VAT and IBAN for what trader_name_match can and cannot tell you.

Cleaning a list

There is no batch endpoint, and a script is where that shows. Send the values one by one — or a few at a time, within your plan’s concurrency limit — and stop on a spent quota rather than hammering it:

import csv from verifnow import VerifNow, VerifNowRateLimitError client = VerifNow() with open("customers.csv", newline="") as source, open("checked.csv", "w", newline="") as target: writer = csv.writer(target) writer.writerow(["email", "valid", "suggestion", "risk_score"]) for row in csv.DictReader(source): try: result = client.validate_email(row["email"]) except VerifNowRateLimitError as error: print(f"Quota spent, resuming after {error.quota.reset_at if error.quota else 'reset'}") break details = result.email_details signals = details.signals if details else None writer.writerow([ row["email"], result.valid, signals.suggested_domain if signals else "", details.risk_score if details else "", ])

Every result carries quota.remaining: read it if you want to stop before the limit rather than at it.

These snippets need verifnow 0.1.0 or later. The SDK README lists every method and option: verifnowio/verifnow-python .


Option 2: Direct API call with requests

If you would rather not add a dependency, every endpoint is a single POST. You then own what the SDK does for you: typing, retries, timeouts, and telling the error cases apart.

import os import requests response = requests.post( "https://api.verifnow.io/api/v1/validate/email", headers={"X-API-KEY": os.environ["VERIFNOW_API_KEY"]}, json={"value": "user@example.com"}, timeout=5, ) if not response.ok: # Errors come back as {"error": "..."} or {"status": ..., "message": "..."}, depending on where # they were raised. Read both, and branch on the HTTP status rather than on the text. try: body = response.json() except ValueError: body = {} raise RuntimeError( f"VerifNow {response.status_code}: {body.get('message') or body.get('error') or response.reason}" ) result = response.json() signals = (result.get("emailDetails") or {}).get("signals") or {} print(result["valid"], signals.get("typo_detected"), signals.get("suggested_domain"))

Note the mix of conventions in the raw body: emailDetails at the top level, snake_case inside it. The SDK maps both to snake_case for you.

Check response.ok before reading valid. An error body has no valid field, so code that reads body.get("valid") on a 401 or a 429 gets None and will tell your user their email is invalid when the real problem is your API key or your quota.

Last updated on