Code Examples

These examples demonstrate how to use the ScreenshotPro API in various programming languages. Each example shows how to take a screenshot and check its status.

cURL

The simplest way to test our API is using cURL from the command line.

Take a Screenshot

curl -X POST "https://api.screenshotpro.com/api/screenshot" \
    -H "X-API-Key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
        "url": "https://example.com",
        "format": "png",
        "fullPage": true,
        "viewport": "1280x720"
    }'

Check Screenshot Status

curl "https://api.screenshotpro.com/api/screenshot/SCREENSHOT_ID" \
    -H "X-API-Key: YOUR_API_KEY"

PHP

Using PHP with cURL or Guzzle HTTP client.

Take a Screenshot with cURL

<?php
// Capture screenshot using cURL
$apiKey = 'YOUR_API_KEY';
$url = 'https://api.screenshotpro.com/api/screenshot';

$data = [
    'url' => 'https://example.com',
    'format' => 'png',
    'fullPage' => true,
    'viewport' => '1280x720'
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'X-API-Key: ' . $apiKey
]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
$screenshotId = $result['data']['id'];

echo "Screenshot ID: " . $screenshotId;
?>

Using Guzzle HTTP Client

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();
$apiKey = 'YOUR_API_KEY';

// Take a screenshot
$response = $client->post('https://api.screenshotpro.com/api/screenshot', [
    'headers' => [
        'X-API-Key' => $apiKey,
        'Content-Type' => 'application/json',
    ],
    'json' => [
        'url' => 'https://example.com',
        'format' => 'png',
        'fullPage' => true,
        'viewport' => '1280x720'
    ]
]);

$result = json_decode($response->getBody(), true);
$screenshotId = $result['data']['id'];

// Check screenshot status
$statusResponse = $client->get('https://api.screenshotpro.com/api/screenshot/' . $screenshotId, [
    'headers' => [
        'X-API-Key' => $apiKey
    ]
]);

$statusResult = json_decode($statusResponse->getBody(), true);
echo "Screenshot status: " . $statusResult['data']['status'];
?>

Node.js

Using Node.js with Axios.

const axios = require('axios');

const apiKey = 'YOUR_API_KEY';
const baseUrl = 'https://api.screenshotpro.com/api';

// Take a screenshot
async function takeScreenshot() {
  try {
    const response = await axios.post(`${baseUrl}/screenshot`, {
      url: 'https://example.com',
      format: 'png',
      fullPage: true,
      viewport: '1280x720'
    }, {
      headers: {
        'X-API-Key': apiKey,
        'Content-Type': 'application/json'
      }
    });
    
    const screenshotId = response.data.data.id;
    console.log(`Screenshot ID: ${screenshotId}`);
    
    // Check status
    return await checkStatus(screenshotId);
  } catch (error) {
    console.error('Error taking screenshot:', error.response?.data || error.message);
  }
}

// Check screenshot status
async function checkStatus(id) {
  try {
    const response = await axios.get(`${baseUrl}/screenshot/${id}`, {
      headers: {
        'X-API-Key': apiKey
      }
    });
    
    const status = response.data.data.status;
    console.log(`Screenshot status: ${status}`);
    
    if (status === 'completed') {
      console.log(`URL: ${response.data.data.url}`);
    } else if (status === 'pending' || status === 'processing') {
      // Poll again after 2 seconds
      console.log('Waiting for screenshot to complete...');
      setTimeout(() => checkStatus(id), 2000);
    }
    
    return response.data;
  } catch (error) {
    console.error('Error checking status:', error.response?.data || error.message);
  }
}

// Run the example
takeScreenshot();

Python

Using Python with the requests library.

import requests
import json
import time

api_key = 'YOUR_API_KEY'
base_url = 'https://api.screenshotpro.com/api'

headers = {
    'X-API-Key': api_key,
    'Content-Type': 'application/json'
}

# Take a screenshot
def take_screenshot():
    url = f'{base_url}/screenshot'
    data = {
        'url': 'https://example.com',
        'format': 'png',
        'fullPage': True,
        'viewport': '1280x720'
    }
    
    response = requests.post(url, headers=headers, json=data)
    result = response.json()
    
    if response.status_code == 200:
        screenshot_id = result['data']['id']
        print(f'Screenshot ID: {screenshot_id}')
        return check_status(screenshot_id)
    else:
        print(f'Error: {result["message"]}')
        return None

