Code Examples

Take Screenshots with Rust

Ready-to-copy Rust code for capturing website screenshots, generating PDFs, and processing pages at scale. Uses reqwest.

Quick Start

Screenshot in Rust — minimal example

The simplest way to capture a screenshot. Just a URL and your API key.

Rustquickstart
let bytes = reqwest::get(
    "https://api.screenshotdev.com/v1/screenshot?url=https://example.com&access_key=YOUR_ACCESS_KEY"
).await?.bytes().await?;
tokio::fs::write("screenshot.png", &bytes).await?;
Full Example

Production-ready Rust script

Complete working script with options for viewport, format, full page capture, and error handling.

Rustfull example
use reqwest::Client;
use std::error::Error;

const API_KEY: &str = "YOUR_ACCESS_KEY";
const BASE_URL: &str = "https://api.screenshotdev.com/v1/screenshot";

async fn take_screenshot(
    client: &Client,
    url: &str,
    format: &str,
    width: u32,
    full_page: bool,
) -> Result<Vec<u8>, Box<dyn Error>> {
    let resp = client
        .get(BASE_URL)
        .query(&[
            ("url", url),
            ("access_key", API_KEY),
            ("format", format),
            ("width", &width.to_string()),
            ("full_page", &full_page.to_string()),
        ])
        .send()
        .await?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await?;
        return Err(format!("Screenshot failed ({status}): {body}").into());
    }
    Ok(resp.bytes().await?.to_vec())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let client = Client::new();
    let img = take_screenshot(&client, "https://example.com", "webp", 1440, true).await?;
    tokio::fs::write("screenshot.webp", &img).await?;
    println!("Saved screenshot.webp ({} bytes)", img.len());
    Ok(())
}
Advanced

More Rust examples

PDF generation, batch processing, webhooks, CSS/JS injection, and S3 upload.

PDF Generation

Rustpdf
let client = Client::new();
let resp = client
    .get("https://api.screenshotdev.com/v1/pdf")
    .query(&[
        ("url", "https://example.com"),
        ("access_key", "YOUR_ACCESS_KEY"),
        ("format", "a4"),
        ("landscape", "false"),
        ("margin", "20px"),
    ])
    .send()
    .await?;
let bytes = resp.bytes().await?;
tokio::fs::write("page.pdf", &bytes).await?;

Batch Screenshots

Rustbatch
use futures::future::join_all;

let urls = vec![
    "https://example.com",
    "https://github.com",
    "https://news.ycombinator.com",
];
let client = Client::new();

let tasks: Vec<_> = urls.into_iter().map(|url| {
    let client = client.clone();
    tokio::spawn(async move {
        let img = take_screenshot(&client, url, "webp", 1280, false).await?;
        let host = url.split("//").nth(1).unwrap_or(url);
        let filename = format!("{host}.webp");
        tokio::fs::write(&filename, &img).await?;
        println!("  {filename} ({} bytes)", img.len());
        Ok::<_, Box<dyn Error + Send + Sync>>(())
    })
}).collect();

join_all(tasks).await;

Async with Webhooks

Rustwebhooks
use serde_json::json;

let client = Client::new();
let resp = client
    .post("https://api.screenshotdev.com/v1/screenshot")
    .json(&json!({
        "url": "https://example.com",
        "access_key": "YOUR_ACCESS_KEY",
        "webhook_url": "https://your-app.com/api/webhooks/screenshot",
        "format": "webp",
        "full_page": true,
    }))
    .send()
    .await?;
let job: serde_json::Value = resp.json().await?;
println!("Job queued: {}", job["id"]);

Custom CSS/JS Injection

Rustinject
let resp = client
    .get(BASE_URL)
    .query(&[
        ("url", "https://example.com"),
        ("access_key", API_KEY),
        ("inject_css", "body { font-family: 'Inter', sans-serif; } .ad { display: none; }"),
        ("inject_js", "document.querySelectorAll('[data-cookie-banner]').forEach(el => el.remove())"),
        ("block_ads", "true"),
    ])
    .send()
    .await?;
let bytes = resp.bytes().await?;
tokio::fs::write("clean.webp", &bytes).await?;

S3 Upload

Rusts3
use aws_sdk_s3::Client as S3Client;
use aws_sdk_s3::primitives::ByteStream;

// 1. Capture
let img = take_screenshot(&client, "https://example.com", "webp", 1280, false).await?;

// 2. Upload
let config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
let s3 = S3Client::new(&config);
s3.put_object()
    .bucket("my-screenshots")
    .key("captures/example-com.webp")
    .body(ByteStream::from(img))
    .content_type("image/webp")
    .send()
    .await?;

Try it live

Test the API in the interactive playground — pre-filled with Rust snippets.

Setup

Installation

Install the HTTP library used in the examples above.

Terminalinstall
cargo add reqwest tokio --features "reqwest/json,tokio/full"

Uses reqwest. Any HTTP client that supports GET requests will work.

More Examples

Code examples in other languages

Start capturing screenshots
with Rust today.

100 free API calls per month. No credit card. First screenshot in under 30 seconds.

Take Screenshots with Rust — ScreenshotDEV