Code Examples

Ready-to-use code samples for integrating the Screenshot API in your favorite programming language.

API Key Required

All examples require an API key. Store it securely in environment variables. Never commit API keys to version control.

Basic Screenshot

Capture a simple screenshot at default resolution (1920x1080):

curl -X POST https://snappkit.com/api/screenshot \
 -H"Authorization: Bearer YOUR_API_KEY" \
 -H"Content-Type: application/json" \
 -d'{"url":"https://example.com"}' \
 --output screenshot.png

Full-Page Screenshot

Capture the entire scrollable page, not just the viewport:

async function captureFullPage(url) {
 const response = await fetch('https://snappkit.com/api/screenshot', {
 method:'POST',
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 body: JSON.stringify({
 url,
 fullPage: true,
 format:'png'
 })
 });

 const buffer = Buffer.from(await response.arrayBuffer());
 return buffer;
}
Full-page screenshots cost 2 credits instead of 1.

Mobile Device Emulation

Capture a screenshot with mobile viewport and user agent:

async function captureMobileView(url) {
 const response = await fetch('https://snappkit.com/api/screenshot', {
 method:'POST',
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 body: JSON.stringify({
 url,
 device:'mobile',
 fullPage: true,
 delay: 2000
 })
 });

 return Buffer.from(await response.arrayBuffer());
}

Custom Dimensions & Format

High-Quality JPEG

async function captureHighQualityJPEG(url) {
 const response = await fetch('https://snappkit.com/api/screenshot', {
 method:'POST',
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 body: JSON.stringify({
 url,
 width: 2560,
 height: 1440,
 format:'jpeg',
 quality: 95
 })
 });

 return Buffer.from(await response.arrayBuffer());
}

Optimized WEBP

def capture_optimized_webp(url):
 response = requests.post(
'https://snappkit.com/api/screenshot',
 headers={
'Authorization': f'Bearer {os.environ["API_KEY"]}',
'Content-Type':'application/json'
 },
 json={
'url': url,
'format':'webp',
'quality': 80,
'width': 1280,
'height': 720
 }
 )

 response.raise_for_status()
 return response.content

Wait for JavaScript

For single-page applications (SPAs) that need time to render:

async function captureSPA(url) {
 const response = await fetch('https://snappkit.com/api/screenshot', {
 method:'POST',
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 body: JSON.stringify({
 url,
 delay: 3000, // Wait 3 seconds for JavaScript to execute
 width: 1920,
 height: 1080
 })
 });

 return Buffer.from(await response.arrayBuffer());
}

Batch Processing Multiple URLs

Capture screenshots of multiple URLs in parallel:

async function captureMultiple(urls) {
 const promises = urls.map(url =>
 fetch('https://snappkit.com/api/screenshot', {
 method:'POST',
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 body: JSON.stringify({ url })
 })
 );

 const responses = await Promise.all(promises);

 return Promise.all(
 responses.map(async (response, index) => {
 if (!response.ok) {
 console.error(`Failed to capture ${urls[index]}`);
 return null;
 }
 return {
 url: urls[index],
 buffer: Buffer.from(await response.arrayBuffer())
 };
 })
 );
}

const urls = [
'https://example.com',
'https://example.org',
'https://example.net'
];

captureMultiple(urls).then(results => {
 results.forEach((result, index) => {
 if (result) {
 fs.writeFileSync(`screenshot-${index}.png`, result.buffer);
 }
 });
});
Be mindful of rate limits (100 requests/hour). Consider adding delays between batches for large workloads.

Error Handling

JavaScript with Retry

async function captureWithRetry(url, maxRetries = 3) {
 for (let attempt = 1; attempt <= maxRetries; attempt++) {
 try {
 const response = await fetch('https://snappkit.com/api/screenshot', {
 method:'POST',
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 body: JSON.stringify({ url })
 });

 if (!response.ok) {
 const error = await response.json();

 // Don't retry client errors (4xx except 429)
 if (response.status >= 400 && response.status < 500 && response.status !== 429) {
 throw new Error(`Client error: ${error.error}`);
 }

 // Retry server errors (5xx) and rate limits (429)
 if (attempt < maxRetries) {
 const delay = Math.pow(2, attempt) * 1000;
 console.log(`Retry ${attempt}/${maxRetries} after ${delay}ms`);
 await new Promise(resolve => setTimeout(resolve, delay));
 continue;
 }

 throw new Error(`Failed after ${maxRetries} attempts: ${error.error}`);
 }

 return Buffer.from(await response.arrayBuffer());

 } catch (err) {
 if (attempt === maxRetries) throw err;
 }
 }
}

Python with Error Details

