# Ruby SDK

Source: https://docs.rocketverifier.com/sdks/ruby

> Run gem install rocketverifier, create RocketVerifier::Client.new(api_key) and call rv.verify(email). The gem uses only the Ruby standard library, converts yes and no flags to booleans, and retries safely with a stable Idempotency-Key.

The `rocketverifier` gem is the official Ruby library for the RocketVerifier API. It covers real-time verification, bulk jobs from a list or a file, progress and downloads, webhooks, monitors, credits and RocketVerifier Connect OAuth.

## Install the gem

Terminal:

```bash
gem install rocketverifier
# or in your Gemfile:
# gem "rocketverifier"
```

## Create a client

Pass your API key as the first argument and any options as keywords. Read the key from `ROCKETVERIFIER_API_KEY` so it never lands in source control.

Ruby:

```ruby
require "rocketverifier"

rv = RocketVerifier::Client.new(ENV.fetch("ROCKETVERIFIER_API_KEY"), timeout: 15, max_retries: 5)
```

The constructor raises `RocketVerifier::AuthenticationError` without a credential. Live keys start with `rv_live_`; sandbox keys start with `rv_test_` and accept only [sandbox addresses](https://docs.rocketverifier.com/sandbox). See [authentication](https://docs.rocketverifier.com/authentication).

| Keyword | Default | What it does |
| --- | --- | --- |
| `api_key:` | none | The API key, when no positional argument is given. |
| `access_token:` | none | An OAuth access token (`rv_at_...`). Calls run on the connected user's credits. |
| `refresh_token:` | none | OAuth refresh token for automatic refresh. |
| `oauth:` | none | A `RocketVerifier::OAuth` instance used for automatic refresh. |
| `on_token_refresh:` | none | Callable that receives the new `TokenSet`. Persist it here. |
| `base_url:` | `https://api.rocketverifier.com` | API base URL. |
| `timeout:` | `30` | Seconds for open, read and write. |
| `max_retries:` | `3` | Retries on 429, timeouts and network errors. `0` turns retries off. |
| `headers:` | `{}` | Extra headers on every request, applied last. |

## Verify an email

`rv.verify(email, idempotency_key: nil, timeout: nil)` checks one address with [`POST /v1/verify`](https://docs.rocketverifier.com/api/verify) and returns a `VerificationResult`. Branch on `status` and read `sub_status` for the reason.

Ruby:

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

case result.status
when "deliverable" then send_to(result.email)
when "risky" then review(result.email, result.sub_status, result.catch_all_verdict)
when "undeliverable" then puts "Remove. Suggestion: #{result.did_you_mean}"
when "unknown" then retry_later(result.email) # free
end
```

`timeout:` is the server side verification timeout in seconds. The gem accepts 5 to 60 and grows the HTTP timeout to cover it. Input without an `@` raises `ValidationError` before any request is sent. The [reading results guide](https://docs.rocketverifier.com/results) explains every status and `sub_status`.

### Result fields

`VerificationResult` has readers named after the API's snake_case fields: `email`, `status`, `reason`, `sub_status`, `score`, `provider`, `catch_all_verdict`, `verified_at`, `did_you_mean`, `domain`, `account`, `dns`, `authentication_score`, `deliverability_tier`, `toxic`, `abuse`, `spam_trap`, `activity` and `evidence`. `deliverable?`, `undeliverable?`, `risky?` and `unknown?` test the status.

- `domain.disposable`, `domain.free` and `account.role` are `true` only for `"yes"`.
- `domain.accept_all`, `account.disabled` and `account.full_mailbox` are `true`, `false` or `nil` when the server reports `"unknown"`.
- `spam_trap` is a boolean; `toxic` and `abuse` keep the original string.
- Every model has `raw`, `to_h` and `[]`, so `result["retry_after"]` reads any field the gem does not name.

## Verify a list in bulk

`rv.batch` runs bulk jobs of up to 100,000 unique addresses. The [batch API reference](https://docs.rocketverifier.com/api/batch) covers the endpoints.

Ruby:

```ruby
job = rv.batch.create(
  emails: ["deliverable@sandbox.rocketverifier.com", "undeliverable@sandbox.rocketverifier.com"],
  name: "October signups"
)

done = rv.batch.wait(job.job_id, poll_interval: 3) do |j|
  puts "#{j.processed_emails}/#{j.total_emails}"
end

rows = rv.batch.download(done.id, parse: true, filter: "send_safe")
```

| Method | Returns |
| --- | --- |
| `create(emails:, name: nil, idempotency_key: nil)` | `BatchCreateResult` with `job_id`, `total_emails`, `estimated_time_seconds`, `credits_to_use`, `credits_remaining` |
| `get(job_id)` | `BatchJob` with counts, `progress_percent`, timestamps, `finished?` and `awaiting_confirmation?` |
| `progress(job_id)` | `JobProgress` with `percent`, `counts`, `counts_by_status`, `rate_per_minute`, `eta_seconds` |
| `wait(job_id, poll_interval: 5, timeout: 300) { \|job\| }` | The final `BatchJob`. Yields every snapshot. Raises code `timeout` past `timeout` seconds. |
| `results(job_id, page: 1, limit: 100, classification: nil)` | `JobResultsPage`. `limit` up to 1000. |
| `each_result(job_id, page_size: 1000, classification: nil)` | Yields every `JobResult`, or returns an `Enumerator` without a block |
| `all_results(job_id, classification: nil)` | `Array` of `JobResult` |
| `download(job_id, format: "csv", parse: false, filter: nil, include_original: false)` | CSV string, parsed row hashes, or the parsed JSON |
| `list(page: 1, limit: 20, status: nil)` | `JobsPage`. `limit` up to 100. |
| `delete(job_id)`, `cancel(job_id)` | `JobDeleteResult` with `refunded_credits` |

`wait` also returns when a previewed upload reaches `awaiting_confirmation`. `download` filters by `deliverable`, `undeliverable`, `risky`, `unknown` or `send_safe`, and `include_original: true` joins upload jobs with your file's own columns.

## Upload a file

`rv.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](https://docs.rocketverifier.com/api/bulk-upload).

Ruby:

```ruby
upload = rv.batch.upload(file: "contacts.csv", email_column: "Work Email", preview: true)

res = rv.batch.preview(upload.job_id)
while res.pending?
  sleep 2
  res = rv.batch.preview(upload.job_id)
end
puts res.preview["estimated_bounce_rate"]

confirmed = rv.batch.confirm(upload.job_id)
puts confirmed.credits_charged
```

- `file:` is a path, an IO, or a string of bytes (then pass `filename:`). Other keywords: `filename:`, `source_url:`, `name:`, `email_column:`, `column_mapping:`, `preview:`, `callback_url:`, `content_type:` and `idempotency_key:`.
- `BatchUploadResult` has `job_id`, `status`, `preview`, `status_url`, `progress_url` and `callback_secret`, set once when you pass `callback_url:`.
- `confirm(job_id, idempotency_key: nil)` charges and starts the job. A job is never charged twice, so it is safe to retry.

## Check a domain, credits and account

Ruby:

```ruby
info = rv.domain.check("northwind.io") # domain, mx_records, provider, disposable, has_valid_mx
credits = rv.credits                   # credits, used_today, used_this_month (alias get_credits)
me = rv.me                             # email, account_type, organization, credits, auth_type, scopes, app
```

`rv.me` (alias `get_me`) calls [`GET /v1/me`](https://docs.rocketverifier.com/api/account). `me.oauth?` is true for OAuth tokens.

## Manage monitors

`rv.monitors` schedules list health re-verification and SPF, DKIM and DMARC checks. See the [monitors API](https://docs.rocketverifier.com/api/monitors).

Ruby:

```ruby
monitor = rv.monitors.create(name: "Brand domain", type: "domain_auth", domain: "northwind.io")
rv.monitors.update(monitor.id, frequency: "daily")
```

- `create(name:, type:, frequency: "weekly", domain: nil, emails: nil, alert_threshold: 5, idempotency_key: nil)`. `domain_auth` needs `domain:`; `list_health` needs `emails:`.
- `update(id, name:, frequency:, is_active:, alert_threshold:, domain:, emails:)` changes only what you pass.
- `list`, `get(id)`, `delete(id)`, `runs(id, page: 1, limit: 20)` and `run_now(id, idempotency_key: nil)` complete the set. `list_health` runs cost 1 credit per address.

## Manage webhook endpoints

`rv.webhooks` registers HTTPS endpoints for events such as `job.completed`. It needs the `webhooks:manage` scope. See the [webhooks API](https://docs.rocketverifier.com/api/webhooks).

Ruby:

```ruby
hook = rv.webhooks.create(
  url: "https://northwind.io/hooks/rocketverifier",
  events: %w[job.completed job.failed credits.low]
)
# Store hook.secret now: it is shown only once.
```

The resource also has `list_events`, `list`, `get(id)`, `update(id, name:, url:, events:, is_active:)`, `delete(id)`, `test(id)`, `logs(id, page: 1, limit: 50, status: nil)` and `rotate_secret(id)`.

## Verify webhook signatures

`RocketVerifier::Webhook.construct_event` checks the `X-RocketVerifier-Signature` header and the timestamp, then returns the parsed event hash. Pass the raw body exactly as received.

Ruby:

```ruby
post "/hooks/rocketverifier" do
  event = RocketVerifier::Webhook.construct_event(
    request.body.read,
    request.get_header("HTTP_X_ROCKETVERIFIER_SIGNATURE"),
    ENV.fetch("ROCKETVERIFIER_WEBHOOK_SECRET")
  )
  puts "Job #{event['data']['job_id']} finished" if event["event"] == "job.completed"
  200
rescue RocketVerifier::WebhookSignatureError => e
  halt 400, e.reason
end
```

- `Webhook.verify_signature(raw_body, header, secret, tolerance: 300, now: nil)` returns `true` or `false`.
- `WebhookSignatureError#reason` is `missing_secret`, `missing_header`, `malformed_header`, `timestamp_out_of_tolerance`, `signature_mismatch` or `invalid_json`.
- `Webhook.generate_signature_header(raw_body, secret)` builds a valid header for testing your endpoint.

## Act for a user with OAuth

`RocketVerifier::OAuth` runs the RocketVerifier Connect authorization code flow with PKCE. The [OAuth guide](https://docs.rocketverifier.com/oauth) covers app registration.

Ruby:

```ruby
oauth = RocketVerifier::OAuth.new(
  client_id: ENV.fetch("RV_CLIENT_ID"),
  client_secret: ENV.fetch("RV_CLIENT_SECRET"),
  redirect_uri: "https://northwind.io/rocketverifier/callback"
)

auth = oauth.authorize_url(scopes: %w[verify:bulk account:read])
session[:rv_state] = auth.state
session[:rv_verifier] = auth.code_verifier
redirect auth.url

# On the callback, after checking state:
tokens = oauth.exchange_code(code: params[:code], code_verifier: session[:rv_verifier])

user_rv = RocketVerifier::Client.new(
  access_token: tokens.access_token,
  refresh_token: tokens.refresh_token,
  oauth: oauth,
  on_token_refresh: ->(t) { save_tokens(user_id, t) }
)
```

- `OAuth.new(client_id:, client_secret: nil, redirect_uri: nil, issuer:, token_endpoint_auth_method: "client_secret_basic", timeout: 30)`. Omit the secret for public clients.
- `authorize_url`, `exchange_code`, `refresh(refresh_token)`, `revoke(token, token_type_hint: nil)` and `introspect(token)` complete the flow. `OAuth.generate_pkce_pair` and `OAuth::SCOPES` are available for custom flows.
- `TokenSet` has `access_token`, `refresh_token`, `token_type`, `expires_in`, `expires_at` (Unix seconds) and `scopes`.
- On a 401 `invalid_token` the client refreshes once, retries and calls `on_token_refresh`. Without refresh configured it raises `InvalidTokenError`. A rejected refresh token raises `OAuthError` with `error == "invalid_grant"`.
- `rv.set_tokens(access_token:, refresh_token:)` swaps in tokens refreshed elsewhere.

## Handle errors

Every error extends `RocketVerifier::Error`, with `code`, `status_code` and `details`.

| Error | Raised when |
| --- | --- |
| `AuthenticationError` | 401, or no credential passed. |
| `InvalidTokenError` | 401 `invalid_token` for an OAuth token that cannot be refreshed. |
| `InsufficientCreditsError` | 402, or code `insufficient_credits` (including the 403 at zero balance). |
| `RateLimitError` | 429 after all retries. `retry_after` holds the seconds. |
| `ValidationError` | 400 or 422, or input rejected before sending. |
| `PermissionDeniedError` | 403, such as a missing scope or an IP allowlist. |
| `NotFoundError` | 404. |
| `WebhookSignatureError` | A delivery fails verification. |
| `OAuthError` | The token, revoke or introspect endpoint returns an error. |
| `Error` | Every other status, plus timeouts (`timeout`) and network failures (`network_error`). |

Ruby:

```ruby
begin
  rv.verify("maya@northwind.io")
rescue RocketVerifier::RateLimitError => e
  sleep(e.retry_after || 60)
rescue RocketVerifier::InsufficientCreditsError
  notify_billing
rescue RocketVerifier::Error => e
  warn "#{e.code}: #{e.message}"
end
```

The [errors reference](https://docs.rocketverifier.com/errors) lists every API error code.

## Retries and timeouts

- **Rate limits (429):** retried up to `max_retries` times, waiting for the `Retry-After` seconds, or 60 seconds when the header is missing. See [rate limits](https://docs.rocketverifier.com/rate-limits).
- **Timeouts and network errors:** retried with 1, 2 and 3 second waits.
- **Other errors:** raised straight away.
- **Idempotency:** every POST, PUT and PATCH sends an `Idempotency-Key` reused across retries of that call.

## Next steps

- [Reading results](https://docs.rocketverifier.com/results)
Every status and sub_status, what it costs and what to do with it.
- [All SDKs](https://docs.rocketverifier.com/sdks)
Compare the Node.js, Python, Go, PHP and Ruby libraries and the CLI.

## Frequently asked questions

### Does the gem have runtime dependencies?

No. It uses net/http, json and openssl from the standard library and supports Ruby 2.6 and later.

### Is the client thread safe?

Yes for OAuth refresh: a mutex makes concurrent threads share one refresh. Each request opens its own Net::HTTP connection.

### Which errors does the gem retry?

Rate limits (429), timeouts and network errors, up to `max_retries` times (3 by default). Other 4xx and 5xx responses raise straight away.
