# 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
<?php

$params = http_build_query(array(
    "access_key" => "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.
