Skip to content
RocketVerifierDOCS

Libraries

Python SDK

In short

Run pip install rocketverifier, create RocketVerifier(api_key) and call rv.verify(email). The package covers every public endpoint with dataclass results, a matching AsyncRocketVerifier on httpx, safe retries with a stable Idempotency-Key and webhook signature helpers.

On this page

rocketverifier is the official Python library for the RocketVerifier API. One install gives you a synchronous client on requests and an async client on httpx, with the same methods: real-time verification, bulk jobs from a list or a file, progress and downloads, webhooks, monitors, credits and RocketVerifier Connect OAuth.

Package
rocketverifier
Version
1.4.0
Python
3.8+
Dependencies
requests (httpx for async)

Install the SDK#

Install from PyPI. Add the async extra for AsyncRocketVerifier.

Terminal
pip install rocketverifier
pip install "rocketverifier[async]"   # adds httpx for AsyncRocketVerifier

rocketverifier.__version__ holds the installed version, and every request sends it in the User-Agent header.

Create a client#

Pass your API key as the first argument. Read it from ROCKETVERIFIER_API_KEY so it never lands in source control. Use the client as a context manager, or call close() when you are done.

Python
import os
from rocketverifier import RocketVerifier

rv = RocketVerifier(os.environ["ROCKETVERIFIER_API_KEY"])

with RocketVerifier(os.environ["ROCKETVERIFIER_API_KEY"], timeout=15, max_retries=5) as rv:
    print(rv.verify("deliverable@sandbox.rocketverifier.com").status)

The constructor raises AuthenticationError when neither api_key nor access_token is given. Live keys start with rv_live_; sandbox keys start with rv_test_ and accept only sandbox addresses.

Arguments

  • api_keystr

    Your API key. Pass this or access_token. See authentication.

  • base_urlstrdefault https://api.rocketverifier.com

    API base URL.

  • timeoutfloatdefault 30.0

    HTTP timeout in seconds.

  • max_retriesintdefault 3

    Retries after the first attempt, on 429 responses, timeouts and connection errors. Set 0 to turn retries off.

  • access_tokenstr

    Keyword only. An OAuth access token (rv_at_...) from RocketVerifier Connect. Calls run on the connected user's account and credits.

  • refresh_tokenstr

    Keyword only. An OAuth refresh token (rv_rt_...). With oauth, a 401 invalid_token triggers one refresh and a retry.

  • oauthOAuth

    Keyword only. The OAuth client used for automatic refresh.

  • on_token_refreshCallable[[TokenSet], Any]

    Keyword only. Called with the new TokenSet after an automatic refresh. Persist the new refresh token here.

Verify an email#

rv.verify(email, idempotency_key=None, timeout=None) checks one address with POST /v1/verify and returns a VerificationResult dataclass. Branch on status and read sub_status for the reason.

Python
result = rv.verify("deliverable@sandbox.rocketverifier.com")

if result.status == "deliverable":
    pass  # send
elif result.status == "risky":
    print("Review:", result.sub_status, result.catch_all_verdict)
elif result.status == "undeliverable":
    print("Remove. Suggestion:", result.did_you_mean)
else:
    pass  # unknown: free, check again later
  • timeout is the server side verification timeout in seconds. The SDK accepts 5 to 60 and raises the HTTP timeout to cover it.
  • Pass your own idempotency_key when you retry a call yourself; otherwise a random key is generated per call.
  • Input without an @ raises ValidationError before any request is sent.

The reading results guide explains every status and sub_status.

Result fields#

VerificationResult uses the API's snake_case names.

FieldTypeNotes
emailstr
statusstrdeliverable, undeliverable, risky or unknown
sub_statusstrOne of SUB_STATUSES, "none" when not specific
scoreint0 to 100
reasonstr
catch_all_verdictstr | Nonesend_safe, send_with_caution or avoid for catch-all domains
did_you_meanstr | NoneTypo suggestion
verified_atstr | NoneISO 8601
providerstr | NoneFor example google.com
domainDomainInfoname, accept_all, disposable, free, accept_all_confidence, accept_all_verdict
accountAccountInfo | Nonerole, disabled, full_mailbox
dnsDNSInfo | Nonetype, record
authentication_scoreint | NoneSPF, DKIM and DMARC score
deliverability_tierstr | None
toxic, abusestr | None"yes", "no" or "unknown"
spam_trapbool | None
activity, evidencedict | None
rawdictThe full response, for any field not named above

result.is_deliverable (alias is_valid) is True when status == "deliverable".

