Skip to documentation content
Browse documentation

Get started

Screenshot API examples in Node.js, Python, and PHP

Copy server-side ScreenshotEngine examples for Node.js, Python, PHP, and cURL, with API key environment variables and binary file handling.

View as Markdown

Before you run the examples

Create an API key in the dashboard and set the SCREENSHOTENGINE_API_KEY environment variable. Run these examples on your server or local development machine. Each example checks the response status and writes a PNG file on success.

Terminal
export SCREENSHOTENGINE_API_KEY="YOUR_API_KEY"

Node.js: fetch and save a screenshot

Use Node.js 20 or later with its built-in fetch. Save this example as screenshot.mjs and run node screenshot.mjs. It needs no additional packages. The 120-second client timeout is an example budget, not an API response-time guarantee.

screenshot.mjs
import { writeFile } from "node:fs/promises";

const apiKey = process.env.SCREENSHOTENGINE_API_KEY;
if (!apiKey) throw new Error("Set SCREENSHOTENGINE_API_KEY first");

const response = await fetch("https://api.screenshotengine.com/v1/screenshot", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    url: "https://example.com",
    format: "png",
    height: "full",
  }),
  signal: AbortSignal.timeout(120_000),
});

if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}

await writeFile("screenshot.png", Buffer.from(await response.arrayBuffer()));
console.log("Saved screenshot.png");

Python: download a screenshot

This Python 3 example uses only the standard library. Save it as screenshot.py and run python3 screenshot.py. HTTP errors are reported before any image file is written.

screenshot.py
import json
import os
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen

payload = {"url": "https://example.com", "format": "png", "height": "full"}
request = Request(
    "https://api.screenshotengine.com/v1/screenshot",
    data=json.dumps(payload).encode("utf-8"),
    headers={
        "Authorization": f"Bearer {os.environ['SCREENSHOTENGINE_API_KEY']}",
        "Content-Type": "application/json",
    },
    method="POST",
)

try:
    with urlopen(request, timeout=120) as response:
        Path("screenshot.png").write_bytes(response.read())
except HTTPError as error:
    raise RuntimeError(
        f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}"
    ) from error

print("Saved screenshot.png")

PHP: capture with cURL

Use PHP 8+ with the cURL extension enabled. Save this as screenshot.php and run php screenshot.php. JSON_THROW_ON_ERROR prevents silently sending invalid JSON.

screenshot.php
<?php
$apiKey = getenv('SCREENSHOTENGINE_API_KEY');
if (!$apiKey) {
    throw new RuntimeException('Set SCREENSHOTENGINE_API_KEY first');
}

$curl = curl_init('https://api.screenshotengine.com/v1/screenshot');
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 120,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'url' => 'https://example.com',
        'format' => 'png',
        'height' => 'full',
    ], JSON_THROW_ON_ERROR),
]);

$body = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = curl_error($curl);
curl_close($curl);

if ($body === false) {
    throw new RuntimeException($error);
}
if ($status < 200 || $status >= 300) {
    throw new RuntimeException("HTTP $status: $body");
}
if (file_put_contents('screenshot.png', $body) === false) {
    throw new RuntimeException('Could not write screenshot.png');
}
echo "Saved screenshot.png\n";

cURL: a request from your terminal

Use --output to save binary bytes to a file. The --fail-with-body option returns an error exit code for HTTP failures while keeping the response body available for debugging.

Terminal
curl --fail-with-body --request POST 'https://api.screenshotengine.com/v1/screenshot' \
  --header "Authorization: Bearer $SCREENSHOTENGINE_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
  "url": "https://example.com",
  "format": "png",
  "height": "full"
}' \
  --output screenshot.png