# ApiFlash screenshot API documentation ApiFlash is a screenshot API built on an up to date version of Chrome running on AWS Lambda. It captures pixel perfect screenshots of any website at scale. ## Access The API is accessed through a single HTTPS endpoint supporting both GET and POST: - `GET https://api.apiflash.com/v1/urltoimage`: parameters are passed in the query string. - `POST https://api.apiflash.com/v1/urltoimage`: parameters are passed as form data. Every API call must be authenticated with a valid access key passed in the `access_key` parameter, like every other parameter. Access keys are managed from the [dashboard](https://apiflash.com/dashboard/access_keys). ``` GET https://api.apiflash.com/v1/urltoimage?access_key=YOUR_ACCESS_KEY&url=https%3A%2F%2Fexample.com ``` By default the API directly returns the screenshot image data with the appropriate `Content-Type` and `Content-Length` headers. If the `response_type` parameter is set to `json`, the response is a JSON document with links to the resulting screenshot. ## Parameters Parameter values must be URL encoded to be processed correctly. Boolean parameters accept `true` or `false`. ### `access_key` (required) A valid access key allowing you to make API calls. Access keys can be managed from your [dashboard](https://apiflash.com/dashboard/access_keys). ### `url` (required) The complete URL of the website for which you want to capture a screenshot. It should be URL encoded and must include the protocol (`http://` or `https://`) to be processed correctly. ### `format` The image format of the captured screenshot. Either `jpeg`, `png` or `webp`. The `webp` format is limited to 16350 pixels in width and in height, once the `scale_factor` is applied. Default: `jpeg` ### `width` The width, in pixels, of the viewport to use. From 0 to 16350 pixels, provided that `width` multiplied by `height` does not exceed 33177600 pixels. Default: `1920` ### `height` The height, in pixels, of the viewport to use. This is ignored if `full_page` is `true`. From 0 to 16350 pixels, provided that `width` multiplied by `height` does not exceed 33177600 pixels. Default: `1080` ### `fresh` Force the API to capture a fresh new screenshot instead of returning a screenshot from the cache. Default: `false` ### `full_page` Set this parameter to `true` to capture the entire page of the target website. Default: `false` ### `quality` The quality of the image between `0` and `100`. This works with the `jpeg` and `webp` formats. Default: `90` ### `delay` When possible, consider using the `wait_for` or the `wait_until` parameter instead as they provide more reliable ways to ensure the page is properly rendered before capture. The delay, in seconds, to wait after the page is loaded before capturing the screenshot. From 0 seconds to a maximum of 10 seconds. Default: `0` ### `scroll_page` Set this parameter to `true` to scroll through the entire page before capturing a screenshot. This is useful to trigger animations or lazy loaded elements. Default: `false` ### `ttl` Number of seconds the screenshot is cached. API calls with the same parameters do return a cached screenshot and don't count in your monthly quota. From 0 seconds to 2592000 seconds (30 days). Default: `86400` ### `response_type` The type of response to return. Can be either `image` or `json`. - If the response type is `image`, the binary data of the screenshot is returned with the appropriate `Content-Type` and `Content-Length` headers. - If the response type is `json`, the response is a json document formatted as follows: ``` { "url": "https://url_of_screenshot...", "extracted_html": "https://url_of_html_file...", "extracted_text": "https://url_of_text_file..." } ``` Default: `image` ### `thumbnail_width` The width, in pixels, of the thumbnail to generate. The aspect ratio will be preserved. This is ignored if `full_page` is `true`. ### `crop` Capture a screenshot of an area of the page. The area to capture is defined by a string of the form `left,top,width,height`. For example, the value `10,20,50,100` captures an area 50 pixels wide and 100 pixels high, with a 10 pixel offset from the left edge and a 20 pixel offset from the top edge. ### `no_cookie_banners` Prevent cookie banners and popups from being displayed. Default: `false` ### `no_ads` Prevent ads from being displayed. Block requests from popular ad-networks and hide common ad spaces. Default: `false` ### `no_tracking` Prevent tracking scripts to run and block requests from popular tracking services. Use this to prevent page views to be incorrectly reported to tracking tools when screenshots are captured. Default: `false` ### `scale_factor` Specifies the device scale factor to use when capturing the screenshot. Acceptable values are `1` (standard resolution) and `2` (high definition for retina displays). A scale factor of `2` produces a high-definition screenshot but results in a heavier file size. Default: `1` ### `element` Capture a screenshot of the first element matched by the given CSS selector. This is ignored if `full_page` is `true`. The CSS selector should be URL encoded to be processed correctly. ### `element_overlap` Also capture the elements that overlap the element targeted by the `element` parameter. Default: `false` ### `user_agent` Sets the `User-Agent` header to emulate a particular device when making screenshots. It should be URL encoded to be processed correctly. ### `extract_html` Extract the HTML of the page at the same time the screenshot is made. This only works when the `response_type` parameter is set to `json`. When this parameter is set to `true`, an `extracted_html` attribute is added to the returned json document. Default: `false` ### `extract_text` Extract the text of the page at the same time the screenshot is made. This only works when the `response_type` parameter is set to `json`. When this parameter is set to `true`, an `extracted_text` attribute is added to the returned json document. Default: `false` ### `transparent` Capture a screenshot with transparency enabled. The background color of the page's body should be set to `transparent` for this to work. This only works with the `png` format. Default: `false` ### `wait_for` Wait until the provided CSS selector matches an element present in the page before capturing a screenshot. If no item matches after waiting 15 seconds, screenshot capture is aborted with an error. ### `wait_until` Wait until the given criterion is satisfied to consider that the page has finished loading. The possible criteria are: - `dom_loaded` to wait until the initial HTML document has been completely loaded, without waiting for stylesheets and images to finish loading. - `page_loaded` to wait until the whole page has loaded, including all dependent resources such as stylesheets and images. - `network_idle` to wait until the whole page has loaded and the network is idle (no more active network connection). Default: `network_idle` ### `wait_until_timeout` The maximum time, in seconds, to wait for the `wait_until` criterion to be satisfied. If the criterion is not satisfied within this time, the screenshot is captured anyway with whatever has been loaded so far. From 1 second to a maximum of 30 seconds. Default: `30` ### `fail_on_status` A comma separated list of HTTP status codes that should make the API call fail instead of returning a screenshot. Hyphen separated HTTP status codes can be used to define ranges. For example `400,404,500-511` would make the API call fail if the URL returns 400, 404 or any status code between 500 and 511. ### `accept_language` Sets the `Accept-Language` header on requests to the target URL allowing you to make screenshots of a website with a specific language. ### `css` A CSS string to inject in the web page when capturing the screenshot. This CSS string needs to be URL encoded to be processed correctly. ### `cookies` A semicolon separated list of cookies to be used when capturing the screenshot. Each cookie should be supplied as a name value pair and multiple pairs should be separated by a semicolon. The `cookies` parameter value should be URL encoded to be processed correctly. For example, `cookie1=value1;cookie2=value2` would have to be URL encoded into `cookie1%3Dvalue1%3Bcookie2%3Dvalue2`. ### `proxy` The address of a proxy server through which the screenshot should be captured. The proxy address should be formatted as `address:port` or `user:password@address:port` if authentication is needed. ### `latitude` The latitude to use when emulating geo-location between `-90` and `90`. ### `longitude` The longitude to use when emulating geo-location between `-180` and `180`. ### `accuracy` The accuracy value, in meters, to use when emulating geo-location. Default: `0` ### `js` Additional JavaScript code to be injected into the page before capturing. The JS string needs to be URL encoded to be processed correctly. ### `headers` A semicolon separated list of headers to be used when capturing the screenshot. Each header should be supplied as a key value pair and multiple pairs should be separated by a semicolon. The `headers` parameter value should be URL encoded to be processed correctly. For example, `Header1=value1;Header2=value2` would have to be URL encoded into `Header1%3Dvalue1%3BHeader2%3Dvalue2`. ### `time_zone` The time zone to use when capturing screenshots. This parameter accepts standard time zome database names. For example, `Europe/Paris` or `America/New_York`. It should be URL encoded to be processed correctly. ### `ip_location` An ISO alpha-2 country code designating the country that should be associated with the IP address of the proxy through which the screenshot is captured. This feature is only available for custom enterprise plans. Get in touch with us if you need it. ### `s3_access_key_id` The AWS access key id to use to upload the screenshot to AWS S3. ### `s3_secret_key` The AWS secret access key to use to upload the screenshot to AWS S3. ### `s3_bucket` The name of the S3 bucket to upload the screenshot to. If you only use the screenshot uploaded to AWS S3 and don't use the screenshot returned in the HTTP response body, you might want to set the `response_type` to `json` to avoid unnecessary data transfer. ### `s3_key` The object key to use when uploading the screenshot. ### `s3_endpoint` If you want to use a custom S3 compatible storage provider, you can specify the endpoint URL here. Leave this field empty to use AWS S3. ### `s3_region` The AWS region to use to upload the screenshot to AWS S3. You might need to set this if you use a custom S3 compatible storage provider. ## Examples The following examples make an HTTP request to the API and save the screenshot to a `screenshot.jpeg` file. ### c# ```cs using System.Net; public class ApiFlashExample { private const string ApiFlashEndpoint = "https://api.apiflash.com/v1/urltoimage"; public static void Main () { using(var webClient = new WebClient()) { // The System.Web assembly reference is required. var parameters = System.Web.HttpUtility.ParseQueryString(string.Empty); parameters["access_key"] = "YOUR_ACCESS_KEY"; parameters["url"] = "https://example.com"; webClient.DownloadFile(ApiFlashEndpoint + "?" + parameters, "screenshot.jpeg"); } } } ``` ### curl ```bash endpoint="https://api.apiflash.com/v1/urltoimage" access_key="YOUR_ACCESS_KEY" url="https://example.com" curl --request GET --url "${endpoint}?access_key=${access_key}&url=${url}" > screenshot.jpeg ``` ### go ```go package main import ( "io" "net/http" "os" ) func main() { apiFlashEndpoint := "https://api.apiflash.com/v1/urltoimage" request, _ := http.NewRequest("GET", apiFlashEndpoint, nil) query := request.URL.Query() query.Add("access_key", "YOUR_ACCESS_KEY") query.Add("url", "https://example.com") request.URL.RawQuery = query.Encode() client := &http.Client{} response, _ := client.Do(request) defer response.Body.Close() image, _ := os.Create("screenshot.jpeg") io.Copy(image, response.Body) image.Close() } ``` ### java ```java import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; public class Main { private static String ACCESS_KEY = "YOUR_ACCESS_KEY"; private static String APIFLASH_ENDPOINT = "https://api.apiflash.com/v1/urltoimage"; public static void main(String[] args) throws Exception { String params = String.format("?access_key=%s&url=https://example.com", ACCESS_KEY); URL apiCallUrl = new URL(APIFLASH_ENDPOINT + params); InputStream inputStream = apiCallUrl.openStream(); OutputStream outputStream = new FileOutputStream("screenshot.jpeg"); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) != -1) { outputStream.write(b, 0, length); } inputStream.close(); outputStream.close(); } } ``` ### node ```javascript const https = require('https'); const fs = require('fs'); https.get("https://api.apiflash.com/v1/urltoimage?" + new URLSearchParams({ access_key: "YOUR_ACCESS_KEY", url: "https://example.com" }).toString(), (response) => { response.pipe(fs.createWriteStream('screenshot.jpeg')); }); ``` ### php ```php "YOUR_ACCESS_KEY", "url" => "https://example.com", )); $image_data = file_get_contents("https://api.apiflash.com/v1/urltoimage?" . $params); file_put_contents("screenshot.jpeg", $image_data); ?> ``` ### python ```python from urllib.parse import urlencode from urllib.request import urlretrieve params = urlencode(dict(access_key="YOUR_ACCESS_KEY", url="https://example.com")) urlretrieve("https://api.apiflash.com/v1/urltoimage?" + params, "screenshot.jpeg") ``` ### ruby ```ruby require "open-uri" File.open('screenshot.jpeg', 'wb') do |fo| params = URI.encode_www_form("access_key" => "YOUR_ACCESS_KEY", "url" => "https://example.com") fo.write open("https://api.apiflash.com/v1/urltoimage?" + params).read end ``` ## Rate limits The API is rate limited using the leaky bucket algorithm with a request rate of 20 requests per second and a burst size of 400 requests. Requests exceeding 20 requests per second are delayed so they are processed at that rate. Once more than 400 requests are delayed, additional requests are rejected with a `429` status code. API calls with the exact same parameters (same url, same width, etc.) that fail to capture a screenshot (unreachable website, unregistered domain, etc.) are rate limited to 5 requests per hour. ## Quota Responses of API calls that successfully captured a screenshot include the following headers. On responses served from the cache, they may reflect the quota at the time the screenshot was captured. | Header | Description | | --- | --- | | `X-Quota-Limit` | The maximum number of API calls you can make per billing period. | | `X-Quota-Remaining` | The number of API calls remaining for the current billing period. | | `X-Quota-Reset` | The time, in UTC epoch seconds, at which the current billing period ends and the remaining number of API calls resets. | For an up to date value, call the quota endpoint: ``` GET https://api.apiflash.com/v1/urltoimage/quota?access_key=YOUR_ACCESS_KEY ``` It returns a JSON document: ```json { "limit": 10000, "remaining": 5400, "reset": 1584549777 } ``` ## Errors When the API fails to capture a web page, the response has one of these status codes: | Status code | Description | | --- | --- | | `400` Bad Request | Either the API call contains invalid parameters or the target URL cannot be captured. | | `401` Unauthorized | The access key used to make this API call has been revoked or is invalid. | | `402` Payment Required | The monthly screenshot quota has been exceeded for the user's current plan. | | `403` Forbidden | The current plan does not support some of the features requested through API parameters. | | `429` Too Many Requests | Too many API calls have been made. The specific reason is included in the response body. | | `500` Internal Server Error | The screenshot capture failed because the API failed to handle the encountered situation. | A `400` response includes a meaningful error message explaining the root cause. If the `response_type` parameter is set to `json`, an error type and additional information may also be returned depending on the error. # Add content over screenshots Last updated february 09, 2024 With the `js` parameter, you can inject javascript into the page before screenshot capture. To add content over a screenshot, you can simply use it to inject some code that adds the HTML content you want to display. Don't forget to **URL encode** the javascript code before passing it to the `js` parameter. Pick one of the following examples, adjust it to your needs and simply pass it to the `js` parameter. ## Example 1 • Add a white watermark at the top left of the page ```js const watermark = document.createElement('div'); watermark.style.all = 'initial'; // Prevent the website style from affecting the watermark. watermark.style.position = 'fixed'; watermark.style.top = '50px'; watermark.style.left = '50px'; watermark.style.color = 'white'; watermark.style.fontSize = '100px'; watermark.style.textShadow = 'black 0 0 5px'; watermark.style.zIndex = '9999'; watermark.innerHTML = 'Some Watermark'; document.body.appendChild(watermark); ``` ## Example 2 • Add the date and time of screenshot capture ```js const dateContainer = document.createElement('div'); dateContainer.style.all = 'initial'; // Prevent the website style from affecting the date. dateContainer.style.position = 'fixed'; dateContainer.style.top = '10px'; dateContainer.style.left = '10px'; dateContainer.style.color = 'black'; dateContainer.style.fontSize = '20px'; dateContainer.style.zIndex = '9999'; dateContainer.innerHTML = new Date().toLocaleString('fr-FR', {timeZone: 'Europe/Paris'}); document.body.appendChild(dateContainer); ``` ## Example 3 • Add a logo at the center of the page ```js const logoContainer = document.createElement('div'); logoContainer.style.all = 'initial'; // Prevent the website style from affecting the logo. logoContainer.style.position = 'fixed'; logoContainer.style.top = '50%'; logoContainer.style.left = '50%'; logoContainer.style.transform = 'translate(-50%, -50%)'; logoContainer.style.zIndex = '9999'; logoContainer.innerHTML = ''; document.body.appendChild(logoContainer); ``` # Capture screenshots with a Cloudflare worker Last updated february 08, 2023 If you don't want to use your backend to make API calls, or if you plan to use screenshots URLs directly in `img` tags, using a Cloudflare worker to proxy ApiFlash might be a good solution. In particular, this is useful for hiding your access key and leveraging Cloudflare's fast network delivery and caching capabilities. To create a Cloudflare account, go to [cloudflare.com](https://www.cloudflare.com/) and sign up. From your dashboard, go to the **workers** section and create a new service. Give it a name, and choose any starter (it doesn't matter which one you choose). Then edit the worker with the following code. (don't forget to put your access key in the following code). ```javascript export default { async fetch(request) { let queryString = new URL(request.url).search; // Get the query string from the request URL. queryString += "&access_key=YOUR_ACCESS_KEY_HERE" // Add your access key to the query string. return fetch("https://api.apiflash.com/v1/urltoimage" + queryString, { cf: { // Cloudflare-specific properties. cacheTtl: 86400, // Cache screenshots for 24 hours. cacheEverything: true // Caches all file types beyond the Cloudflare default cached content. } }) }, }; ``` Your Cloudflare worker is now proxying our screenshot API. All query string parameters are passed directly to ApiFlash, except for the `access_key` parameter, which is added by the worker. You can now make API calls to ApiFlash through your worker (replace your worker name and subdomain). ```html https://your-cf-worker-name.your-cf-subdomain.workers.dev/?url=https://example.com&wait_until=page_loaded ``` If you want to restrict the type of screenshots that can be made through your worker, you can add the needed checks. For example here is how you can restrict the target `url`. ```javascript export default { async fetch(request) { let queryString = new URL(request.url).search; // Get the query string from the request URL. if (!new URLSearchParams(queryString).get("url").startsWith('https://target-domain.com')) { // Return a 403 response if the target URL does not start with https://target-domain.com return new Response('Forbidden URL', {status: 403}); } queryString += "&access_key=YOUR_ACCESS_KEY_HERE" // Add your access key to the query string. return fetch("https://api.apiflash.com/v1/urltoimage" + queryString, { cf: { // Cloudflare-specific properties. cacheTtl: 86400, // Cache screenshots for 24 hours. cacheEverything: true // Caches all file types beyond the Cloudflare default cached content. } }) }, }; ``` # Capture screenshots through Nginx Last updated december 01, 2022 This guide walks you through a simple and secure setup to capture screenshots through nginx. This guide is particularly useful if you want to: - include screenshot URLs directly in `img` tags - serve screenshots from your own domain - hide your access key from end users ## 1. Proxy ApiFlash & hide your access key Add this `location` block to your nginx configuration (don't forget to replace your access key). ```nginx location /screenshot { set $args $args&access_key=YOUR_ACCESS_KEY_HERE proxy_pass https://api.apiflash.com/v1/urltoimage; } ``` This block is proxying each `/screenshot` request to ApiFlash's screenshot API endpoint. Using the `set` directive, your access key is directly added by nginx to the query string parameters. As a result your end users cannot get your access key. Screenshots are served from your own domain and you can directly include screenshot URLs into `img` tags. ```html ``` Even though this setup is useful already, an end user could use your `/screenshot` endpoint to capture arbitrary screenshots. ## 2. Restrict the URLs that can be captured Another layer of security can be added with an `if` block to restrict the allowed target URLs. ```nginx location /screenshot { if ( $arg_url !~* https:\/\/somedomain.com ){ return 403; } set $args $args&access_key=YOUR_ACCESS_KEY_HERE proxy_pass https://api.apiflash.com/v1/urltoimage; } ``` This `if` block ensures nginx returns an `HTTP 403 Forbidden` error when URLs don't match the specified regular expression. In particular, in the previous example, only URLs that begin with `https://somedomain.com` can be captured as screenshots. End users cannot capture arbitrary screenshots with this setup. But they can still make a lot of HTTP requests to your `/screenshot` endpoint and potentially consume your subscription quota as a result. ## 3. Rate limiting your screenshot endpoint Rate limiting your endpoint is a good way to ensure that end users cannot aggressively call the `/screenshot` endpoint. Depending on your use case and the volume you're expecting, you might want to adjust the rate limit and the burst size. ```nginx limit_req_zone $binary_remote_addr zone=rate_limit:50m rate=1r/s; server { # The rest of your server configuration... location /screenshot { limit_req zone=rate_limit burst=10; if ( $arg_url !~* https:\/\/google.com ){ return 403; } set $args $args&access_key=YOUR_ACCESS_KEY_HERE; proxy_pass https://api.apiflash.com/v1/urltoimage; } } ``` In the previous example, requests are rate limited based on IP address and are limited to 1 request per second. With a burst size of 10, up to 10 requests can be queued per IP address without being dropped by nginx. ## 4. Public pages & screenshot caching On public pages with high traffic, if you use the `/screenshot` endpoint directly in `img` tags, this will result in a lot of unnecessary requests to ApiFlash. To ensure that ApiFlash's rate limit is not exceeded, you need to configure nginx to cache the generated screenshots. ```nginx proxy_cache_path /screenshot_cache levels=1:2 keys_zone=screenshot_cache:10m max_size=2g inactive=86400s use_temp_path=off; limit_req_zone $binary_remote_addr zone=rate_limit:50m rate=1r/s; server { # The rest of your server configuration... location /screenshot { limit_req zone=rate_limit burst=10; if ( $arg_url !~* https:\/\/google.com ){ return 403; } set $args $args&access_key=YOUR_ACCESS_KEY_HERE; proxy_pass https://api.apiflash.com/v1/urltoimage; proxy_cache screenshot_cache; proxy_cache_lock on; proxy_cache_key $request_uri$request_body; proxy_cache_bypass $arg_fresh; proxy_ignore_headers Vary Set-Cookie; } } ``` The previous configuration is caching up to 2GB of screenshots for 24 hours in the `/screenshot_cache` directory. Various nginx proxy directives are used to fine tune the caching behavior. More information about those directives can be found in the [nginx documentation](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache). # Capture screenshots in parallel Last updated january 25, 2023 ApiFlash can capture multiple screenshots in parallel. Our screenshot API is rate limited based on the number of requests per second and there is no limit on the number of concurrent requests. This means that you can make as many requests as you want in parallel as long as you don't exceed [our requests rate limit](https://apiflash.com/documentation#rate_limits). Here are some examples of how to make concurrent requests to our API with various languages. C#: ```csharp using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; public class ApiFlashExample { private const string ApiFlashEndpoint = "https://api.apiflash.com/v1/urltoimage"; private const string AccessKey = "YOUR_ACCESS_KEY_HERE"; public static void capture(string url){ var client = new HttpClient(); var parameters = new Dictionary{ {"access_key", AccessKey}, {"url", url}}; Console.WriteLine("Capturing " + url + " ..."); var encodedParameters = new FormUrlEncodedContent(parameters).ReadAsStringAsync().Result; var response = client.GetAsync(ApiFlashEndpoint + "?" + encodedParameters).Result; var filename = url.Replace("https://", "") + ".jpeg"; var file = System.IO.File.Create(filename); response.Content.CopyToAsync(file).Wait(); file.Close(); Console.WriteLine("Screenshot of " + url + " captured."); } public static void Main(string[] args) { var urls = new List{ "https://example.com", "https://google.com", "https://twitter.com"}; var tasks = new List(); foreach (var url in urls) { tasks.Add(Task.Run(() => capture(url))); } Task.WaitAll(tasks.ToArray()); } } ``` Go: ```go package main import ( "fmt" "io/ioutil" "net/http" "os" "strings" "sync" ) const accessKey = "YOUR_ACCESS_KEY_HERE" func capture(url string, wg *sync.WaitGroup, imageCh chan []byte) { defer wg.Done() request, _ := http.NewRequest("GET", "https://api.apiflash.com/v1/urltoimage", nil) query := request.URL.Query() query.Add("access_key", accessKey) query.Add("url", url) request.URL.RawQuery = query.Encode() fmt.Printf("Capturing %s ...\n", url) client := &http.Client{} resp, err := client.Do(request) defer resp.Body.Close() if err != nil { fmt.Printf("Failed to capture screenshot of %s: %s\n", url, err) return } if resp.StatusCode != 200 { fmt.Printf("Failed to capture screenshot of %s: %s\n", url, resp.Status) return } fmt.Printf("Screenshot of %s captured.\n", url) image, _ := ioutil.ReadAll(resp.Body) imageCh <- image } func main() { var wg sync.WaitGroup urlsToCapture := []string{ "https://example.com", "https://google.com", "https://twitter.com", } imageCh := make(chan []byte, len(urlsToCapture)) for _, url := range urlsToCapture { wg.Add(1) go capture(url, &wg, imageCh) } wg.Wait() for i := 0; i < len(urlsToCapture); i++ { image := <-imageCh filename := strings.ReplaceAll(urlsToCapture[i], "https://", "") + ".jpeg" f, err := os.Create(filename) if err != nil { fmt.Printf("Failed to create file %s: %s\n", filename, err) continue } defer f.Close() f.Write(image) } } ``` Java: ```java import java.io.FileOutputStream; import java.net.URL; import java.net.URLEncoder; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.file.Paths; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; class Main { private static final String ACCESS_KEY = "YOUR_ACCESS_KEY_HERE"; private static final String APIFLASH_ENDPOINT = "https://api.apiflash.com/v1/urltoimage"; public static void capture(String url) throws Exception { String params = String.format("?access_key=%s&url=%s", ACCESS_KEY, url); URL apiUrl = new URL(APIFLASH_ENDPOINT + params); System.out.println(String.format("Capturing %s ...", url)); ReadableByteChannel channel = Channels.newChannel(apiUrl.openStream()); String fileName = url.replace("https://", "") + ".jpeg"; FileOutputStream stream = new FileOutputStream(fileName); stream.getChannel().transferFrom(channel, 0, Long.MAX_VALUE); stream.close(); System.out.println(String.format("Screenshot of %s captured", url)); } public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); String[] urlsToCapture = {"https://example.com", "https://google.com", "https://twitter.com"}; Future[] futures = new Future[urlsToCapture.length]; for (int i = 0; i < urlsToCapture.length; i++) { String url = urlsToCapture[i]; futures[i] = executor.submit(() -> { try { capture(url); } catch (Exception e) { System.out.println(url + " generated an exception: " + e.getMessage()); } }); } executor.shutdown(); } } ``` Node.js: ```javascript const https = require('https'); const fs = require('fs'); const access_key = 'YOUR_ACCESS_KEY_HERE'; async function capture(url) { const params = new URLSearchParams({access_key: access_key, url: url}).toString(); console.log(`Capturing ${url} ...`); return new Promise((resolve, reject) => { https.get(`https://api.apiflash.com/v1/urltoimage?${params}`, (response) => { if (response.statusCode !== 200) { reject(`Failed to capture screenshot of ${url}: ${response.statusMessage}`); } else { console.log(`Screenshot of ${url} captured.`); let screenshotData = []; response.on('data', (chunk) => { screenshotData.push(chunk); }); response.on('end', () => { resolve(Buffer.concat(screenshotData)); }); } }); }); } const urls_to_capture = [ 'https://example.com', 'https://google.com', 'https://twitter.com', ]; (async () => { const screenshots = await Promise.all(urls_to_capture.map(url => capture(url))); screenshots.forEach((screenshot, index) => { const filename = urls_to_capture[index].replace('https://', '') + '.jpeg'; fs.writeFileSync(filename, screenshot); }); })(); ``` PHP: ```php $access_key, 'url' => $url)); curl_setopt($handles[$url], CURLOPT_URL, "https://api.apiflash.com/v1/urltoimage?$params"); curl_setopt($handles[$url], CURLOPT_RETURNTRANSFER, 1); curl_multi_add_handle($mh, $handles[$url]); } $running = null; do { curl_multi_exec($mh, $running); } while ($running > 0); foreach ($handles as $url => $handle) { try { $response = curl_multi_getcontent($handle); echo "Screenshot of $url captured.\n"; $filename = str_replace('https://', '', $url) . '.jpeg'; file_put_contents($filename, $response); } catch (Exception $e) { echo "$url generated an exception: " . $e->getMessage() . "\n"; } curl_multi_remove_handle($mh, $handle); } curl_multi_close($mh); ?> ``` Python: ```python import concurrent.futures from urllib.parse import urlencode from urllib.request import urlopen access_key = 'YOUR_ACCESS_KEY_HERE' def capture(url): params = urlencode({'access_key': access_key, 'url': url}) print(f'Capturing {url} ...') with urlopen(f"https://api.apiflash.com/v1/urltoimage?{params}") as response: if response.status != 200: raise Exception(f'Failed to capture screenshot of {url}: {response.read()}') print(f'Screenshot of {url} captured.') return response.read() urls_to_capture = ['https://example.com', 'https://google.com', 'https://twitter.com'] with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: future_to_url = {executor.submit(capture, url): url for url in urls_to_capture} for future in concurrent.futures.as_completed(future_to_url): url = future_to_url[future] try: filename = url.replace('https://', '') + '.jpeg' with open(filename, 'wb') as screenshot_file: screenshot_file.write(future.result()) except Exception as error: print(f'{url} generated an exception: {error}') ``` Ruby: ```ruby require 'net/http' require 'uri' def capture(url) access_key = 'YOUR_ACCESS_KEY_HERE' uri = URI.parse("https://api.apiflash.com/v1/urltoimage?access_key=#{access_key}&url=#{url}") puts "Capturing #{url} ..." response = Net::HTTP.get_response(uri) if response.code != '200' raise "Failed to capture screenshot of #{url}: #{response.body}" end puts "Screenshot of #{url} captured." response.body end urls_to_capture = ['https://example.com', 'https://google.com', 'https://twitter.com'] thread_count = 5 threads = [] urls_to_capture.each_slice(thread_count) do |urls| urls.each do |url| threads << Thread.new do filename = url.gsub('https://', '') + '.jpeg' File.open(filename, 'wb') do |file| file.write(capture(url)) end end end threads.each(&:join) threads = [] end ``` # Screenshot authenticated pages Last updated september 29, 2026 ApiFlash captures each screenshot with a fresh browser that isn't logged in. Here is how to give it access to pages behind a login. Options 1 and 2 require changing the code of the website, so they only work for websites you own. | Option | Works with | Best for | | --- | --- | --- | | [1. Send a secret in a header](https://apiflash.com/guides/screenshot-authenticated-pages#secret-header) | Your website only | Quick setup | | [2. Send a signed token in a header](https://apiflash.com/guides/screenshot-authenticated-pages#signed-token) | Your website only | Extra security, since leaked tokens expire | | [3. Pass session cookies](https://apiflash.com/guides/screenshot-authenticated-pages#session-cookies) | Any website | Websites that log users in with a cookie | | [4. Pass HTTP headers](https://apiflash.com/guides/screenshot-authenticated-pages#http-headers) | Any website | Basic authentication or bearer tokens | | [5. Log in with JavaScript](https://apiflash.com/guides/screenshot-authenticated-pages#javascript-login) | Any website | When you can't get a session cookie ahead of time | Parameter values are shown unencoded below for readability, but must be URL encoded in your API calls. ## Option 1 • Send a secret in a header Send a secret string with the `headers` parameter: ``` https://api.apiflash.com/v1/urltoimage ?access_key=YOUR_ACCESS_KEY &url=https://app.example.com/reports/42 &headers=X-Screenshot-Secret=YOUR_SECRET ``` And make your website verify the secret before rendering the page: Express: ```javascript const crypto = require('crypto'); function isScreenshotRequest(req) { const received = Buffer.from(req.get('X-Screenshot-Secret') || ''); const expected = Buffer.from(process.env.SCREENSHOT_SECRET); return received.length === expected.length && crypto.timingSafeEqual(received, expected); } app.get('/reports/:id', (req, res) => { if (!req.user && !isScreenshotRequest(req)) { return res.redirect('/login'); } res.render('report', {report: getReport(req.params.id)}); }); ``` Django: ```python import hmac import os from django.contrib.auth.views import redirect_to_login from django.shortcuts import get_object_or_404, render from .models import Report def is_screenshot_request(request): received = request.headers.get('X-Screenshot-Secret', '').encode() return hmac.compare_digest(received, os.environ['SCREENSHOT_SECRET'].encode()) def report(request, report_id): if not request.user.is_authenticated and not is_screenshot_request(request): return redirect_to_login(request.get_full_path()) return render(request, 'report.html', {'report': get_object_or_404(Report, pk=report_id)}) ``` Laravel: ```php ['secret' => env('SCREENSHOT_SECRET')], class ReportController extends Controller { public function show(Request $request, Report $report) { if (!Auth::check() && !$this->isScreenshotRequest($request)) { return redirect()->route('login'); } return view('report', ['report' => $report]); } private function isScreenshotRequest(Request $request): bool { $secret = config('services.screenshot.secret') ?: throw new \RuntimeException('SCREENSHOT_SECRET is not set.'); return hash_equals($secret, $request->header('X-Screenshot-Secret', '')); } } ``` Rails: ```ruby class ReportsController < ApplicationController skip_before_action :authenticate_user!, if: :screenshot_request? def show @report = Report.find(params[:id]) end private def screenshot_request? ActiveSupport::SecurityUtils.secure_compare( request.headers['X-Screenshot-Secret'].to_s, ENV.fetch('SCREENSHOT_SECRET') ) end end ``` Spring Boot: ```java @Controller public class ReportController { private static final byte[] SCREENSHOT_SECRET = System.getenv("SCREENSHOT_SECRET").getBytes(StandardCharsets.UTF_8); private final ReportRepository reportRepository; public ReportController(ReportRepository reportRepository) { this.reportRepository = reportRepository; } static boolean isScreenshotRequest(String secret) { return secret != null && MessageDigest.isEqual(secret.getBytes(StandardCharsets.UTF_8), SCREENSHOT_SECRET); } // Also permit "/reports/**" in your Spring Security configuration. @GetMapping("/reports/{id}") public String report(@PathVariable long id, @RequestHeader(name = "X-Screenshot-Secret", required = false) String secret, Principal principal, Model model) { if (principal == null && !isScreenshotRequest(secret)) { return "redirect:/login"; } model.addAttribute("report", reportRepository.findById(id).orElseThrow()); return "report"; } } ``` Gin: ```go var screenshotSecret = []byte(os.Getenv("SCREENSHOT_SECRET")) func isScreenshotRequest(c *gin.Context) bool { received := []byte(c.GetHeader("X-Screenshot-Secret")) return len(screenshotSecret) > 0 && subtle.ConstantTimeCompare(received, screenshotSecret) == 1 } // router.GET("/reports/:id", showReport) func showReport(c *gin.Context) { if currentUser(c) == nil && !isScreenshotRequest(c) { c.Redirect(http.StatusFound, "/login") return } c.HTML(http.StatusOK, "report.html", gin.H{"report": getReport(c.Param("id"))}) } ``` ASP.NET Core: ```csharp using System.Security.Cryptography; using System.Text; static bool IsScreenshotRequest(HttpRequest request, IConfiguration config) { var received = Encoding.UTF8.GetBytes(request.Headers["X-Screenshot-Secret"].ToString()); var expected = Encoding.UTF8.GetBytes(config["ScreenshotSecret"]!); return CryptographicOperations.FixedTimeEquals(received, expected); } app.MapGet("/reports/{id}", (int id, HttpContext context, IConfiguration config) => { if (context.User.Identity?.IsAuthenticated != true && !IsScreenshotRequest(context.Request, config)) { return Results.Redirect("/login"); } return Results.Content(RenderReport(id), "text/html"); }); ``` To generate a random secret, you can run `openssl rand -hex 32` for example. Headers are also sent to the third party resources loaded by the page, like CDNs or analytics. If a leaked secret is a concern, use [option 2](https://apiflash.com/guides/screenshot-authenticated-pages#signed-token). ## Option 2 • Send a signed token in a header Instead of sending the secret itself, send a token signed with it that expires after 5 minutes: ``` https://api.apiflash.com/v1/urltoimage ?access_key=YOUR_ACCESS_KEY &url=https://app.example.com/reports/42 &headers=X-Screenshot-Token=TOKEN ``` Generate a token on your server for each API call and check that token instead of the secret from option 1: Express: ```javascript const crypto = require('crypto'); function sign(value) { return crypto.createHmac('sha256', process.env.SCREENSHOT_SECRET).update(value).digest('hex'); } function screenshotToken() { const expires = String(Math.floor(Date.now() / 1000) + 300); return `${expires}.${sign(expires)}`; } function isScreenshotRequest(req) { const [expires, signature] = (req.get('X-Screenshot-Token') || '').split('.'); if (!signature || !(Number(expires) > Date.now() / 1000)) { return false; } const received = Buffer.from(signature); const expected = Buffer.from(sign(expires)); return received.length === expected.length && crypto.timingSafeEqual(received, expected); } ``` Django: ```python import hashlib import hmac import os import time def sign(value): return hmac.new(os.environ['SCREENSHOT_SECRET'].encode(), value.encode(), hashlib.sha256).hexdigest() def screenshot_token(): expires = str(int(time.time()) + 300) return f'{expires}.{sign(expires)}' def is_screenshot_request(request): expires, _, signature = request.headers.get('X-Screenshot-Token', '').partition('.') if not (expires.isascii() and expires.isdigit()) or int(expires) < time.time(): return False return hmac.compare_digest(signature.encode(), sign(expires).encode()) ``` Laravel: ```php ['secret' => env('SCREENSHOT_SECRET')], class ScreenshotToken { public static function generate(): string { $expires = (string) (time() + 300); return $expires . '.' . self::sign($expires); } public static function isValid(?string $token): bool { $parts = explode('.', $token ?? '', 2); if (count($parts) !== 2 || !ctype_digit($parts[0]) || (int) $parts[0] < time()) { return false; } return hash_equals(self::sign($parts[0]), $parts[1]); } private static function sign(string $value): string { $secret = config('services.screenshot.secret') ?: throw new \RuntimeException('SCREENSHOT_SECRET is not set.'); return hash_hmac('sha256', $value, $secret); } } // In the controller, replace $this->isScreenshotRequest($request) with // ScreenshotToken::isValid($request->header('X-Screenshot-Token')). ``` Rails: ```ruby module ScreenshotToken def self.generate expires = (Time.now.to_i + 300).to_s "#{expires}.#{sign(expires)}" end def self.valid?(token) expires, signature = token.to_s.split('.', 2) return false unless expires&.match?(/\A\d+\z/) && expires.to_i > Time.now.to_i ActiveSupport::SecurityUtils.secure_compare(signature.to_s, sign(expires)) end def self.sign(value) OpenSSL::HMAC.hexdigest('SHA256', ENV.fetch('SCREENSHOT_SECRET'), value) end end # In the controller: # skip_before_action :authenticate_user!, if: -> { ScreenshotToken.valid?(request.headers['X-Screenshot-Token']) } ``` Spring Boot: ```java public final class ScreenshotToken { private static final byte[] SECRET = System.getenv("SCREENSHOT_SECRET").getBytes(StandardCharsets.UTF_8); public static String generate() { String expires = String.valueOf(Instant.now().getEpochSecond() + 300); return expires + "." + sign(expires); } public static boolean isValid(String token) { String[] parts = token == null ? new String[0] : token.split("\\.", 2); if (parts.length != 2 || !parts[0].matches("\\d{1,18}") || Long.parseLong(parts[0]) < Instant.now().getEpochSecond()) { return false; } return MessageDigest.isEqual(parts[1].getBytes(StandardCharsets.UTF_8), sign(parts[0]).getBytes(StandardCharsets.UTF_8)); } private static String sign(String value) { try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(SECRET, "HmacSHA256")); return HexFormat.of().formatHex(mac.doFinal(value.getBytes(StandardCharsets.UTF_8))); } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } } } // In the controller, replace isScreenshotRequest(secret) with ScreenshotToken.isValid(token). ``` Gin: ```go var screenshotSecret = []byte(os.Getenv("SCREENSHOT_SECRET")) func sign(value string) string { mac := hmac.New(sha256.New, screenshotSecret) mac.Write([]byte(value)) return hex.EncodeToString(mac.Sum(nil)) } func screenshotToken() string { expires := strconv.FormatInt(time.Now().Unix()+300, 10) return expires + "." + sign(expires) } func isScreenshotRequest(c *gin.Context) bool { expires, signature, _ := strings.Cut(c.GetHeader("X-Screenshot-Token"), ".") timestamp, err := strconv.ParseInt(expires, 10, 64) if len(screenshotSecret) == 0 || err != nil || timestamp < time.Now().Unix() { return false } return hmac.Equal([]byte(signature), []byte(sign(expires))) } ``` ASP.NET Core: ```csharp using System.Security.Cryptography; using System.Text; static string Sign(string value, IConfiguration config) { var key = Encoding.UTF8.GetBytes(config["ScreenshotSecret"]!); return Convert.ToHexString(HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(value))); } static string ScreenshotToken(IConfiguration config) { var expires = (DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 300).ToString(); return $"{expires}.{Sign(expires, config)}"; } static bool IsScreenshotRequest(HttpRequest request, IConfiguration config) { var parts = request.Headers["X-Screenshot-Token"].ToString().Split('.', 2); if (parts.Length != 2 || !long.TryParse(parts[0], out var expires) || expires < DateTimeOffset.UtcNow.ToUnixTimeSeconds()) { return false; } return CryptographicOperations.FixedTimeEquals( Encoding.UTF8.GetBytes(parts[1]), Encoding.UTF8.GetBytes(Sign(parts[0], config))); } ``` As the token changes with every API call, screenshots are never served from the cache. The secret never leaves your server, and a leaked token is useless after 5 minutes. ## Option 3 • Pass session cookies Most websites keep users logged in with a session cookie. Pass that cookie with the `cookies` parameter, and ApiFlash loads the page as the logged in user: ``` https://api.apiflash.com/v1/urltoimage ?access_key=YOUR_ACCESS_KEY &url=https://app.example.com/dashboard &cookies=session_id=YOUR_SESSION_ID;csrf_token=YOUR_CSRF_TOKEN ``` To get the session cookie, log in with your browser and copy it from the developer tools (**Application** › **Cookies**). Cookies are only sent to the domain of the `url` parameter. Some session cookies expire. To get fresh ones automatically, log in with a script and build the `cookies` parameter from the cookies it receives: Puppeteer: ```javascript const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://app.example.com/login'); await page.type('input[name="email"]', 'screenshots@example.com'); await page.type('input[name="password"]', process.env.PASSWORD); await Promise.all([page.waitForNavigation(), page.click('button[type="submit"]')]); const cookies = (await browser.cookies()).filter(cookie => cookie.domain.endsWith('example.com')); await browser.close(); console.log(cookies.map(cookie => `${cookie.name}=${cookie.value}`).join(';')); })(); ``` Playwright: ```python import os from playwright.sync_api import sync_playwright with sync_playwright() as playwright: browser = playwright.chromium.launch() page = browser.new_page() page.goto('https://app.example.com/login') page.locator('input[name="email"]').fill('screenshots@example.com') page.locator('input[name="password"]').fill(os.environ['PASSWORD']) page.locator('button[type="submit"]').click() page.wait_for_url('**/dashboard') cookies = page.context.cookies('https://app.example.com') browser.close() print(';'.join(f'{cookie["name"]}={cookie["value"]}' for cookie in cookies)) ``` Selenium: ```python import os from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait driver = webdriver.Chrome() driver.get('https://app.example.com/login') driver.find_element(By.NAME, 'email').send_keys('screenshots@example.com') driver.find_element(By.NAME, 'password').send_keys(os.environ['PASSWORD']) driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]').click() WebDriverWait(driver, 10).until(expected_conditions.url_contains('/dashboard')) cookies = driver.get_cookies() driver.quit() print(';'.join(f'{cookie["name"]}={cookie["value"]}' for cookie in cookies)) ``` Requests: ```python import os import requests # Without a browser, this only works with simple login forms that don't need JavaScript or a CSRF token. session = requests.Session() session.post('https://app.example.com/login', data={ 'email': 'screenshots@example.com', 'password': os.environ['PASSWORD'], }) print(';'.join(f'{name}={value}' for name, value in session.cookies.items())) ``` ## Option 4 • Pass HTTP headers Some websites and APIs authenticate each request with a header, usually `Authorization`. Pass that header with the `headers` parameter, and ApiFlash sends it when loading the page: ``` https://api.apiflash.com/v1/urltoimage ?access_key=YOUR_ACCESS_KEY &url=https://app.example.com/reports/42 &headers=Authorization=Bearer YOUR_TOKEN ``` For Basic authentication, use `Authorization=Basic CREDENTIALS` where `CREDENTIALS` is `username:password` encoded in base64. Like in [option 1](https://apiflash.com/guides/screenshot-authenticated-pages#secret-header), headers are also sent to the third party resources loaded by the page. Prefer [cookies](https://apiflash.com/guides/screenshot-authenticated-pages#session-cookies) if the website supports them, as they are only sent to the domain of the `url` parameter. ## Option 5 • Log in with JavaScript ApiFlash can also log in by itself, by filling in and submitting the login form of the website before taking the screenshot. Set `url` to the login page, submit the login form with the `js` parameter, and set `wait_for` to a CSS selector that only exists once logged in: ``` https://api.apiflash.com/v1/urltoimage ?access_key=YOUR_ACCESS_KEY &url=https://app.example.com/login?next=/reports/42 &js=LOGIN_SCRIPT &wait_for=.report ``` Where `LOGIN_SCRIPT` fills in and submits the login form: ```js function fill(selector, value) { const input = document.querySelector(selector); // Use the native setter so that frameworks like React notice the change. Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(input, value); input.dispatchEvent(new Event('input', {bubbles: true})); } fill('input[name="email"]', 'screenshots@example.com'); fill('input[name="password"]', 'YOUR_PASSWORD'); document.querySelector('input[name="password"]').form.requestSubmit(); ``` The screenshot shows the page you land on after the login, which you can often choose with a redirect parameter like `/login?next=/reports/42`. This doesn't work with CAPTCHAs or two-factor authentication. # Allow users to download generated screenshots Last updated december 01, 2022 Here are some ways to allow your users to download the generated screenshots. ## Option 1 • Use an anchor element if you are proxying ApiFlash If you are proxying ApiFlash's API through your own domain, you can just use an [anchor element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) with the `download` attribute to allow users to download the generated screenshot. ```html Download ``` Using ApiFlash's API endpoint `https://api.apiflash.com/v1/urltoimage...` directly in the `href` attribute will not work because the `download` attribute only works for same-origin URLs. If you are not proxying ApiFlash's API yet and would like to use anchor elements to trigger screenshots downloads, please check one of those guides: - [Make api calls through Nginx.](https://apiflash.com/guides/api-calls-through-nginx) ## Option 2 • Make an api call from the frontend and trigger a file download. Making api calls from the front end will **expose your access key to the end users**. This method should only be used for internal tools or situations where all end users can be trusted. As seen previously, the `download` attribute of the anchor element only works for same-origin URLs. But there is still a way to trigger a file download from the frontend using javascript. ```javascript fetch('https://api.apiflash.com/v1/urltoimage?access_key=YOUR_ACCESS_KEY&url=https://example.com') .then(response => { response .blob() .then(blob => { let a = document.createElement('a'); a.href = window.URL.createObjectURL(blob); a.download = 'screenshot.jpeg'; document.body.appendChild(a); a.click(); }); }); ``` In the previous example we make an api call to ApiFlash's screenshot API and get the response as a blob. Then we create an anchor element and simulate a click to trigger the file download. We used the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API), but you can use anything you'd like to make the HTTP request to perform the api call. ## Option 3 • Make an api call from the backend and use appropriate HTTP headers. If the HTTP response contains the `Content-Disposition` header with the `attachment` parameter, almost all browsers will automatically trigger a file download. ```http Content-Disposition: attachment; filename="filename.jpg" ``` When your user is navigating to one of your endpoint, you can simply make an API call to ApiFlash from the backend, put the resulting image in the HTTP response's body and set the `Content-Disposition` header.