Yes and no flags are booleans#

The API sends flags as the strings "yes", "no" and "unknown". The SDK converts them.

  • domain.disposable, domain.free and account.role are bool.
  • domain.accept_all, account.disabled, account.full_mailbox and spam_trap are True, False or None when the server reports "unknown".
  • toxic and abuse keep the original string.
Python
if result.domain.disposable or (result.account and result.account.role):
    flag_signup(result.email)

Verify a list in bulk#

rv.batch runs bulk jobs of up to 100,000 addresses. Create a job, wait for it with a progress callback, then read or download the results. The batch API reference covers the endpoints.

Python
job = rv.batch.create(
    emails=["deliverable@sandbox.rocketverifier.com", "undeliverable@sandbox.rocketverifier.com"],
    name="October signups",
)
print(job.id, job.credits_to_use, job.credits_remaining)

done = rv.batch.wait(
    job.id,
    poll_interval=3,
    on_progress=lambda j: print(f"{j.processed_emails}/{j.total_emails} ({j.progress:.0f}%)"),
)

rows = rv.batch.download(done.id, parse=True, filter="send_safe")

Create a job#

batch.create(emails, name=None, idempotency_key=None) returns a BatchJob with id, status (pending), total_emails, credits_to_use, credits_remaining and estimated_time_seconds. Lists longer than 100,000 entries raise ValidationError. To get a callback when the job finishes, register a webhook for job.completed.

Wait for a job#

batch.wait(job_id, poll_interval=5.0, timeout=300.0, on_progress=None) polls until the job is completed, failed or cancelled, and returns the final BatchJob. It also returns when a previewed upload reaches awaiting_confirmation. Past timeout seconds it raises RocketVerifierError with code timeout.

BatchJob has id, name, status, total_emails, processed_emails, valid_count, invalid_count, risky_count, catch_all_count, disposable_count, unknown_count, progress_percent, credits_used, download_url and timestamps, plus the properties progress, is_completed, is_failed, is_cancelled, is_finished and is_awaiting_confirmation.

Track progress#

batch.progress(job_id) reads the cheap progress endpoint and returns a JobProgress: status, total, processed, remaining, percent, counts (valid, invalid, risky, catch_all, disposable, unknown), counts_by_status (deliverable, undeliverable, risky, unknown), rate_per_minute, eta_seconds and timestamps.

Python
p = rv.batch.progress(job.id)
print(f"{p.percent}% done, ETA {p.eta_seconds}s")

Read results#

Python
page = rv.batch.results(job.id, page=1, limit=500)
print(page.total, page.has_more)

valid = [r.email for r in rv.batch.iter_results(job.id) if r.is_valid]
  • batch.results(job_id, page=1, limit=100) returns a JobResultsPage (limit up to 1000).
  • batch.iter_results(job_id, page_size=1000) yields every JobResult, fetching pages as you go.
  • Each JobResult has email, classification, is_valid, is_disposable, is_catch_all, is_role_based, confidence_score, sub_status and verified_at.

Download results#

batch.download(job_id, format="csv", parse=False, filter=None, include_original=False) fetches the full results file of a completed job.

Python
csv_text = rv.batch.download(job.id)
rows = rv.batch.download(job.id, parse=True)            # list of dicts
data = rv.batch.download(job.id, format="json")         # {"job_id": ..., "results": [...]}
safe = rv.batch.download(job.id, filter="send_safe", parse=True)
  • filter keeps only deliverable, undeliverable, risky, unknown or send_safe rows. send_safe is deliverable plus high-scoring catch-all addresses.
  • include_original=True joins upload jobs with your file's own columns, followed by rv_status, rv_sub_status, rv_score and the other rv_ columns.
  • With parse=True, the boolean columns become bool, confidence_score becomes a number and an empty verified_at becomes None. parse_results_csv(text) does the same for CSV you already have.
  • A job that is still running raises ValidationError with code == "job_not_complete".

Get, list and cancel jobs#

MethodReturns
batch.get(job_id)BatchJob
batch.list(limit=10, offset=0, status=None)list[BatchJob], newest first
batch.list_page(page=1, limit=20, status=None)JobsPage with jobs, total, page, limit, has_more. limit up to 100.
batch.delete(job_id), batch.cancel(job_id)JobCancelResult with success, job_id, refunded_credits, message

Upload a file#

batch.upload() creates a job from a CSV, TSV, TXT or XLSX file of up to 50 MB, or from a public HTTPS URL. Pass exactly one of file or source_url. See bulk upload for limits and column detection.