def capture_with_error_handling(url):
 try:
 response = requests.post(
'https://snappkit.com/api/screenshot',
 headers={
'Authorization': f'Bearer {os.environ["API_KEY"]}',
'Content-Type':'application/json'
 },
 json={'url': url}
 )

 if response.status_code == 400:
 error = response.json()
 print(f"Invalid request: {error}")
 return None

 elif response.status_code == 401:
 print("Authentication failed. Check your API key.")
 return None

 elif response.status_code == 402:
 error = response.json()
 print(f"Insufficient credits: {error['required']} needed, {error['available']} available")
 return None

 elif response.status_code == 429:
 print("Rate limit exceeded. Wait and try again.")
 return None

 elif response.status_code == 500:
 error = response.json()
 print(f"Server error: {error.get('message','Unknown error')}")
 return None

 response.raise_for_status()
 return response.content

 except requests.RequestException as e:
 print(f"Request failed: {e}")
 return None

Using Axios (Alternative)

Prefer axios over fetch? Here's how to use it:

Installation: npm install axios

Basic Screenshot with Axios

const axios = require('axios');
const fs = require('fs');

async function captureScreenshot(url) {
 try {
 const response = await axios.post(
'https://snappkit.com/api/screenshot',
 { url },
 {
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 responseType:'arraybuffer' // Important for binary data
 }
 );

 fs.writeFileSync('screenshot.png', response.data);
 console.log('Screenshot saved!');
 } catch (error) {
 if (error.response) {
 console.error(`HTTP ${error.response.status}: ${error.response.data}`);
 } else {
 console.error(`Request failed: ${error.message}`);
 }
 }
}

captureScreenshot('https://example.com');

Full-Page Screenshot with Axios

async function captureFullPageAxios(url) {
 const response = await axios.post(
'https://snappkit.com/api/screenshot',
 {
 url,
 fullPage: true,
 format:'webp',
 quality: 85
 },
 {
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 responseType:'arraybuffer'
 }
 );

 return Buffer.from(response.data);
}

Axios with Retry Logic

const axios = require('axios');
const axiosRetry = require('axios-retry');

// Configure axios with automatic retries
axiosRetry(axios, {
 retries: 3,
 retryDelay: axiosRetry.exponentialDelay,
 retryCondition: (error) => {
 // Retry on network errors, 5xx, and 429 (rate limit)
 return axiosRetry.isNetworkOrIdempotentRequestError(error) ||
 error.response?.status === 429;
 }
});

async function captureWithRetry(url) {
 try {
 const response = await axios.post(
'https://snappkit.com/api/screenshot',
 { url },
 {
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 responseType:'arraybuffer'
 }
 );

 return Buffer.from(response.data);
 } catch (error) {
 console.error('Failed after retries:', error.message);
 throw error;
 }
}
Installation for retry support:npm install axios axios-retry

TypeScript with Type Safety

interface ScreenshotOptions {
 url: string;
 width?: number;
 height?: number;
 format?:'png' |'jpeg' |'webp';
 quality?: number;
 fullPage?: boolean;
 device?:'mobile' |'tablet' |'desktop';
 delay?: number;
}

interface ScreenshotError {
 error: string;
 details?: any[];
 url?: string;
 message?: string;
}

async function captureScreenshot(
 options: ScreenshotOptions
): Promise<Buffer> {
 const response = await fetch('https://snappkit.com/api/screenshot', {
 method:'POST',
 headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type':'application/json',
 },
 body: JSON.stringify(options)
 });

 if (!response.ok) {
 const error: ScreenshotError = await response.json();
 throw new Error(`HTTP ${response.status}: ${error.error}`);
 }

 return Buffer.from(await response.arrayBuffer());
}

// Usage
const screenshot = await captureScreenshot({
 url:'https://example.com',
 width: 1920,
 height: 1080,
 format:'png',
 fullPage: true
});

Managing API Keys Programmatically

You can also manage your API keys via code. This is useful for automation, CI/CD pipelines, or building admin interfaces.

Create a New API Key

curl -X POST https://snappkit.com/api/keys \
 -H"Authorization: Bearer YOUR_CLERK_TOKEN" \
 -H"Content-Type: application/json" \
 -d'{"name":"CI/CD Pipeline"}'

List All API Keys

const response = await fetch('https://snappkit.com/api/keys', {
 headers: {
'Authorization':'Bearer YOUR_CLERK_TOKEN'
 }
});

const { keys } = await response.json();
keys.forEach(key => {
 console.log(`${key.name}: ${key.key} (last used: ${key.lastUsed})`);
});

Revoke an API Key

const keyId ='key_abc123';

await fetch(`https://snappkit.com/api/keys/${keyId}`, {
 method:'PATCH',
 headers: {
'Authorization':'Bearer YOUR_CLERK_TOKEN',
'Content-Type':'application/json'
 },
 body: JSON.stringify({ isActive: false })
});

console.log('Key revoked successfully');

Learn More

For complete API key management documentation including error handling and response formats, visit theAuthentication Guide.

Need More Help?

Check theAPI Referencefor complete parameter documentation, or try theInteractive Playgroundto test requests without writing code.