Basic Screenshots | PeekShot API Examples
Basic Screenshots
Section titled “Basic Screenshots”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.
Simple Website Screenshot
Section titled “Simple Website Screenshot”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);
import requests
def take_simple_screenshot(url):
headers = {
'x-api-key': 'YOUR_API_KEY',
'Content-Type': 'application/json'
}
payload = {'url': url}
response = requests.post(
'https://api.peekshot.com/api/v1/screenshots',
json=payload,
headers=headers
)
result = response.json()
return result['url']
# Usage
screenshot_url = take_simple_screenshot('https://example.com')
print(f'Screenshot saved at: {screenshot_url}')
curl -X POST https://api.peekshot.com/api/v1/screenshots \
-H "x-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com"}'
<?php
function takeSimpleScreenshot($url) {
$data = array('url' => $url);
$options = array(
'http' => array(
'header' => "x-api-key: YOUR_API_KEY\r\n" .
"Content-Type: application/json\r\n",
'method' => 'POST',
'content' => json_encode($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents('https://api.peekshot.com/api/v1/screenshots', false, $context);
$response = json_decode($result, true);
return $response['url'];
}
// Usage
$screenshotUrl = takeSimpleScreenshot('https://example.com');
echo "Screenshot saved at: " . $screenshotUrl;
?>
Social Media Preview Images
Section titled “Social Media Preview Images”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");
Mobile Screenshots
Section titled “Mobile Screenshots”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 };
};
High-Quality PDF Generation
Section titled “High-Quality PDF Generation”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
};
Batch Processing Multiple URLs
Section titled “Batch Processing Multiple URLs”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 },
});
Screenshots with Custom CSS
Section titled “Screenshots with Custom CSS”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();
};
Screenshot with Authentication
Section titled “Screenshot with Authentication”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();
};
Error Handling Best Practices
Section titled “Error Handling Best Practices”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");
};
Working with the Results
Section titled “Working with the Results”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,
};
};
Common Use Case Examples
Section titled “Common Use Case Examples”E-commerce Product Previews
Section titled “E-commerce Product Previews”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());
};
Blog Post Thumbnails
Section titled “Blog Post Thumbnails”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());
};
Website Monitoring
Section titled “Website Monitoring”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,
};
};
Next Steps
Section titled “Next Steps”Now that you’ve seen the basic examples, explore more advanced features:
- Custom Templates - Create branded screenshot templates
- Bulk Processing - Handle large volumes efficiently
- Webhook Integration - Process screenshots asynchronously
- JavaScript SDK - Use our official library for easier integration