# Check screenshot status
def check_status(screenshot_id):
    url = f'{base_url}/screenshot/{screenshot_id}'
    
    response = requests.get(url, headers=headers)
    result = response.json()
    
    if response.status_code == 200:
        status = result['data']['status']
        print(f'Screenshot status: {status}')
        
        if status == 'completed':
            print(f'URL: {result["data"]["url"]}')
            return result
        elif status in ['pending', 'processing']:
            print('Waiting for screenshot to complete...')
            time.sleep(2)
            return check_status(screenshot_id)
    else:
        print(f'Error: {result["message"]}')
    
    return None

# Run the example
if __name__ == '__main__':
    take_screenshot()

Ruby

Using Ruby with the HTTParty gem.

require 'httparty'
require 'json'

class ScreenshotClient
  include HTTParty
  base_uri 'https://api.screenshotpro.com/api'
  
  def initialize(api_key)
    @api_key = api_key
    @headers = {
      'X-API-Key' => @api_key,
      'Content-Type' => 'application/json'
    }
  end
  
  def take_screenshot
    options = {
      headers: @headers,
      body: {
        url: 'https://example.com',
        format: 'png',
        fullPage: true,
        viewport: '1280x720'
      }.to_json
    }
    
    response = self.class.post('/screenshot', options)
    result = JSON.parse(response.body)
    
    if response.code == 200
      screenshot_id = result['data']['id']
      puts "Screenshot ID: #{screenshot_id}"
      check_status(screenshot_id)
    else
      puts "Error: #{result['message']}"
      nil
    end
  end
  
  def check_status(screenshot_id)
    options = { headers: @headers }
    response = self.class.get("/screenshot/#{screenshot_id}", options)
    result = JSON.parse(response.body)
    
    if response.code == 200
      status = result['data']['status']
      puts "Screenshot status: #{status}"
      
      if status == 'completed'
        puts "URL: #{result['data']['url']}"
        result
      elsif status == 'pending' || status == 'processing'
        puts "Waiting for screenshot to complete..."
        sleep 2
        check_status(screenshot_id)
      end
    else
      puts "Error: #{result['message']}"
      nil
    end
  end
end

# Run the example
client = ScreenshotClient.new('YOUR_API_KEY')
client.take_screenshot

Java

Using Java with OkHttp and Gson.

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ScreenshotClient {
    private static final String BASE_URL = "https://api.screenshotpro.com/api";
    private static final String API_KEY = "YOUR_API_KEY";
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();
    private static final Gson gson = new Gson();
    
    public static void main(String[] args) {
        try {
            String screenshotId = takeScreenshot();
            if (screenshotId != null) {
                checkStatus(screenshotId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static String takeScreenshot() throws IOException {
        JsonObject json = new JsonObject();
        json.addProperty("url", "https://example.com");
        json.addProperty("format", "png");
        json.addProperty("fullPage", true);
        json.addProperty("viewport", "1280x720");
        
        RequestBody body = RequestBody.create(
                MediaType.parse("application/json"), json.toString());
        
        Request request = new Request.Builder()
                .url(BASE_URL + "/screenshot")
                .addHeader("X-API-Key", API_KEY)
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
        
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                System.out.println("Error: " + response.code());
                return null;
            }
            
            String responseBody = response.body().string();
            JsonObject result = gson.fromJson(responseBody, JsonObject.class);
            
            String screenshotId = result.getAsJsonObject("data").get("id").getAsString();
            System.out.println("Screenshot ID: " + screenshotId);
            return screenshotId;
        }
    }
    
    private static void checkStatus(String screenshotId) throws IOException, InterruptedException {
        Request request = new Request.Builder()
                .url(BASE_URL + "/screenshot/" + screenshotId)
                .addHeader("X-API-Key", API_KEY)
                .get()
                .build();
        
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            System.out.println("Error: " + response.code());
            return;
        }
        
        String responseBody = response.body().string();
        JsonObject result = gson.fromJson(responseBody, JsonObject.class);
        
        String status = result.getAsJsonObject("data").get("status").getAsString();
        System.out.println("Screenshot status: " + status);
        
        if (status.equals("completed")) {
            String url = result.getAsJsonObject("data").get("url").getAsString();
            System.out.println("URL: " + url);
        } else if (status.equals("pending") || status.equals("processing")) {
            System.out.println("Waiting for screenshot to complete...");
            TimeUnit.SECONDS.sleep(2);
            checkStatus(screenshotId);
        }
    }
}

C#

Using C# with HttpClient and Newtonsoft.Json.

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ScreenshotProExample
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();
        private const string BaseUrl = "https://api.screenshotpro.com/api";
        private const string ApiKey = "YOUR_API_KEY";

        static async Task Main(string[] args)
        {
            client.DefaultRequestHeaders.Add("X-API-Key", ApiKey);
            
            try
            {
                string screenshotId = await TakeScreenshot();
                if (screenshotId != null)
                {
                    await CheckStatus(screenshotId);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
            
            Console.ReadLine();
        }

        static async Task TakeScreenshot()
        {
            var payload = new
            {
                url = "https://example.com",
                format = "png",
                fullPage = true,
                viewport = "1280x720"
            };

            string json = JsonConvert.SerializeObject(payload);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await client.PostAsync($"{BaseUrl}/screenshot", content);
            string responseBody = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                dynamic result = JObject.Parse(responseBody);
                string screenshotId = result.data.id;
                Console.WriteLine($"Screenshot ID: {screenshotId}");
                return screenshotId;
            }
            else
            {
                dynamic result = JObject.Parse(responseBody);
                Console.WriteLine($"Error: {result.message}");
                return null;
            }
        }

        static async Task CheckStatus(string screenshotId)
        {
            var response = await client.GetAsync($"{BaseUrl}/screenshot/{screenshotId}");
            string responseBody = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                dynamic result = JObject.Parse(responseBody);
                string status = result.data.status;
                Console.WriteLine($"Screenshot status: {status}");

                if (status == "completed")
                {
                    Console.WriteLine($"URL: {result.data.url}");
                }
                else if (status == "pending" || status == "processing")
                {
                    Console.WriteLine("Waiting for screenshot to complete...");
                    await Task.Delay(2000);
                    await CheckStatus(screenshotId);
                }
            }
            else
            {
                dynamic result = JObject.Parse(responseBody);
                Console.WriteLine($"Error: {result.message}");
            }
        }
    }
}

