Skip to content
LinkedInInstagramFacebook

Basic Screenshots | PeekShot API Examples

This guide provides practical examples of the most common screenshot scenarios using PeekShot API. Each example includes complete code that you can copy and adapt for your own applications.

The most basic use case - capturing a screenshot of any public website:

const takeSimpleScreenshot = async (url) => {
  const response = await fetch("https://api.peekshot.com/api/v1/screenshots", {
    method: "POST",
    headers: {
      "x-api-key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: url,
    }),
  });

  const result = await response.json();
  return result.url; // Direct URL to the screenshot
};

// Usage
const screenshotUrl = await takeSimpleScreenshot("https://example.com");
console.log("Screenshot saved at:", screenshotUrl);

Create Open Graph images perfect for social media sharing:

const createSocialPreview = async (articleUrl) => {
  const response = await fetch("https://api.peekshot.com/api/v1/screenshots", {
    method: "POST",
    headers: {
      "x-api-key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: articleUrl,
      viewport: {
        width: 1200, // Perfect for Open Graph
        height: 630,
      },
      format: "png",
      quality: 95,
      device: "desktop",
      wait_for: 2000, // Wait for content to load
    }),
  });

  const result = await response.json();
  return result;
};

// Usage
const preview = await createSocialPreview("https://yourblog.com/article/123");

Capture how your site looks on mobile devices:

const takeMobileScreenshot = async (url) => {
  return await fetch("https://api.peekshot.com/api/v1/screenshots", {
    method: "POST",
    headers: {
      "x-api-key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: url,
      device: "mobile",
      viewport: {
        width: 375, // iPhone viewport width
        height: 667,
      },
      full_page: true, // Capture entire page
      format: "png",
    }),
  }).then((res) => res.json());
};

// Capture both desktop and mobile versions
const captureResponsiveScreenshots = async (url) => {
  const [desktop, mobile] = await Promise.all([
    takeSimpleScreenshot(url),
    takeMobileScreenshot(url),
  ]);

  return { desktop, mobile };
};

Generate PDFs from web pages for reports or documentation:

const generatePDF = async (url) => {
  const response = await fetch("https://api.peekshot.com/api/v1/screenshots", {
    method: "POST",
    headers: {
      "x-api-key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: url,
      format: "pdf",
      full_page: true,
      viewport: {
        width: 1920,
        height: 1080,
      },
      wait_for: 3000, // Allow extra time for complex pages
      css: `
        @media print { 
          .no-print { display: none !important; }
          .header, .footer { page-break-inside: avoid; }
        }
      `,
    }),
  });

  const result = await response.json();
  return result.url; // URL to download PDF
};

Process multiple URLs efficiently:

const batchScreenshots = async (urls, options = {}) => {
  const results = [];
  const batchSize = 5; // Process 5 at a time for optimal performance

  for (let i = 0; i < urls.length; i += batchSize) {
    const batch = urls.slice(i, i + batchSize);

    const batchPromises = batch.map((url) =>
      fetch("https://api.peekshot.com/api/v1/screenshots", {
        method: "POST",
        headers: {
          "x-api-key": "YOUR_API_KEY",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          url,
          ...options,
        }),
      })
        .then((res) => res.json())
        .catch((error) => ({ error, url }))
    );

    const batchResults = await Promise.all(batchPromises);
    results.push(...batchResults);

    // Wait between batches for optimal performance
    if (i + batchSize < urls.length) {
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }

  return results;
};

// Usage
const urls = [
  "https://example.com",
  "https://github.com",
  "https://stackoverflow.com",
];

const screenshots = await batchScreenshots(urls, {
  format: "png",
  viewport: { width: 1920, height: 1080 },
});

Hide elements or modify styling before capturing:

const customStyledScreenshot = async (url) => {
  const response = await fetch("https://api.peekshot.com/api/v1/screenshots", {
    method: "POST",
    headers: {
      "x-api-key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: url,
      css: `
        /* Hide ads and popups */
        .ad, .advertisement, .popup, .modal { 
          display: none !important; 
        }
        
        /* Hide cookie notices */
        [class*="cookie"], [id*="cookie"] { 
          display: none !important; 
        }
        
        /* Customize appearance */
        body { 
          background: white !important; 
        }
      `,
      hide_selectors: [".cookie-banner", ".newsletter-popup", ".chat-widget"],
      wait_for: 2000,
    }),
  });

  return await response.json();
};