Python
up = rv.batch.upload("contacts.csv", email_column="Work Email", preview=True)
print(up.job_id, up.status)  # ..., "ingesting"

up2 = rv.batch.upload(source_url="https://northwind.io/exports/leads.csv", name="Leads")
ArgumentWhat it does
fileA path, bytes, or a binary file object.
filenameName with extension. Defaults to the path or the file object's name.
source_urlKeyword only. A public HTTPS URL the API fetches instead.
nameJob name.
email_columnHeader name or 0-based index of the email column.
column_mappingFor example {"email": "Work Email"}. Overrides email_column.
previewStop in awaiting_confirmation with a free list health preview.
callback_urlHTTPS URL that receives a signed POST when the job finishes.
content_typeMIME type of the file part. Defaults from the extension.
idempotency_keyMakes your own retries safe.

The result is a BulkUpload with job_id (also id), status, preview, status_url, progress_url and callback_secret, which is returned once when you set callback_url.

Preview and confirm an upload#

With preview=True, the job waits in awaiting_confirmation with a free estimate of the list's health. Read it with batch.preview, then charge and start the job with batch.confirm.

Python
import time

res = rv.batch.preview(up.job_id)
while res.pending:
    time.sleep(2)
    res = rv.batch.preview(up.job_id)
print(res.preview.estimated_bounce_rate, res.preview.credits_needed)

confirmed = rv.batch.confirm(up.job_id)
print(confirmed.credits_charged, confirmed.credits_remaining)
  • batch.preview(job_id, refresh=False) returns a BulkPreviewResult with job_id, status, preview and pending. BulkPreview has estimated_bounce_rate, undeliverable_share, risky_share, unknown_share, credits_needed, estimated_credits_after_refunds, free_checks, smtp_sample and confidence.
  • batch.confirm(job_id, idempotency_key=None) returns a BulkConfirmResult with credits_charged and credits_remaining. A job is never charged twice, so it is safe to retry.

Check a domain#

rv.domain.check(domain) combines the MX lookup and disposable check tools and returns a DomainCheckResult with domain, mx_records (each with priority and host), provider, disposable and has_valid_mx.

Python
info = rv.domain.check("northwind.io")
print(info.has_valid_mx, info.mx_records[0].host if info.mx_records else None)

Read credits and account#

rv.get_credits() returns credits, used_today and used_this_month. rv.get_me() returns the account behind the credential with GET /v1/me: email, name, account_type, organization, credits, auth_type, scopes and app.

Python
me = rv.get_me()
print(f"Connected as {me.email}, {rv.get_credits().credits} credits")

Manage monitors#

rv.monitors schedules list health re-verification (list_health) and SPF, DKIM and DMARC checks (domain_auth). Monitors need the monitors:read and monitors:write scopes. See the monitors API.

Python
monitor = rv.monitors.create(
    name="Newsletter list",
    type="list_health",
    emails=["maya@northwind.io", "deliverable@sandbox.rocketverifier.com"],
)
runs = rv.monitors.runs(monitor.id, page=1, limit=20)
MethodWhat it does
create(name, type, frequency="weekly", domain=None, emails=None, alert_threshold=5, idempotency_key=None)domain_auth needs domain; list_health needs emails.
list(), get(monitor_id)Return Monitor objects.
update(monitor_id, name=, frequency=, is_active=, alert_threshold=, domain=, emails=)Changes only the arguments you pass.
delete(monitor_id)Removes the monitor and its run history.
runs(monitor_id, page=1, limit=20)MonitorRunsPage, most recent first.
run_now(monitor_id, idempotency_key=None)Runs it immediately and returns the response dict. list_health runs cost 1 credit per address.

Manage webhook endpoints#

rv.webhooks registers HTTPS endpoints that receive signed events such as job.completed. It needs the webhooks:manage scope. The webhooks API lists every event and payload.

Python
hook = rv.webhooks.create(
    "https://northwind.io/hooks/rocketverifier",
    events=["job.completed", "job.failed", "credits.low"],
)
save_secret(hook.secret)  # shown only once
MethodReturns
events()list[WebhookEventType] with name and description.
list(), get(webhook_id)Webhook with is_active, success_count, failure_count and delivery timestamps.
create(url, events=None, name=None)Webhook with secret, signature_header and verification_instructions. The URL must use HTTPS. Events default to job.completed and job.failed.
update(webhook_id, name=, url=, events=, is_active=)The updated Webhook. Pass at least one field.
delete(webhook_id){"success": True, "message": ...}
test(webhook_id)WebhookTestResult with success, message, status_code, response_time_ms.
logs(webhook_id, page=1, limit=50, status=None)WebhookLogsPage. status is pending, success, failed or retrying.
rotate_secret(webhook_id){"success", "message", "secret"} with the new secret.

