Help CenterCode Examples
Step 4 of 5

Code Examples That Work

Copy, paste, and start generating screenshots in your favorite language. These examples actually work - no guessing needed!

🚀 Quick Start (Copy & Run)

Pick your favorite language and you'll have screenshots working in under 2 minutes. Just replace YOUR_API_KEY and YOUR_SITE_ID!

Command Line (cURL)

Perfect for testing and automation

curl -X POST https://urlpixel.com/api/screenshot \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com",
    "site_id": "YOUR_SITE_ID",
    "quality": "high"
  }'

JavaScript/Node.js

For web apps and Node.js projects

const response = await fetch('https://urlpixel.com/api/screenshot', {
  method: 'POST',
  headers: {
    'X-API-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    url: 'https://example.com',
    site_id: 'YOUR_SITE_ID',
    quality: 'high'
  })
});

const data = await response.json();
console.log('Screenshot URL:', data.url);

📚 Complete Examples by Language

Ready-to-use examples with error handling and best practices. Just what you need without the fluff!

JavaScript/Node.js (Complete Example)

screenshot-generator.js
// screenshot-generator.js
const fetch = require('node-fetch'); // npm install node-fetch

async function generateScreenshot(url, siteId, quality = 'high') {
  try {
    const response = await fetch('https://urlpixel.com/api/screenshot', {
      method: 'POST',
      headers: {
        'X-API-Key': process.env.URLPIXEL_API_KEY, // Store your key safely!
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        url: url,
        site_id: siteId,
        quality: quality
      })
    });

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

    const data = await response.json();
    
    if (data.success) {
      console.log('✅ Screenshot generated!');
      console.log('📸 URL:', data.url);
      console.log('📊 Size:', Math.round(data.file_size / 1024) + 'KB');
      return data;
    } else {
      throw new Error(data.error || 'Unknown error');
    }
  } catch (error) {
    console.error('❌ Error generating screenshot:', error.message);
    throw error;
  }
}

// Usage example
generateScreenshot('https://example.com', 'your-site-id', 'high')
  .then(result => console.log('Done!', result))
  .catch(error => console.error('Failed:', error));

Complete Node.js example with error handling and async/await

Python (requests library)

screenshot_generator.py
# screenshot_generator.py
import requests
import os
import json

def generate_screenshot(url, site_id, quality='high'):
    """
    Generate a screenshot using URLPixel API
    
    Args:
        url (str): The website URL to screenshot
        site_id (str): Your URLPixel site ID
        quality (str): Image quality - 'standard', 'high', 'retina', or 'mobile'
    
    Returns:
        dict: API response with screenshot details
    """
    
    # Get API key from environment variable (recommended!)
    api_key = os.getenv('URLPIXEL_API_KEY')
    if not api_key:
        raise ValueError("Please set URLPIXEL_API_KEY environment variable")
    
    # API endpoint and headers
    endpoint = 'https://urlpixel.com/api/screenshot'
    headers = {
        'X-API-Key': api_key,
        'Content-Type': 'application/json'
    }
    
    # Request payload
    payload = {
        'url': url,
        'site_id': site_id,
        'quality': quality
    }
    
    try:
        print(f"📸 Generating screenshot for: {url}")
        response = requests.post(endpoint, headers=headers, json=payload)
        response.raise_for_status()  # Raises an HTTPError for bad responses
        
        data = response.json()
        
        if data.get('success'):
            print("✅ Screenshot generated successfully!")
            print(f"📱 Screenshot URL: {data['url']}")
            print(f"📊 File size: {round(data['file_size'] / 1024, 1)}KB")
            return data
        else:
            raise Exception(data.get('error', 'Unknown error occurred'))
            
    except requests.exceptions.RequestException as e:
        print(f"❌ Network error: {e}")
        raise
    except Exception as e:
        print(f"❌ Error: {e}")
        raise

# Example usage
if __name__ == "__main__":
    try:
        result = generate_screenshot(
            url='https://example.com',
            site_id='your-site-id',
            quality='high'
        )
        print("🎉 Success! Screenshot saved to:", result['url'])
    except Exception as e:
        print(f"💥 Failed to generate screenshot: {e}")

Python example using the popular requests library

PHP (cURL)

screenshot_generator.php
<?php
// screenshot_generator.php

function generateScreenshot($url, $siteId, $quality = 'high') {
    // Get API key from environment or config
    $apiKey = $_ENV['URLPIXEL_API_KEY'] ?? getenv('URLPIXEL_API_KEY');
    
    if (!$apiKey) {
        throw new Exception('URLPIXEL_API_KEY environment variable not set');
    }
    
    // Prepare the data
    $data = json_encode([
        'url' => $url,
        'site_id' => $siteId,
        'quality' => $quality
    ]);
    
    // Initialize cURL
    $ch = curl_init();
    
    curl_setopt_array($ch, [
        CURLOPT_URL => 'https://urlpixel.com/api/screenshot',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_HTTPHEADER => [
            'X-API-Key: ' . $apiKey,
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data)
        ],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    // Execute request
    echo "📸 Generating screenshot for: $url\n";
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    if (curl_error($ch)) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception("cURL error: $error");
    }
    
    curl_close($ch);
    
    // Parse response
    $data = json_decode($response, true);
    
    if ($httpCode !== 200) {
        throw new Exception("HTTP error $httpCode: " . ($data['error'] ?? 'Unknown error'));
    }
    
    if ($data['success']) {
        echo "✅ Screenshot generated successfully!\n";
        echo "📱 Screenshot URL: " . $data['url'] . "\n";
        echo "📊 File size: " . round($data['file_size'] / 1024, 1) . "KB\n";
        return $data;
    } else {
        throw new Exception($data['error'] ?? 'Unknown error occurred');
    }
}

// Example usage
try {
    $result = generateScreenshot(
        'https://example.com',
        'your-site-id',
        'high'
    );
    echo "🎉 Success! Screenshot available at: " . $result['url'] . "\n";
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
}
?>

PHP example using cURL - works with any PHP version

🔧 Common Patterns & Tips

Different Quality Settings

standard1280x720, ~150KB
high1920x1080, ~300KB
retina2560x1440, ~500KB
mobile375x667, ~100KB

💡 Use standard for most cases, high for portfolios,mobile for responsive testing!

Error Handling Tips

  • Always check for success: true
  • Handle HTTP status codes (401, 429, 500)
  • Set reasonable timeouts (30 seconds)
  • Store API keys in environment variables

🔒 Security tip: Never hardcode API keys in your source code!

🚨 Common Issues & Solutions

Getting 401 Unauthorized error

Solution: Check that your API key is correct and included in the 'X-API-Key' header. Make sure there are no extra spaces!

Request timing out

Solution: Increase your timeout to 30+ seconds. Some websites take time to load fully before we can capture them.

Getting 429 Too Many Requests

Solution: You've hit your plan's rate limit. Check your usage in the dashboard or upgrade your plan.

Screenshot looks broken or blank

Solution: The website might have bot protection. Try a different URL or contact us if it's a common site.