Go

Using Go with net/http package.

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

const (
	baseURL = "https://api.screenshotpro.com/api"
	apiKey  = "YOUR_API_KEY"
)

type ScreenshotRequest struct {
	URL       string `json:"url"`
	Format    string `json:"format"`
	FullPage  bool   `json:"fullPage"`
	Viewport  string `json:"viewport"`
}

type ScreenshotResponse struct {
	Success bool `json:"success"`
	Data    struct {
		ID     string `json:"id"`
		Status string `json:"status"`
		URL    string `json:"url,omitempty"`
	} `json:"data"`
	Message string `json:"message"`
}

func main() {
	screenshotID, err := takeScreenshot()
	if err != nil {
		fmt.Printf("Error taking screenshot: %v\n", err)
		return
	}
	
	if screenshotID != "" {
		checkStatus(screenshotID)
	}
}

func takeScreenshot() (string, error) {
	reqData := ScreenshotRequest{
		URL:       "https://example.com",
		Format:    "png",
		FullPage:  true,
		Viewport:  "1280x720",
	}
	
	reqBody, err := json.Marshal(reqData)
	if err != nil {
		return "", err
	}
	
	req, err := http.NewRequest("POST", baseURL+"/screenshot", bytes.NewBuffer(reqBody))
	if err != nil {
		return "", err
	}
	
	req.Header.Set("X-API-Key", apiKey)
	req.Header.Set("Content-Type", "application/json")
	
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	
	var result ScreenshotResponse
	err = json.Unmarshal(body, &result)
	if err != nil {
		return "", err
	}
	
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("API error: %s", result.Message)
	}
	
	screenshotID := result.Data.ID
	fmt.Printf("Screenshot ID: %s\n", screenshotID)
	return screenshotID, nil
}

func checkStatus(screenshotID string) error {
	req, err := http.NewRequest("GET", baseURL+"/screenshot/"+screenshotID, nil)
	if err != nil {
		return err
	}
	
	req.Header.Set("X-API-Key", apiKey)
	
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	
	var result ScreenshotResponse
	err = json.Unmarshal(body, &result)
	if err != nil {
		return err
	}
	
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("API error: %s", result.Message)
	}
	
	status := result.Data.Status
	fmt.Printf("Screenshot status: %s\n", status)
	
	if status == "completed" {
		fmt.Printf("URL: %s\n", result.Data.URL)
		return nil
	} else if status == "pending" || status == "processing" {
		fmt.Println("Waiting for screenshot to complete...")
		time.Sleep(2 * time.Second)
		return checkStatus(screenshotID)
	}
	
	return nil
}