Verify webhook signatures#

Every delivery carries X-RocketVerifier-Signature: t=<unix>,v1=<hex>, an HMAC-SHA256 of the timestamp and the raw body. construct_event checks the signature and the timestamp, then returns the parsed event.

Python
import os
from flask import Flask, request
from rocketverifier import construct_event, WebhookSignatureError, SIGNATURE_HEADER

app = Flask(__name__)

@app.post("/hooks/rocketverifier")
def rocketverifier_webhook():
    try:
        event = construct_event(
            request.get_data(),  # raw bytes, not parsed JSON
            request.headers.get(SIGNATURE_HEADER, ""),
            os.environ["ROCKETVERIFIER_WEBHOOK_SECRET"],
        )
    except WebhookSignatureError as e:
        return e.code, 400

    if event["event"] == "job.completed":
        print("Job done:", event["data"]["job_id"])
    return "", 204
  • verify_webhook_signature(raw_body, header, secret, tolerance=300, now=None) returns True or False.
  • construct_event(raw_body, header, secret, tolerance=300, now=None) returns the event dict and raises WebhookSignatureError whose code is invalid_signature_header, timestamp_outside_tolerance, signature_mismatch, missing_secret or invalid_payload.
  • Pass the body as bytes or str exactly as received. A parsed dict raises TypeError.
  • During a secret rotation the header carries more than one v1 value, and any match passes.
  • generate_signature_header(raw_body, secret) builds a valid header for testing your endpoint locally.

Act for a user with OAuth#

The OAuth class runs the RocketVerifier Connect authorization code flow with PKCE, so your app can verify on another user's account and credits. The OAuth guide covers app registration; the OAuth quickstart walks through a full app.

Python
import os
from rocketverifier import OAuth, RocketVerifier

oauth = OAuth(
    client_id=os.environ["RV_CLIENT_ID"],
    client_secret=os.environ["RV_CLIENT_SECRET"],
    redirect_uri="https://northwind.io/rocketverifier/callback",
)

# 1. Send the user to the consent screen
auth = oauth.get_authorize_url(scopes=["verify:bulk", "account:read"])
# store auth.state and auth.code_verifier in the session, then redirect to auth.url

# 2. On the callback, after checking state
tokens = oauth.exchange_code(code=code, code_verifier=auth.code_verifier)

# 3. Call the API for that user, with automatic refresh
user_rv = RocketVerifier(
    access_token=tokens.access_token,
    refresh_token=tokens.refresh_token,
    oauth=oauth,
    on_token_refresh=lambda t: save_tokens(user_id, t),
)
MemberWhat it does
OAuth(client_id, client_secret=None, redirect_uri=None, issuer=..., token_endpoint_auth_method="client_secret_basic", timeout=30.0)Omit client_secret for public clients. issuer defaults to https://app.rocketverifier.com.
get_authorize_url(scopes, redirect_uri=, state=, code_verifier=, resource=, prompt=)AuthorizeUrl with url, state and code_verifier, generated when omitted.
exchange_code(code, code_verifier, redirect_uri=None)TokenSet. Codes are single use and expire after 60 seconds.
refresh(refresh_token)A new TokenSet. The refresh token rotates on every use.
revoke(token, token_type_hint=None)Revokes a token. Revoking a refresh token ends the connection.
introspect(token)The raw introspection dict (active, scope, ...).
aexchange_code, arefresh, arevoke, aintrospectAsync versions on httpx.

A TokenSet holds access_token, refresh_token, token_type, expires_in (seconds), expires_at (Unix seconds) and scopes.

How token refresh works#

When the API answers 401 invalid_token and the client has both refresh_token and oauth, it refreshes once, retries the call and passes the new tokens to on_token_refresh. A lock makes concurrent threads share one refresh, because refresh tokens are single use. Without refresh configured, the call raises InvalidTokenError. If the refresh token itself is rejected, OAuthError is raised with error == "invalid_grant": send the user through Connect again.

Use rv.set_tokens(access_token, refresh_token=None) to swap in tokens you refreshed elsewhere. OAUTH_SCOPES, generate_pkce_pair() and pkce_challenge() are exported for custom flows.

