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
- Install the SDK
- Create a client
- Verify an email
- Result fields
- Yes and no flags are booleans
- Verify a list in bulk
- Create a job
- Wait for a job
- Track progress
- Read results
- Download results
- Get, list and cancel jobs
- Upload a file
- Preview and confirm an upload
- Check a domain
- Read credits and account
- Manage monitors
- Manage webhook endpoints
- Verify webhook signatures
- Act for a user with OAuth
- How token refresh works
- Use the async client
- Handle errors
- Retries and timeouts
- Type hints
- Next steps
- Frequently asked questions
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.
pip install rocketverifier
pip install "rocketverifier[async]" # adds httpx for AsyncRocketVerifierrocketverifier.__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.
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
0to 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_...). Withoauth, a 401invalid_tokentriggers 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
TokenSetafter 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.
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 latertimeoutis 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_keywhen you retry a call yourself; otherwise a random key is generated per call. - Input without an
@raisesValidationErrorbefore any request is sent.
The reading results guide explains every status and sub_status.
Result fields#
VerificationResult uses the API's snake_case names.
| Field | Type | Notes |
|---|---|---|
email | str | |
status | str | deliverable, undeliverable, risky or unknown |
sub_status | str | One of SUB_STATUSES, "none" when not specific |
score | int | 0 to 100 |
reason | str | |
catch_all_verdict | str | None | send_safe, send_with_caution or avoid for catch-all domains |
did_you_mean | str | None | Typo suggestion |
verified_at | str | None | ISO 8601 |
provider | str | None | For example google.com |
domain | DomainInfo | name, accept_all, disposable, free, accept_all_confidence, accept_all_verdict |
account | AccountInfo | None | role, disabled, full_mailbox |
dns | DNSInfo | None | type, record |
authentication_score | int | None | SPF, DKIM and DMARC score |
deliverability_tier | str | None | |
toxic, abuse | str | None | "yes", "no" or "unknown" |
spam_trap | bool | None | |
activity, evidence | dict | None | |
raw | dict | The 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.freeandaccount.rolearebool.domain.accept_all,account.disabled,account.full_mailboxandspam_trapareTrue,FalseorNonewhen the server reports"unknown".toxicandabusekeep the original string.
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.
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.
p = rv.batch.progress(job.id)
print(f"{p.percent}% done, ETA {p.eta_seconds}s")Read results#
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 aJobResultsPage(limitup to 1000).batch.iter_results(job_id, page_size=1000)yields everyJobResult, fetching pages as you go.- Each
JobResulthasemail,classification,is_valid,is_disposable,is_catch_all,is_role_based,confidence_score,sub_statusandverified_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.
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)filterkeeps onlydeliverable,undeliverable,risky,unknownorsend_saferows.send_safeis deliverable plus high-scoring catch-all addresses.include_original=Truejoins upload jobs with your file's own columns, followed byrv_status,rv_sub_status,rv_scoreand the otherrv_columns.- With
parse=True, the boolean columns becomebool,confidence_scorebecomes a number and an emptyverified_atbecomesNone.parse_results_csv(text)does the same for CSV you already have. - A job that is still running raises
ValidationErrorwithcode == "job_not_complete".
Get, list and cancel jobs#
| Method | Returns |
|---|---|
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.
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")| Argument | What it does |
|---|---|
file | A path, bytes, or a binary file object. |
filename | Name with extension. Defaults to the path or the file object's name. |
source_url | Keyword only. A public HTTPS URL the API fetches instead. |
name | Job name. |
email_column | Header name or 0-based index of the email column. |
column_mapping | For example {"email": "Work Email"}. Overrides email_column. |
preview | Stop in awaiting_confirmation with a free list health preview. |
callback_url | HTTPS URL that receives a signed POST when the job finishes. |
content_type | MIME type of the file part. Defaults from the extension. |
idempotency_key | Makes 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.
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 aBulkPreviewResultwithjob_id,status,previewandpending.BulkPreviewhasestimated_bounce_rate,undeliverable_share,risky_share,unknown_share,credits_needed,estimated_credits_after_refunds,free_checks,smtp_sampleandconfidence.batch.confirm(job_id, idempotency_key=None)returns aBulkConfirmResultwithcredits_chargedandcredits_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.
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.
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.
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)| Method | What 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.
hook = rv.webhooks.create(
"https://northwind.io/hooks/rocketverifier",
events=["job.completed", "job.failed", "credits.low"],
)
save_secret(hook.secret) # shown only once| Method | Returns |
|---|---|
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.
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 "", 204verify_webhook_signature(raw_body, header, secret, tolerance=300, now=None)returnsTrueorFalse.construct_event(raw_body, header, secret, tolerance=300, now=None)returns the event dict and raisesWebhookSignatureErrorwhosecodeisinvalid_signature_header,timestamp_outside_tolerance,signature_mismatch,missing_secretorinvalid_payload.- Pass the body as
bytesorstrexactly as received. A parsed dict raisesTypeError. - During a secret rotation the header carries more than one
v1value, 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.
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),
)| Member | What 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, aintrospect | Async 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().
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, anhttpx.AsyncBaseTransportfor proxies orhttpx.MockTransportin tests. on_token_refreshcan be a plain function or a coroutine function.AsyncRocketVerifieris imported lazily, so the sync client works withouthttpxinstalled.
Handle errors#
Every exception extends RocketVerifierError, which carries message, code, status_code and details.
| Exception | Raised when | code |
|---|---|---|
AuthenticationError | 401, or no credential passed to the constructor. | unauthorized |
InvalidTokenError | 401 invalid_token for an OAuth token that cannot be refreshed. Extends AuthenticationError. | invalid_token |
InsufficientCreditsError | 402, or any response with code insufficient_credits (including the 403 at zero balance). | insufficient_credits |
RateLimitError | 429 after all retries. retry_after holds the seconds to wait. | rate_limit_exceeded |
ValidationError | 400 or 422, or input the SDK rejects before sending. | the API's code, such as validation_error or job_not_complete |
PermissionDeniedError | 403, for example a missing scope or an IP allowlist. | the API's code, or forbidden |
NotFoundError | 404: the job, webhook or monitor does not exist. | the API's code, or not_found |
WebhookSignatureError | construct_event cannot trust a delivery. | see signatures |
OAuthError | The token, revoke or introspect endpoint returns an error. error holds the OAuth code. | the OAuth error |
RocketVerifierError | Every other status, timeouts and network failures. | the API's code, timeout or network_error |
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_retriestimes. Each retry waits for theRetry-Afterseconds, or 60 seconds when the header is missing. See rate limits. - Timeouts and connection errors: retried up to
max_retriestimes, waiting 1, 2 and 3 seconds. After the last attempt, a timeout raisesRocketVerifierErrorwith codetimeout. - 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.
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