Capture screenshots of protected pages:

const authenticatedScreenshot = async (url, authToken) => {
  const response = await fetch("https://api.peekshot.com/api/v1/screenshots", {
    method: "POST",
    headers: {
      "x-api-key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: url,
      headers: {
        Authorization: `Bearer ${authToken}`,
        "User-Agent": "PeekShot-Bot/1.0",
      },
      cookies: [
        {
          name: "session_id",
          value: "your-session-id",
          domain: "yourdomain.com",
        },
      ],
      wait_for: 3000,
    }),
  });

  return await response.json();
};

Always include proper error handling:

const robustScreenshot = async (url, options = {}) => {
  try {
    const response = await fetch(
      "https://api.peekshot.com/api/v1/screenshots",
      {
        method: "POST",
        headers: {
          "x-api-key": "YOUR_API_KEY",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          url,
          ...options,
        }),
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(`Screenshot failed: ${error.message} (${error.code})`);
    }

    const result = await response.json();

    // Handle async processing
    if (result.status === "processing") {
      return await pollForCompletion(result.id);
    }

    return result;
  } catch (error) {
    console.error("Screenshot error:", error);

    // Implement retry logic for transient errors
    if (
      error.message.includes("timeout") ||
      error.message.includes("network")
    ) {
      console.log("Retrying after error...");
      await new Promise((resolve) => setTimeout(resolve, 2000));
      return robustScreenshot(url, options); // Simple retry
    }

    throw error;
  }
};

// Poll for async completion
const pollForCompletion = async (screenshotId, maxAttempts = 10) => {
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const response = await fetch(
      `https://api.peekshot.com/api/v1/screenshots/${screenshotId}`,
      {
        headers: {
          "x-api-key": "YOUR_API_KEY",
        },
      }
    );

    const result = await response.json();

    if (result.status === "completed") {
      return result;
    } else if (result.status === "failed") {
      throw new Error(`Screenshot failed: ${result.error}`);
    }

    // Wait before next poll
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }

  throw new Error("Screenshot processing timeout");
};

Common patterns for handling screenshot results:

const processScreenshot = async (url) => {
  const screenshot = await takeSimpleScreenshot(url);

  // Download the image
  const imageResponse = await fetch(screenshot.url);
  const imageBuffer = await imageResponse.arrayBuffer();

  // Save to file (Node.js)
  const fs = require("fs");
  fs.writeFileSync("screenshot.png", Buffer.from(imageBuffer));

  // Or convert to base64 for embedding
  const base64 = Buffer.from(imageBuffer).toString("base64");
  const dataUri = `data:image/png;base64,${base64}`;

  return {
    url: screenshot.url,
    dataUri: dataUri,
    metadata: screenshot.metadata,
  };
};
const productPreview = async (productUrl) => {
  return await fetch("https://api.peekshot.com/api/v1/screenshots", {
    method: "POST",
    headers: {
      "x-api-key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: productUrl,
      viewport: { width: 800, height: 600 },
      wait_for_selector: ".product-image", // Wait for product to load
      format: "jpeg",
      quality: 85,
    }),
  }).then((res) => res.json());
};
const blogThumbnail = async (postUrl) => {
  return await fetch("https://api.peekshot.com/api/v1/screenshots", {
    method: "POST",
    headers: {
      "x-api-key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: postUrl,
      viewport: { width: 400, height: 300 },
      format: "webp", // Smaller file size
      quality: 80,
      css: ".sidebar, .comments { display: none; }", // Focus on content
    }),
  }).then((res) => res.json());
};
const monitorWebsite = async (url) => {
  const screenshot = await fetch(
    "https://api.peekshot.com/api/v1/screenshots",
    {
      method: "POST",
      headers: {
        "x-api-key": "YOUR_API_KEY",
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        url: url,
        full_page: true,
        wait_for: 5000, // Extra wait for dynamic content
        format: "png",
      }),
    }
  ).then((res) => res.json());

  // Store for comparison with previous screenshots
  return {
    timestamp: new Date().toISOString(),
    url: screenshot.url,
    pageTitle: screenshot.metadata.page_title,
    loadTime: screenshot.metadata.load_time,
  };
};

Now that you’ve seen the basic examples, explore more advanced features: