5 Ways to Use a Screenshot API in Your Next Project

javascript dev.to

5 Ways to Use a Screenshot API in Your Next Project

Have you ever needed to capture a screenshot of a webpage programmatically? Whether you're building a monitoring tool, generating PDFs, or extracting link previews, doing this manually is painful. Browser automation libraries like Puppeteer work, but they're heavyweight, require a Chromium instance, and add ops complexity to your stack.

That's where a Screenshot API comes in. With a single HTTP request, you get back a rendered screenshot — no headless browser to manage, no infra to babysit.

In this article, we'll explore 5 real-world use cases using the Screenshot Capture API on RapidAPI, which supports async capture, PDF generation, OpenGraph extraction, dark mode, ad blocking, and more.

Get started free: https://rapidapi.com/tawanshamsanor/api/screenshot-capture-api1


The API at a Glance

  • Base URL: https://hubaiasia.com/screenshot-api
  • Key endpoints:
    • POST /screenshot — Synchronous capture
    • POST /screenshot/async — Async capture with job queue
    • GET /screenshot/job/:id — Poll async job result
    • POST /screenshot/pdf — Generate PDF (A4, Letter, Legal, Tabloid)
    • POST /screenshot/og — Extract OpenGraph metadata + favicon
  • Formats: PNG, JPEG, WebP
  • Options: fullPage, viewport, selector, delay, darkMode, blockAds, waitForSelector, clip, quality
  • Free tier available

All examples below use the X-RapidAPI-Key header. Grab your key from RapidAPI and plug it in.


1. Social Media Link Previews

When a user pastes a URL into your app (a chat tool, a note-taking app, a CMS), you want to show a rich preview card — thumbnail + title + description. The /screenshot/og endpoint does both: it extracts OpenGraph metadata and returns a favicon, all in one shot.

async function getLinkPreview(url) {
  const response = await fetch("https://hubaiasia.com/screenshot-api/screenshot/og", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-RapidAPI-Key": "YOUR_RAPIDAPI_KEY",
      "X-RapidAPI-Host": "screenshot-capture-api1.p.rapidapi.com"
    },
    body: JSON.stringify({ url })
  });

  const data = await response.json();

  return {
    title: data.og?.title || data.title,
    description: data.og?.description || data.description,
    image: data.og?.image,
    favicon: data.favicon,
    siteName: data.og?.site_name
  };
}

// Usage
const preview = await getLinkPreview("https://dev.to");
console.log(preview.title); // "DEV Community"
Enter fullscreen mode Exit fullscreen mode

No scraping, no HTML parsing, no regex nightmares. One request and you have everything to render a beautiful preview card.


2. Website Monitoring and Archiving

Visual monitoring goes beyond uptime checks. Sometimes a page is "up" but shows a broken layout, a white screen, or a degraded state. With the async endpoint, you can schedule periodic screenshots of critical pages and store them for comparison.

async function archivePage(url, label) {
  // Submit async job
  const jobRes = await fetch("https://hubaiasia.com/screenshot-api/screenshot/async", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-RapidAPI-Key": "YOUR_RAPIDAPI_KEY",
      "X-RapidAPI-Host": "screenshot-capture-api1.p.rapidapi.com"
    },
    body: JSON.stringify({
      url,
      fullPage: true,
      format: "png",
      blockAds: true,
      viewport: { width: 1440, height: 900 }
    })
  });

  const { jobId } = await jobRes.json();

  // Poll for result
  let result;
  for (let i = 0; i < 10; i++) {
    await new Promise(r => setTimeout(r, 3000));
    const pollRes = await fetch(
      `https://hubaiasia.com/screenshot-api/screenshot/job/${jobId}`,
      { headers: { "X-RapidAPI-Key": "YOUR_RAPIDAPI_KEY" } }
    );
    result = await pollRes.json();
    if (result.status === "done") break;
  }

  // result.image is base64 — save it to your storage
  const buffer = Buffer.from(result.image, "base64");
  console.log(`Archived ${label}: ${buffer.length} bytes`);
  return buffer;
}
Enter fullscreen mode Exit fullscreen mode

Run this on a cron job, store the PNGs to S3 or Cloudflare R2, and you have a visual archive. Add pixel diffing (e.g. with pixelmatch) and you've got a lightweight visual monitoring system.


3. PDF Generation for Invoices and Reports

Generating PDFs server-side is notoriously finicky. wkhtmltopdf is unmaintained, puppeteer-pdf adds 300 MB to your Docker image, and most PDF libraries can't render modern CSS. The /screenshot/pdf endpoint gives you a clean PDF from any URL — perfect for invoice pages, reports, or print-ready documents.

async function generateInvoicePDF(invoiceUrl) {
  const response = await fetch("https://hubaiasia.com/screenshot-api/screenshot/pdf", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-RapidAPI-Key": "YOUR_RAPIDAPI_KEY",
      "X-RapidAPI-Host": "screenshot-capture-api1.p.rapidapi.com"
    },
    body: JSON.stringify({
      url: invoiceUrl,
      format: "A4",        // A4 | Letter | Legal | Tabloid
      printBackground: true,
      waitForSelector: ".invoice-ready" // wait for data to load
    })
  });

  const { pdf } = await response.json(); // base64 PDF
  const pdfBuffer = Buffer.from(pdf, "base64");

  // In Express: send as download
  // res.setHeader("Content-Type", "application/pdf");
  // res.setHeader("Content-Disposition", `attachment; filename="invoice.pdf"`);
  // res.send(pdfBuffer);

  return pdfBuffer;
}
Enter fullscreen mode Exit fullscreen mode

The waitForSelector option is key here — it waits until your invoice data has rendered before capturing, so you never get a half-loaded PDF.


4. OG Metadata Extraction for SEO Tools

Building an SEO audit tool, a content scheduler, or a social preview checker? You need to validate OpenGraph tags across hundreds of URLs efficiently. The /screenshot/og endpoint returns structured metadata you can validate, score, and report on.

async function auditSEOMetadata(urls) {
  const results = await Promise.all(
    urls.map(async (url) => {
      const res = await fetch("https://hubaiasia.com/screenshot-api/screenshot/og", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-RapidAPI-Key": "YOUR_RAPIDAPI_KEY",
          "X-RapidAPI-Host": "screenshot-capture-api1.p.rapidapi.com"
        },
        body: JSON.stringify({ url })
      });

      const data = await res.json();
      const og = data.og || {};

      return {
        url,
        hasTitle: !!og.title,
        hasDescription: !!og.description,
        hasImage: !!og.image,
        titleLength: og.title?.length || 0,
        descriptionLength: og.description?.length || 0,
        score: [og.title, og.description, og.image].filter(Boolean).length
      };
    })
  );

  return results;
}

// Usage
const audit = await auditSEOMetadata([
  "https://yoursite.com/blog/post-1",
  "https://yoursite.com/blog/post-2"
]);

audit.forEach(r => {
  console.log(`${r.url} — Score: ${r.score}/3`);
});
Enter fullscreen mode Exit fullscreen mode

This is a great foundation for a Slack bot that alerts your content team whenever a new page is missing its OG image.


5. Automated Visual Regression Testing

CI pipelines check logic, but they don't catch visual regressions — a CSS change that breaks the hero section on mobile, or a font that falls back incorrectly. With the Screenshot API, you can capture baseline screenshots and diff them on every PR.

import pixelmatch from "pixelmatch";
import { PNG } from "pngjs";

async function captureScreenshot(url, viewport = { width: 1280, height: 800 }) {
  const res = await fetch("https://hubaiasia.com/screenshot-api/screenshot", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-RapidAPI-Key": "YOUR_RAPIDAPI_KEY",
      "X-RapidAPI-Host": "screenshot-capture-api1.p.rapidapi.com"
    },
    body: JSON.stringify({
      url,
      viewport,
      fullPage: false,
      format: "png",
      delay: 1000 // wait for animations to settle
    })
  });

  const { image } = await res.json();
  return Buffer.from(image, "base64");
}

async function visualRegression(url, baselineBuffer) {
  const currentBuffer = await captureScreenshot(url);

  const baseline = PNG.sync.read(baselineBuffer);
  const current = PNG.sync.read(currentBuffer);
  const { width, height } = baseline;

  const diff = new PNG({ width, height });
  const numDiffPixels = pixelmatch(
    baseline.data, current.data, diff.data,
    width, height,
    { threshold: 0.1 }
  );

  const diffPercent = (numDiffPixels / (width * height)) * 100;
  console.log(`Visual diff: ${diffPercent.toFixed(2)}%`);

  if (diffPercent > 1) {
    throw new Error(`Visual regression detected: ${diffPercent.toFixed(2)}% pixels changed`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Integrate this into your GitHub Actions workflow: capture a baseline on main, then diff on every PR. Fail the check if the diff exceeds your threshold.


Wrapping Up

A Screenshot API punches well above its weight. Five lines of fetch can replace hundreds of lines of Puppeteer setup, and you get PDF generation and OG extraction thrown in for free.

Here's a quick summary of what we covered:

Use Case Endpoint Key Option
Social media previews /screenshot/og Returns title, description, image
Website archiving /screenshot/async fullPage: true, blockAds: true
Invoice PDFs /screenshot/pdf format: "A4", waitForSelector
SEO metadata audit /screenshot/og Batch multiple URLs
Visual regression /screenshot delay, viewport, then diff

Get your free API key and start building:
https://rapidapi.com/tawanshamsanor/api/screenshot-capture-api1

The free tier is available — no credit card required to get started. Happy building!

Read Full Tutorial open_in_new
arrow_back Back to Tutorials