McAPI - Screenshot API Ruby

Ruby sample code and snippets to capture website screenshots with the McAPI Screenshot REST API service. The sample uses Ruby 2.6 but the code will also work with Ruby 3. The samples use the packages uri, net/http and openssl which should all be available with a standard Ruby installation. If not, simply install them using GEM.

Requirements: A free RapidAPI account. Replace YOUR_API_KEY in the snippets below with your RapidAPI key.

All samples below work with the free tier of the API, see RapidAPI McAPI Screenshot Listing for available plans.

See the overview page for a reference that lists all available parameters and error codes.

Take a screenshot using Ruby

In the first Ruby sample, we take a screenshot of the Indiehackers website. The device is set to Default (=1024x768px). With the storeExternal option set to "false", the screenshot will be returned as a base64 encoded JPEG. See snippet at end of page on how to write base64 encoded images to file with Ruby.

The source code:

# Ruby

require 'uri'
require 'net/http'
require 'openssl'

url = URI("https://mcapi-screenshot.p.rapidapi.com/")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/json'
request["x-rapidapi-key"] = 'YOUR_API_KEY'
request["x-rapidapi-host"] = 'mcapi-screenshot.p.rapidapi.com'
request.body = "{
  \"url\": \"https://indiehackers.com\",
  \"format\": \"jpeg\",
  \"storeExternal\": \"false\",
  \"devices\": [ \"Default\" ]
}"

response = http.request(request)

The response will be delivered as a JSON object in response.read_body, e.g.:

{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "url": "https://indiehackers.com",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "data:image/jpeg;base64,/9j/4AAQSkZJRgAB ... 9yXvZG0pSuhyP/9k="
    }
  ]
}

McAPI Screenshot API - Sample screenshot with Ruby

The returned image from the Ruby request:

Image of McAPI Screenshot API Sample Screenshot Ruby

Specifying devices

The Screenshot API contains a built-in database of over one hundred predefined devices and screen sizes. To get a list of all devices use the listDevices option, like so:

# Ruby
  
...

request.body = "{
  \"listDevices\": \"true\"
}"

...

The API will now return an array of all known devices:

{
  "devices": [

    ...
  
    { "name": "iPhone 12 mini", "width": 375, "height": 812 },
    { "name": "iPhone 12 mini landscape", "width": 812, "height": 375 },
    { "name": "iPhone 12", "width": 390, "height": 844 },
    { "name": "iPhone 12 landscape", "width": 844, "height": 390 },
    { "name": "iPhone 12 Pro", "width": 390, "height": 844 },
    { "name": "iPhone 12 Pro landscape", "width": 844, "height": 390 },
    { "name": "iPhone 12 Pro Max", "width": 428, "height": 926 },
    { "name": "iPhone 12 Pro Max landscape", "width": 926, "height": 428 },

    ...
  ]
}

Internally, the API also maintains proper User Agent-strings for all devices, those are not shown in the list.

Specifying a predefined device is simple, just use its name in the call:

# Ruby
  
...

request.body = "{
  \"url\": \"https://mcapi.io\",
  \"devices\": [ \"iPhone 12\" ]
}"

...

The devices param is an array; to create multiple screenshots at once, specify additional devices (the current limit is five):

# Ruby
  
...

request.body = "{
  \"url\": \"https://mcapi.io\",
  \"devices\": [ \"iPhone 12\", \"iPhone 12 landscape\" ]
}"

...

Note that specifying multiple devices will cause the API to load the target URL for each device and then take a screenshot; this can take some time with heavy sites and may cause your code (or the API) to timeout; see the discussion on timeouts.

Specifying viewports

If none of the predefined devices and screen sizes are suitable for your application, you can specify your own viewport:

# Ruby
  
...

request.body = "{
  \"url\": \"https://mcapi.io\",
  \"viewPort\": { \"width\": 800, \"height\": 600 }
}"

...

This will create a screenshot with 800x600px; if a viewport is specified, the API will use a generic desktop User agent-string when loading the target URL.

Note that the viewPort param is ignored if a devices array is also specified.

Taking a screenshot with Ruby - Clicking cookie warnings, block ads

