Ruby Screenshot API Tutorial: Net::HTTP, Faraday, Rails and Sidekiq
Working Ruby code for the Screenshotly screenshot API: a stdlib quick start, a Faraday client with Retry-After handling, Rails jobs that attach captures to Active Storage, and webhook verification.
Ruby apps tend to need screenshots in the background: a Rails CMS that stores a preview of every linked page, a Sidekiq job that snapshots customer dashboards for weekly reports, or a rake task that archives a list of URLs. This guide shows how to call the Screenshotly API from plain Ruby, Faraday, Active Job and Sidekiq, and how to store the results with Active Storage.
Every request body below was checked against the API's request schema, and the snippets were run against a local mock of the API (including the retry and error paths) with Ruby 3.3, Faraday 2.15, faraday-retry 2.4, Active Job 8.1 and Sidekiq 8.1.
The API contract in one table
| Endpoint | POST https://screenshotly.app/api/screenshot |
| Authentication | x-api-key: YOUR_API_KEY header (Authorization: Bearer YOUR_API_KEY also works) |
| Body | JSON. Only url is required. Unknown fields are rejected with 400. |
| Success | 200 with the file as the body (image/png, image/jpeg, image/webp, application/pdf, …) |
| Errors | JSON {"error": "...", "message": "..."} with 400, 401, 403, 413, 429, 500 or 503 |
The full parameter list is in the screenshot API reference. Sign up to get a key; the Free plan includes 100 captures in total, and failed captures do not count against it.
Quick start: Net::HTTP
No gems needed:
require 'net/http'
require 'json'
SCREENSHOTLY_URI = URI('https://screenshotly.app/api/screenshot')
class ScreenshotlyError < StandardError
attr_reader :status, :retry_after
def initialize(message, status:, retry_after: nil)
super(message)
@status = status
@retry_after = retry_after
end
end
def capture_screenshot(url, path, **options)
request = Net::HTTP::Post.new(SCREENSHOTLY_URI)
request['x-api-key'] = ENV.fetch('SCREENSHOTLY_API_KEY')
request['Content-Type'] = 'application/json'
request.body = { url: url, format: 'png' }.merge(options).to_json
Net::HTTP.start(SCREENSHOTLY_URI.host, SCREENSHOTLY_URI.port,
use_ssl: SCREENSHOTLY_URI.scheme == 'https',
open_timeout: 10, read_timeout: 60) do |http|
http.request(request) do |response|
unless response.is_a?(Net::HTTPOK)
error = JSON.parse(response.body) rescue {}
raise ScreenshotlyError.new(
"HTTP #{response.code}: #{error['message'] || error['error']}",
status: response.code.to_i,
retry_after: response['Retry-After']&.to_i
)
end
# Stream the body to disk instead of holding it in memory
File.open(path, 'wb') { |file| response.read_body { |chunk| file.write(chunk) } }
end
end
end
# Usage
capture_screenshot('https://example.com', 'example.png', fullPage: true)
puts 'Saved example.png'
The block form of http.request lets you stream the body to disk with read_body, so a large full-page capture never sits in memory as one string. A capture can take tens of seconds on a slow page (page navigation alone may use up to 30 seconds), so read_timeout is 60 seconds. Pages slower than that belong in the async jobs API.
A Faraday client with sensible retries
For application code, use Faraday 2 and the faraday-retry middleware:
# Gemfile
# gem 'faraday', '~> 2.0'
# gem 'faraday-retry', '~> 2.0'
require 'faraday'
require 'faraday/retry'
require 'json'
class ScreenshotlyClient
class Error < StandardError
attr_reader :status
def initialize(message, status)
super(message)
@status = status
end
end
class ClientError < Error; end # 400, 401, 403, 413: retrying will not help
class ServerError < Error; end # 500, 503
class RateLimited < Error # 429
attr_reader :retry_after
def initialize(message, status, retry_after)
super(message, status)
@retry_after = retry_after
end
end
def initialize(api_key: ENV.fetch('SCREENSHOTLY_API_KEY'))
@connection = Faraday.new(
url: 'https://screenshotly.app',
headers: { 'x-api-key' => api_key },
request: { open_timeout: 10, timeout: 60 }
) do |f|
f.request :json
# POST is not retried by default; opt in. Retry-After is honoured, and a
# Retry-After longer than max_interval (an exhausted quota) is not retried.
f.request :retry, max: 2, interval: 1, backoff_factor: 2, max_interval: 60,
methods: %i[post], retry_statuses: [429, 500, 503]
end
end
# Returns the file as a binary String.
def capture(url, **options)
response = @connection.post('/api/screenshot', { url: url, format: 'png' }.merge(options))
return response.body if response.status == 200
error = JSON.parse(response.body) rescue {}
message = "Screenshotly HTTP #{response.status}: #{error['message'] || error['error']}"
case response.status
when 429 then raise RateLimited.new(message, 429, response.headers['retry-after'].to_i)
when 500..599 then raise ServerError.new(message, response.status)
else raise ClientError.new(message, response.status)
end
end
end
# Usage
client = ScreenshotlyClient.new
File.binwrite('example.webp', client.capture('https://example.com', format: 'webp', quality: 80))
puts 'Saved example.webp'
How the retry settings map to the API's behaviour:
- 429 with a short
Retry-After: you hit the per-minute request limit (Free 5, Basic 40, Growth 80, Scale 200). faraday-retry waits the stated number of seconds and tries again. - 429 with a long
Retry-After: the plan's capture quota is used up, and the header points at the reset time, which can be days away. Because the value is abovemax_interval, faraday-retry does not retry, andcaptureraisesRateLimitedstraight away. - 500 and 503: the capture failed or the regional proxy was unavailable. Retried with backoff.
- 400, 401, 403 and 413 raise
ClientErrorand are never retried: invalid options, a bad key, a feature your plan does not include, or a request body over 64 KB.
f.request :json encodes the request body only. The response is left as a binary string, which is what you want for images and PDFs.
Capture options
Options are top-level JSON keys, written in camelCase. Some need a paid plan; when you send one your plan does not include, the API returns 403 with "error": "Plan upgrade required" and a minimumPlan field.
| Goal | Keys | Plan |
|---|---|---|
| Custom viewport | width: (320–3840), height: (240–3840), or device: desktop, laptop, tablet, mobile |
All |
| Whole page | fullPage: true |
All |
| Smaller files | format: 'webp' or 'jpeg' with quality: (0–100) |
All |
| Hide ads | blockAds: true |
All |
| Wait for content | delay: (ms, up to 10000), waitForSelector:, waitForNetworkIdle: true |
All |
| Retina output | deviceScaleFactor: 2 |
All |
| PDF or HTML output | format: 'pdf' or 'html' |
Basic+ |
| Logged-in pages | headers:, cookies: |
Basic+ |
| Remove cookie banners and chat widgets | aiRemoval: { enabled: true, types: %w[cookie-banner chat-widget] } |
Growth+ |
| Device frame | mockup: 'iphone-14' (also ipad-pro, macbook-pro, browser-light, browser-dark, browser-minimal) |
Growth+ |
PDF output is A4 with 1 cm margins and is not configurable. See pricing for what each plan includes.
Rails: client, credentials and Active Storage
Store the key in encrypted credentials (bin/rails credentials:edit):
screenshotly:
api_key: your-api-key
webhook_secret: a-long-random-string
Put the Faraday client in app/clients/screenshotly_client.rb and give it one shared instance that reads from credentials:
class ScreenshotlyClient
def self.default
@default ||= new(api_key: Rails.application.credentials.dig(:screenshotly, :api_key))
end
end
The model just needs an attachment:
class Page < ApplicationRecord
has_one_attached :screenshot
end
Active Job
Capture in a job, never in a controller action. This one retries server and network errors with backoff, waits out short 429s, discards requests that can never succeed, and lets a quota error fail loudly:
# app/jobs/capture_screenshot_job.rb
class CaptureScreenshotJob < ApplicationJob
queue_as :screenshots
retry_on ScreenshotlyClient::ServerError, Faraday::ConnectionFailed, Faraday::TimeoutError,
wait: :polynomially_longer, attempts: 5
discard_on ScreenshotlyClient::ClientError do |job, error|
Rails.logger.error("Screenshot for Page #{job.arguments.first.id} discarded: #{error.message}")
end
def perform(page)
image = ScreenshotlyClient.default.capture(page.url, fullPage: true, blockAds: true)
page.screenshot.attach(
io: StringIO.new(image),
filename: "page-#{page.id}.png",
content_type: 'image/png'
)
rescue ScreenshotlyClient::RateLimited => e
# Long Retry-After = quota used up: let the job fail and surface in your error tracker.
raise if e.retry_after > 1.hour.to_i
retry_job wait: e.retry_after.seconds
end
end
Enqueue it from the controller or a model callback:
CaptureScreenshotJob.perform_later(page)
wait: :polynomially_longer needs Rails 7.1 or later. On older versions use :exponentially_longer.
Sidekiq without Active Job
With a native Sidekiq job, sidekiq_retry_in can use the exception to pick the delay. Returning :kill moves the job to the Dead set without further retries:
# app/sidekiq/screenshot_job.rb
class ScreenshotJob
include Sidekiq::Job
sidekiq_options queue: :screenshots, retry: 5
sidekiq_retry_in do |count, exception, _job|
case exception
when ScreenshotlyClient::RateLimited
exception.retry_after <= 3600 ? exception.retry_after : :kill
when ScreenshotlyClient::ClientError
:kill # straight to the Dead set; retrying will not help
else
(count**4) + 15 # roughly Sidekiq's default backoff
end
end
def perform(page_id)
page = Page.find(page_id)
image = ScreenshotlyClient.default.capture(page.url, fullPage: true)
page.screenshot.attach(io: StringIO.new(image), filename: "page-#{page.id}.png", content_type: 'image/png')
end
end
Keep the Sidekiq concurrency for this queue below your plan's per-minute limit. For example, ten threads that each finish a capture every few seconds can exceed the Free plan's 5 requests per minute almost immediately.
Slow pages, PDFs and batches: the async jobs API
On the Basic plan and above, POST /api/jobs accepts the same body as /api/screenshot but returns 202 immediately with a job ID. Screenshotly runs the capture, retries it on failure and keeps the result for your account's retention period. Send an Idempotency-Key so a retried submit returns the original job rather than creating a second one:
require 'faraday'
require 'json'
api = Faraday.new(url: 'https://screenshotly.app',
headers: { 'x-api-key' => ENV.fetch('SCREENSHOTLY_API_KEY') },
request: { timeout: 20 }) do |f|
f.request :json
f.response :json
f.response :raise_error
end
# 1. Queue the capture. Retrying with the same Idempotency-Key returns the original job.
queued = api.post('/api/jobs', { url: 'https://example.com/invoices/4821', format: 'pdf' },
{ 'Idempotency-Key' => 'invoice-4821' }).body
# 2. Poll until the job reaches a final state.
deadline = Time.now + 300
job = queued
while %w[QUEUED RUNNING].include?(job['status']) && Time.now < deadline
sleep 2
job = api.get(queued['statusUrl']).body
end
raise "Job #{job['id']} ended as #{job['status']}" unless job['status'] == 'SUCCEEDED'
# 3. resultUrl is a short-lived signed link: download it now, without the API key.
File.binwrite('invoice-4821.pdf', Faraday.get(job['resultUrl']).body)
puts 'Saved invoice-4821.pdf'
Job states are QUEUED, RUNNING, SUCCEEDED, FAILED and CANCELED. The resultUrl signature expires quickly, so download it straight away or read the job again for a fresh link. Growth and Scale accounts can submit up to 20 captures in one call to POST /api/jobs/batch with a { captures: [...] } body. See the async jobs reference.
In a Rails app, run the polling loop inside a job too, or skip polling and use a webhook.
Webhooks: verify the signature
Add webhook: { url: 'https://yourapp.com/webhooks/screenshotly', secret: '...' } to a capture (Basic+), and Screenshotly POSTs a JSON event when it finishes, retrying delivery up to five times. With a secret set, the request carries X-Screenshotly-Signature: sha256=<hex>, an HMAC-SHA256 of the raw body. Compare it in constant time:
# app/controllers/webhooks/screenshotly_controller.rb
class Webhooks::ScreenshotlyController < ActionController::API
def create
secret = Rails.application.credentials.dig(:screenshotly, :webhook_secret)
expected = "sha256=#{OpenSSL::HMAC.hexdigest('SHA256', secret, request.raw_post)}"
provided = request.headers['X-Screenshotly-Signature'].to_s
return head :unauthorized unless ActiveSupport::SecurityUtils.secure_compare(expected, provided)
event = JSON.parse(request.raw_post)
if event['event'] == 'screenshot.completed'
# event['data'] has url, format, size, duration and, if you asked for
# storage, a signed storageUrl.
Rails.logger.info("Screenshot ready for #{event.dig('data', 'url')}")
end
head :no_content
end
end
Outside Rails, Rack::Utils.secure_compare or OpenSSL.fixed_length_secure_compare (after checking the lengths match) do the same job.
Testing with WebMock
Stub the endpoint so your specs never call the real API:
# spec/clients/screenshotly_client_spec.rb
require 'webmock/rspec'
RSpec.describe ScreenshotlyClient do
let(:client) { described_class.new(api_key: 'test-key') }
let(:endpoint) { 'https://screenshotly.app/api/screenshot' }
it 'sends the key and returns the image bytes' do
stub_request(:post, endpoint)
.with(headers: { 'x-api-key' => 'test-key' }, body: { url: 'https://example.com', format: 'png' }.to_json)
.to_return(status: 200, body: "\x89PNG", headers: { 'Content-Type' => 'image/png' })
expect(client.capture('https://example.com')).to eq("\x89PNG")
end
it 'raises RateLimited without retrying when the quota is exhausted' do
stub_request(:post, endpoint).to_return(
status: 429,
body: { error: 'Rate limit exceeded', message: 'Limit resets at 2026-12-01T00:00:00.000Z' }.to_json,
headers: { 'Retry-After' => '1500000' }
)
expect { client.capture('https://example.com') }
.to raise_error(ScreenshotlyClient::RateLimited) { |e| expect(e.retry_after).to eq(1_500_000) }
expect(a_request(:post, endpoint)).to have_been_made.once
end
it 'raises ClientError for a plan-gated option' do
stub_request(:post, endpoint).to_return(
status: 403,
body: { error: 'Plan upgrade required', message: 'PDF output requires the basic plan or higher', minimumPlan: 'basic' }.to_json
)
expect { client.capture('https://example.com', format: 'pdf') }.to raise_error(ScreenshotlyClient::ClientError, /basic plan/)
end
end
Error reference
| Status | Meaning | Ruby handling |
|---|---|---|
| 400 | Invalid JSON, unknown key, out-of-range value, or a URL that is not public | ClientError; fix the request |
| 401 | Missing or invalid API key | ClientError; check credentials |
| 403 | Feature needs a higher plan (minimumPlan in the body) |
ClientError; remove the option or upgrade |
| 413 | Request body over 64 KB | ClientError; trim javascript, headers or cookies |
| 429 | Per-minute limit (short Retry-After) or quota used up (long Retry-After) |
Retry after a short wait; fail on a long one |
| 500 | The page could not be captured | ServerError; retry with backoff |
| 503 | The regional capture proxy is unavailable | ServerError; retry later |
Checklist before production
- The key lives in Rails credentials or the environment, never in code.
- Captures run in background jobs, with a 60-second HTTP read timeout.
- 429 handling checks how long
Retry-Afteris before waiting. - Client errors are discarded or killed, not retried.
- Queue concurrency stays under your plan's per-minute limit.
- Slow pages and PDFs go through
/api/jobs(Basic+). - Webhook endpoints verify
X-Screenshotly-Signaturein constant time.
Ready to add screenshots to your Ruby app?
Get your free API key →. The Free plan includes 100 captures.
See also:
About the Author

Asad Ali
CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.
Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients
Frequently Asked Questions
Should I use Net::HTTP or Faraday in Ruby?
Net::HTTP is in the standard library and is fine for scripts and rake tasks. For application code, Faraday 2 with the faraday-retry middleware gives you retries that honour Retry-After, configurable timeouts and easy stubbing in tests.
Where should the capture run in a Rails app?
In a background job (Active Job on Sidekiq, GoodJob or Solid Queue), never in a controller. A capture can take tens of seconds on a slow page, and a Puma thread waiting on it is not serving requests. The controller enqueues the job; the job captures and attaches the file with Active Storage.
How do I handle rate limits in Sidekiq?
Raise a dedicated error that carries the Retry-After value and use sidekiq_retry_in to return that delay. Return :kill when Retry-After is very long, because that means the plan's capture quota is used up and retrying will not help until it resets.
Does Screenshotly have an official Ruby gem?
No. Use any HTTP client; the API is a single JSON POST. The examples here use Net::HTTP and Faraday.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.