Use the async client#

AsyncRocketVerifier has the same methods as the sync client, as coroutines. Install the async extra, then use it as an async context manager or call await rv.aclose().

Python
import asyncio, os
from rocketverifier import AsyncRocketVerifier

async def main():
    async with AsyncRocketVerifier(os.environ["ROCKETVERIFIER_API_KEY"]) as rv:
        emails = ["maya@northwind.io", "deliverable@sandbox.rocketverifier.com"]
        results = await asyncio.gather(*(rv.verify(e) for e in emails))
        for r in results:
            print(r.email, r.status)

        job = await rv.batch.create(emails=emails)
        await rv.batch.wait(job.id)
        async for row in rv.batch.iter_results(job.id):
            print(row.email, row.classification)

asyncio.run(main())
  • The constructor takes the same arguments plus transport, an httpx.AsyncBaseTransport for proxies or httpx.MockTransport in tests.
  • on_token_refresh can be a plain function or a coroutine function.
  • AsyncRocketVerifier is imported lazily, so the sync client works without httpx installed.

Handle errors#

Every exception extends RocketVerifierError, which carries message, code, status_code and details.

ExceptionRaised whencode
AuthenticationError401, or no credential passed to the constructor.unauthorized
InvalidTokenError401 invalid_token for an OAuth token that cannot be refreshed. Extends AuthenticationError.invalid_token
InsufficientCreditsError402, or any response with code insufficient_credits (including the 403 at zero balance).insufficient_credits
RateLimitError429 after all retries. retry_after holds the seconds to wait.rate_limit_exceeded
ValidationError400 or 422, or input the SDK rejects before sending.the API's code, such as validation_error or job_not_complete
PermissionDeniedError403, for example a missing scope or an IP allowlist.the API's code, or forbidden
NotFoundError404: the job, webhook or monitor does not exist.the API's code, or not_found
WebhookSignatureErrorconstruct_event cannot trust a delivery.see signatures
OAuthErrorThe token, revoke or introspect endpoint returns an error. error holds the OAuth code.the OAuth error
RocketVerifierErrorEvery other status, timeouts and network failures.the API's code, timeout or network_error
Python
from rocketverifier import InsufficientCreditsError, RateLimitError, RocketVerifierError

try:
    rv.verify("maya@northwind.io")
except RateLimitError as e:
    print(f"Slow down for {e.retry_after}s")
except InsufficientCreditsError:
    print("Top up credits")
except RocketVerifierError as e:
    print(e.code, e.status_code, e.message)

The errors reference lists every API error code.

Retries and timeouts#

The client retries only what is safe and useful to retry, and never charges twice for a retried call.

  • Rate limits (429): retried up to max_retries times. Each retry waits for the Retry-After seconds, or 60 seconds when the header is missing. See rate limits.
  • Timeouts and connection errors: retried up to max_retries times, waiting 1, 2 and 3 seconds. After the last attempt, a timeout raises RocketVerifierError with code timeout.
  • Other errors: 4xx and 5xx responses raise straight away.
  • Idempotency: every POST, PUT and PATCH sends an Idempotency-Key, generated per call and reused on every retry of that call.

Set max_retries=0 to handle every retry yourself.

Type hints#

Every model is a dataclass with full type hints, and the package exports its constants: SUB_STATUSES, CATCH_ALL_VERDICTS, JOB_STATUSES, SIGNATURE_HEADER, EVENT_ID_HEADER and OAUTH_SCOPES. New sub_status values arrive as plain strings, so compare against the values you act on and keep a default branch.

Python
from rocketverifier import VerificationResult, CATCH_ALL_VERDICTS

def can_send(r: VerificationResult) -> bool:
    return r.status == "deliverable" or r.catch_all_verdict == "send_safe"

Next steps#

Frequently asked questions

Is there an async client?

Yes. Install rocketverifier[async] and use AsyncRocketVerifier. It has the same methods as the sync client, built on httpx.AsyncClient.

Which errors does the SDK retry?

Rate limits (429), timeouts and connection errors, up to max_retries times (3 by default). A 429 waits for the Retry-After seconds. Other 4xx and 5xx responses raise straight away.

Are the yes and no fields booleans in Python?

Yes. result.domain.disposable and result.account.role are bool. Fields that can be unknown, such as domain.accept_all, are True, False or None.

How do I read a response field the dataclass does not name?

Every VerificationResult keeps the full response in result.raw, for example result.raw.get("retry_after").

Updated 11 November 2026Suggest an edit