If so desired, the API can also automatically click the "Accept", "Accept all" or a similarly worded button on GDPR / DSGVO cookie consent banners (Note that this feature is experimental for the API version V1.0, discussion.)

Consider this screenshot of CNBC.com with default API settings. This site presents a huge cookie warning to new visitors:

Screenshot API - Cookie Consent Banner Ruby

Set the cookie option to "true", like so:

# Ruby
  
...

request.body = "{
  \"url\": \"https://mcapi.io\",
  \"cookie\": \"true\",  
  \"devices\": [ \"Default\" ]
}"

...

We can now take a screenshot without the cookie warning removed:

Screenshot API - Clicked Cookie Banner and Ad with Ruby

Blocking ads in screenshots

While it can be useful to take screenshots with ads (for example to check ad rotation or placement), usually you will want to block them. The screenshot API comes with a built-in ad blocker, you activate it with Ruby like so:

# Ruby
  
...

request.body = "{
  \"url\": \"https://mcapi.io\",
  \"cookie\": \"true\", 
  \"adblock\": \"true\",  
  \"devices\": [ \"Default\" ]
}"

...

Screenshot of the CNBC site without cookie warning and without ads:

Screenshot API - Clicked Cookie Banner and Ad blocked Ruby

The header-parameter - taking screenshots with Ruby and write to a file

With the storeExternal option set to "false", the screenshot image is returned as a base64 encoded string. With default settings, this string will preceded by a MIME header that describes the media type of the encoded image.

Sample data block for a screenshot, to be returned as a PNG:

# Ruby

...

request.body = "{
  \"url\": \"https://mcapi.io\",
  \"storeExternal\": \"false\", 
  \"format\": \"png\"
}"

...

The result from this API call will look like this:

{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "url": "https://mcapi.io",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "data:image/png;base64,iVBORr/klmpqa2 ... 9yXvZG0pjjmSuhQmCC"
    }
  ]
}

After parsing the result with a JSON parser you can directly set the "screenshot"-string as the src property of an img tag, like so:

# Ruby

require json

...

if response.code == "200"
  # In production code you would wrap the parser in begin/rescue/end
  # and iterate over the screenshots array
  screenshot = JSON.parse(response.read_body)["screenshots"][0]["screenshot"]
  puts('<img src="' + screenshot + '"/>')
else
  puts("Error")
end

...

The MIME header will make sure that the image data is interpreted correctly by the browser. However, when writing the image data to a file, including the header would result in a corrupt file. To create a screenshot image without the header, set the header option to "false", like so:

# Ruby

...

request.body = "{
  \"url\": \"https://mcapi.io\",
  \"storeExternal\": \"false\", 
  \"header\": \"false\"
}"

...

We now get the screenshot without header string:

{
  "service": "McAPI Screenshot Generator, https://mcapi.io",
  "version": "V1",
  "format": "png",
  "url": "https://mcapi.io",
  "screenshots": [
    {
      "device": "Default",
      "screenshot": "iVBORr/klmpqa2 ... 9yXvZG0pjjmSuhQmCC"
    }
  ]
}

Now, all we have to do is decode the base64 string and then write the screenshot to a file, listed here as a complete Ruby example:

# Ruby

require 'uri'
require 'net/http'
require 'openssl'
require 'json'
require 'base64'

url = URI("https://mcapi-screenshot.p.rapidapi.com/")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/json'
request["x-rapidapi-key"] = 'YOUR_API_KEY'
request["x-rapidapi-host"] = 'mcapi-screenshot.p.rapidapi.com'
request.body = "{
  \"url\": \"https://indiehackers.com\",
  \"storeExternal\": \"false\", 
  \"format\": \"png\",
  \"header\": \"false\"   
}"

response = http.request(request)
if response.code == "200"
  # In production code you would wrap the parser in begin/rescue/end
  # and iterate over the screenshots array
  screenshot = JSON.parse(response.read_body)["screenshots"][0]["screenshot"]
  png = Base64.decode64(screenshot)
  File.open("screenshot.png", "wb") do |f|
    f.write(png)
  end
else
  puts("Error")
end

Back to McAPI Screenshot API main page.