Ruby
Official screenshotapi_to gem for Ruby — capture screenshots, PDFs, and rendered HTML from scripts and Rails with a zero-dependency client.
The official screenshotapi_to gem is a small net/http client with no runtime dependencies. It captures screenshots, PDFs, and rendered HTML and raises typed errors for API failures.
Gem: screenshotapi_to on RubyGems · Require: screenshotapi · Source & examples: github.com/miketromba/screenshotapi-ruby · Ruby 3.0+.
Installation
Add the gem to your Gemfile (note the require: so bundle loads the right file):
gem "screenshotapi_to", require: "screenshotapi"bundle installOr install it directly:
gem install screenshotapi_toAuthentication
Create an API key in the dashboard and keep it in an environment variable. The SDK sends it in the x-api-key header.
export SCREENSHOTAPI_KEY="sk_live_your_key_here"require "screenshotapi"
client = ScreenshotAPI::Client.new(ENV.fetch("SCREENSHOTAPI_KEY"))Keep API keys on the server. Never expose them in client-side code or commit them to source control.
Quick Start
Capture a URL and save it to disk
save captures the screenshot, writes the file, and returns the response metadata.
require "screenshotapi"
client = ScreenshotAPI::Client.new(ENV.fetch("SCREENSHOTAPI_KEY"))
metadata = client.save(url: "https://example.com", path: "screenshot.png")
puts "Screenshot ID: #{metadata.screenshot_id}"
puts "Credits remaining: #{metadata.credits_remaining}"Or work with the raw image bytes
screenshot returns a Result with the image bytes plus metadata.
result = client.screenshot(url: "https://example.com", type: "webp")
File.binwrite("screenshot.webp", result.image)
puts result.content_type # "image/webp"
puts result.metadata.duration_msMethods
ScreenshotAPI::Client.new(api_key, base_url:, timeout:)
| Parameter | Type | Default | Description |
|---|---|---|---|
api_key | String | — (required) | Your API key |
base_url | String | https://screenshotapi.to | API base URL (proxies, tests) |
timeout | Integer | 60 | Open and read timeout in seconds |
client.screenshot(**options)
Returns a ScreenshotAPI::Result:
result.image # String (binary) — raw image or PDF bytes
result.content_type # "image/png", "image/webp", "application/pdf", …
result.metadata.credits_remaining # Integer
result.metadata.screenshot_id # String — include this when contacting support
result.metadata.duration_ms # Integerclient.save(path:, **options)
Captures, writes the bytes to path:, and returns a ScreenshotAPI::Metadata (the metadata shape above).
Options
Pass any screenshot parameter as a snake_case keyword argument; the client converts them to API parameters for you.
| Option | Type | Default | Description |
|---|---|---|---|
url | String | Required unless html is set | URL to capture |
html | String | — | Raw HTML to render (switches to POST) |
width | Integer | 1440 | Viewport width in pixels (max 1920) |
height | Integer | 900 | Viewport height in pixels (max 10000) |
full_page | Boolean | false | Capture the full scrollable page |
type | String | "png" | "png", "jpeg", "webp", or "pdf" |
quality | Integer | 100 | JPEG/WebP quality, 1–100 |
color_scheme | String | Page default | "light" or "dark" |
wait_until | String | "networkidle2" | "load", "domcontentloaded", "networkidle0", "networkidle2" |
wait_for_selector | String | — | CSS selector to wait for |
delay | Integer | 0 | Extra wait after load (ms, max 30000) |
block_ads | Boolean | false | Block common ad networks |
remove_cookie_banners | Boolean | false | Auto-remove cookie consent dialogs |
css_inject | String | — | CSS injected before capture |
js_inject | String | — | JavaScript evaluated before capture |
stealth_mode | Boolean | false | Anti-bot-detection browser fingerprint |
device_pixel_ratio | Integer | 1 | Retina/HiDPI scale (1, 2, or 3) |
timezone | String | Server default | IANA timezone, e.g. "America/New_York" |
locale | String | Server default | BCP 47 locale, e.g. "en-US" |
cache_ttl | Integer | 0 | Cache identical captures for N seconds |
preload_fonts | Boolean | false | Preload Google Fonts before capture |
remove_elements | Array<String> | — | CSS selectors to remove |
remove_popups | Boolean | false | Remove common modals/overlays |
mockup_device | String | — | "browser", "iphone", or "macbook" (PNG output) |
geo_latitude, geo_longitude, geo_accuracy | Numeric | — | Geolocation override (GET requests) |
geo_location | Hash | — | Geolocation as { latitude:, longitude:, accuracy: } (HTML/POST requests) |
result = client.screenshot(
url: "https://example.com/pricing",
width: 1440,
height: 1200,
full_page: true,
type: "webp",
quality: 85,
color_scheme: "dark",
wait_until: "networkidle2",
wait_for_selector: "main",
delay: 500,
block_ads: true,
remove_cookie_banners: true,
device_pixel_ratio: 2,
cache_ttl: 300,
remove_elements: [".newsletter", "#cookie-banner"]
)
File.binwrite("pricing.webp", result.image)Render HTML & generate PDFs
Pass html: to render a raw string — the client uses POST /api/v1/screenshot with a JSON body. Combine with type: "pdf" for documents.
# Render HTML to PNG
result = client.screenshot(
html: "<main><h1>Hello from Ruby</h1></main>",
width: 800,
height: 600,
type: "png"
)
# Save a URL as a PDF
client.save(url: "https://example.com/report", type: "pdf", path: "report.pdf")Error Handling
The SDK raises typed errors. All inherit from ScreenshotAPI::APIError.
require "screenshotapi"
client = ScreenshotAPI::Client.new(ENV.fetch("SCREENSHOTAPI_KEY"))
begin
result = client.screenshot(url: "https://example.com")
File.binwrite("screenshot.png", result.image)
rescue ScreenshotAPI::AuthenticationError
warn "API key missing or malformed (401)"
rescue ScreenshotAPI::InvalidAPIKeyError
warn "API key revoked or invalid (403)"
rescue ScreenshotAPI::InsufficientCreditsError => e
warn "Out of credits (402). Balance: #{e.balance}"
rescue ScreenshotAPI::ScreenshotFailedError => e
warn "Capture failed server-side (500): #{e.message}"
rescue ScreenshotAPI::NetworkError => e
warn "Network error: #{e.message}"
rescue ScreenshotAPI::APIError => e
warn "ScreenshotAPI error #{e.status}: #{e.message}"
end| Error | When |
|---|---|
AuthenticationError | 401 — API key missing or malformed |
InsufficientCreditsError | 402 — no credits remaining (exposes #balance) |
InvalidAPIKeyError | 403 — API key revoked or invalid |
ScreenshotFailedError | 500 — capture failed server-side |
NetworkError | Connection failure or timeout |
APIError | Base class (exposes #status) |
Framework Recipes
Rails Controller
Stream the screenshot back to the browser and map SDK errors to HTTP responses.
class ScreenshotsController < ApplicationController
def show
url = params.require(:url)
result = client.screenshot(url: url, type: "webp", quality: 80)
response.headers["Cache-Control"] = "public, max-age=3600"
send_data result.image, type: result.content_type, disposition: "inline"
rescue ScreenshotAPI::InsufficientCreditsError
render json: { error: "Out of screenshot credits" }, status: :payment_required
rescue ScreenshotAPI::APIError => e
render json: { error: e.message }, status: :bad_gateway
end
private
def client
@client ||= ScreenshotAPI::Client.new(ENV.fetch("SCREENSHOTAPI_KEY"))
end
endRunnable examples ship with the gem: plain_ruby.rb and rails_controller.rb.
Next steps
- Screenshot API reference — every parameter in detail
- Authentication — create and rotate API keys
- Credits — how billing works (200 free screenshots/month)
- Integrations — framework and platform guides