Python Screenshot API: Tutorial with requests, httpx and Celery
A hands-on Python tutorial for capturing website screenshots programmatically, from a single requests call to async batches, durable jobs, and signed webhooks in Django or Flask apps.
Python developers often need website screenshots for documentation, monitoring, reports or ML datasets. Selenium and Playwright can take them, but you then own the browsers, fonts, timeouts and servers. A screenshot API turns that into one HTTP request.
This tutorial covers Python patterns: scripts, data pipelines, and Django, Flask, FastAPI and Celery apps. Every request body below uses fields the API accepts. The schema is strict, so a misspelled or unsupported field returns 400.
Libraries referenced: Requests for synchronous code, HTTPX for async, Celery for background tasks, and Flask for the webhook example. For every parameter, see the screenshot API reference.
Prerequisites
- Python 3.9 or later
- A Screenshotly API key. The Free plan includes 100 captures in total.
pip install requests, plushttpxfor the async section
Keep the key in the environment, not in code:
export SCREENSHOTLY_API_KEY="your_api_key_here"
The API contract
| Item | Value |
|---|---|
| Endpoint | POST https://screenshotly.app/api/screenshot |
| Auth | x-api-key: YOUR_KEY header (Authorization: Bearer YOUR_KEY also works) |
| Body | JSON, max 64 KB, unknown fields rejected |
| Success | 200 with the image or PDF bytes |
| Errors | JSON {"error": "...", "message": "..."} with 400, 401, 403, 413, 429, 500 or 503 |
A reusable capture function
This function owns the key, the timeout and the retry rules. The rest of the tutorial builds on it.
# screenshotly_client.py
import os
import time
from typing import Any, Dict, Tuple
import requests
API_URL = "https://screenshotly.app/api/screenshot"
MAX_RETRY_WAIT_SECONDS = 60
session = requests.Session()
class ScreenshotlyError(Exception):
def __init__(self, status: int, body: Dict[str, Any], retry_after: int = 0):
message = body.get("message") or body.get("error") or "request failed"
super().__init__(f"Screenshotly {status}: {message}")
self.status = status
self.body = body
self.retry_after = retry_after
def capture(options: Dict[str, Any], retries: int = 3, timeout: Tuple[float, float] = (5, 60)) -> bytes:
"""POST a capture request and return the image/PDF bytes.
timeout is (connect, read) seconds. Captures can take tens of seconds.
"""
api_key = os.environ["SCREENSHOTLY_API_KEY"]
for attempt in range(retries + 1):
try:
response = session.post(
API_URL,
json=options,
headers={"x-api-key": api_key},
timeout=timeout,
)
except (requests.ConnectionError, requests.Timeout):
if attempt == retries:
raise
time.sleep(2 ** attempt)
continue
if response.ok:
return response.content
try:
body = response.json()
except ValueError:
body = {"error": response.text}
retry_after = int(response.headers.get("Retry-After") or 0)
if response.status_code == 429:
# Short wait = per-minute limit. Long wait = monthly quota used up.
retryable = retry_after <= MAX_RETRY_WAIT_SECONDS
else:
retryable = response.status_code >= 500
if not retryable or attempt == retries:
raise ScreenshotlyError(response.status_code, body, retry_after)
time.sleep(retry_after if response.status_code == 429 else 2 ** attempt)
raise RuntimeError("unreachable")
The retry rules follow the API's behavior:
400,401,403,413: never retried.403with"error": "Plan upgrade required"includesminimumPlan, which names the plan the feature needs.500/503and connection errors: retried with exponential backoff. Failed captures don't consume quota.429: retried only for short waits. Per-minute throughput is 5 requests on Free, 40 on Basic, 80 on Growth and 200 on Scale. When the monthly quota is exhausted,Retry-Aftercounts down to the reset, which can be days away. Don't sleep through that in a worker.
Tenacity can express the same policy if you prefer decorators. Keep the "don't retry 4xx except short 429s" rule either way.
Basic screenshot capture
from pathlib import Path
from screenshotly_client import capture
image = capture({"url": "https://example.com", "device": "desktop", "format": "png"})
Path("example.png").write_bytes(image)
print(f"Saved {len(image)} bytes")
The API loads the page in a real browser, waits for it to load and returns the encoded image.
Device presets and custom viewports
The device presets are desktop (1920×1080), laptop (1366×768), tablet (768×1024) and mobile (375×812):
from pathlib import Path
from screenshotly_client import capture
for device in ["desktop", "tablet", "mobile"]:
Path(f"example_{device}.png").write_bytes(
capture({"url": "https://example.com", "device": device})
)
# Creates example_desktop.png, example_tablet.png, example_mobile.png
For exact dimensions, send top-level width and height (320–3840 × 240–3840). There is no nested viewport object. Add deviceScaleFactor (1–3) for high-DPI output:
from pathlib import Path
from screenshotly_client import capture
sizes = {"fullhd": (1920, 1080), "qhd": (2560, 1440), "phone": (375, 812)}
for name, (width, height) in sizes.items():
Path(f"{name}.png").write_bytes(
capture({"url": "https://example.com", "width": width, "height": height})
)
retina = capture({"url": "https://example.com", "width": 1440, "height": 900, "deviceScaleFactor": 2})
Full-page captures and waiting for content
from pathlib import Path
from screenshotly_client import capture
image = capture({
"url": "https://example.com/landing",
"fullPage": True,
"waitForSelector": "main", # wait until this element exists
"waitForNetworkIdle": True, # and network activity settles
"format": "webp",
"quality": 80,
})
Path("landing_full.webp").write_bytes(image)
delay (0–10,000 ms) gives late animations extra time. darkMode, timezone and userAgent control the rendering context, and selector captures a single element.
AI element removal (Growth plan and above)
Remove cookie banners, chat widgets and similar overlays before the capture:
from pathlib import Path
from screenshotly_client import capture
image = capture({
"url": "https://example.com",
"aiRemoval": {
"enabled": True,
"types": ["cookie-banner", "chat-widget", "newsletter"],
},
"hideSelectors": ["#promo-bar"], # also Growth+: hide elements you already know about
})
Path("clean.png").write_bytes(image)
Supported types are cookie-banner, newsletter, chat-widget, social-overlay and ad. confidence (0–1, default 0.8) adjusts how aggressive the removal is. blockAds: True is available on every plan.
Device mockups (Growth plan and above)
mockup is a template ID string. The options are browser-light, browser-dark, browser-minimal, iphone-14, ipad-pro and macbook-pro:
from pathlib import Path
from screenshotly_client import capture
for template in ["macbook-pro", "browser-dark"]:
Path(f"marketing_{template}.png").write_bytes(
capture({"url": "https://example.com", "mockup": template})
)
On Free or Basic, AI removal and mockup requests return 403 with "minimumPlan": "growth". With capture(), that surfaces as a ScreenshotlyError whose .status is 403.
PDF generation (Basic plan and above)
from pathlib import Path
from screenshotly_client import capture
pdf = capture({"url": "https://example.com/report", "format": "pdf"})
Path("report.pdf").write_bytes(pdf)
PDF output is A4 with 1 cm margins, with backgrounds printed. Page size, orientation, margins and headers/footers are fixed, so there is no pdfOptions field. If you need Letter or landscape output, generate the PDF yourself.
Authenticated pages (Basic plan and above)
Pass session cookies or request headers for the target site:
import os
from pathlib import Path
from screenshotly_client import capture
image = capture({
"url": "https://app.example.com/dashboard",
"cookies": [{
"name": "session",
"value": os.environ["DASHBOARD_SESSION_COOKIE"],
"domain": "app.example.com",
"secure": True,
"httpOnly": True,
}],
})
Path("dashboard.png").write_bytes(image)
Cookie values are sent to Screenshotly so the browser can use them. Use a dedicated, read-only account whose session you can revoke, not a personal admin login. The authenticated capture guide covers this in more depth.
Concurrent batches with httpx
For a list of URLs, such as a sitemap or a column in a DataFrame, use one httpx.AsyncClient and a semaphore. The 429 handling mirrors the sync client:
# batch_capture.py
import asyncio
import os
from pathlib import Path
from typing import List, Optional, Tuple
import httpx
API_URL = "https://screenshotly.app/api/screenshot"
MAX_RETRY_WAIT_SECONDS = 60
async def capture_one(client: httpx.AsyncClient, sem: asyncio.Semaphore, url: str) -> Tuple[str, Optional[bytes], str]:
async with sem:
for attempt in range(4):
response = await client.post(API_URL, json={"url": url, "format": "webp", "quality": 80})
if response.status_code == 200:
return url, response.content, "ok"
retry_after = int(response.headers.get("Retry-After") or 0)
if response.status_code == 429 and retry_after <= MAX_RETRY_WAIT_SECONDS:
await asyncio.sleep(retry_after)
elif response.status_code >= 500:
await asyncio.sleep(2 ** attempt)
else:
return url, None, f"{response.status_code}: {response.text[:200]}"
return url, None, "gave up after retries"
async def capture_batch(urls: List[str], concurrency: int = 4) -> List[Tuple[str, Optional[bytes], str]]:
sem = asyncio.Semaphore(concurrency)
headers = {"x-api-key": os.environ["SCREENSHOTLY_API_KEY"]}
async with httpx.AsyncClient(headers=headers, timeout=httpx.Timeout(60, connect=5)) as client:
return await asyncio.gather(*(capture_one(client, sem, url) for url in urls))
async def main() -> None:
urls = [
"https://example.com/",
"https://example.com/pricing",
"https://example.com/docs",
]
for index, (url, image, status) in enumerate(await capture_batch(urls)):
if image:
Path(f"page_{index}.webp").write_bytes(image)
print(url, status)
if __name__ == "__main__":
asyncio.run(main())
In a pandas workflow, pass df["url"].tolist() to capture_batch and write each status back to a column. For a few hundred URLs or more, use async jobs instead.
Long or must-not-lose captures: async jobs (Basic plan and above)
The synchronous endpoint keeps the connection open while the page renders. Navigation alone may take up to 30 seconds before any delay or waitForSelector, so slow pages, large PDFs and batches are better as jobs. The jobs API stores the request, retries failures up to three times and keeps the result for you. See the async jobs reference.
# jobs.py
import os
import time
from typing import Any, Dict
import requests
BASE_URL = "https://screenshotly.app"
HEADERS = {"x-api-key": os.environ["SCREENSHOTLY_API_KEY"]}
def submit_job(body: Dict[str, Any], idempotency_key: str) -> Dict[str, Any]:
response = requests.post(
f"{BASE_URL}/api/jobs",
json=body,
headers={**HEADERS, "Idempotency-Key": idempotency_key},
timeout=15,
)
response.raise_for_status()
return response.json() # {"id", "status", "replayed", "statusUrl"}
def wait_for_job(job_id: str, interval: float = 2, timeout: float = 300) -> Dict[str, Any]:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
response = requests.get(f"{BASE_URL}/api/jobs/{job_id}", headers=HEADERS, timeout=15)
response.raise_for_status()
job = response.json()
if job["status"] == "SUCCEEDED":
return job
if job["status"] in ("FAILED", "CANCELED"):
raise RuntimeError(f"Job {job_id} ended as {job['status']}: {job.get('errorMessage')}")
time.sleep(interval)
raise TimeoutError(f"Job {job_id} still running after {timeout}s")
if __name__ == "__main__":
job = submit_job({"url": "https://example.com/report", "format": "pdf"}, "report-2026-11")
done = wait_for_job(job["id"])
# resultUrl is pre-signed and short-lived. Don't send your API key to it.
pdf = requests.get(done["resultUrl"], timeout=60)
pdf.raise_for_status()
with open("report.pdf", "wb") as f:
f.write(pdf.content)
The Idempotency-Key makes the submit safe to retry. If the first response was lost, a repeat with the same key returns the original job ("replayed": true) instead of a second capture. If resultUrl has expired, call GET /api/jobs/{id} again for a fresh link. Growth and Scale accounts can submit up to 20 captures at once to POST /api/jobs/batch with {"captures": [...]}.
Django, Flask and FastAPI: keep captures out of the request
A capture takes seconds. Running it inside a view ties up a worker for that whole time. The usual shape:
- The view (or a
post_savesignal) enqueues a task with the object ID. - A Celery task calls the API and stores the result on the model or in object storage.
- The page shows a placeholder until the image exists.
# tasks.py
from celery import shared_task
from screenshotly_client import ScreenshotlyError, capture
@shared_task(bind=True, max_retries=5)
def capture_preview(self, page_id: int, url: str) -> int:
try:
image = capture({"url": url, "format": "webp", "quality": 80}, retries=0)
except ScreenshotlyError as exc:
if exc.status == 429 and exc.retry_after <= 60:
raise self.retry(exc=exc, countdown=exc.retry_after)
if exc.status >= 500:
raise self.retry(exc=exc, countdown=2 ** self.request.retries * 10)
raise # 4xx and quota exhaustion: fail visibly, don't loop
save_preview(page_id, image) # e.g. a Django FileField or an S3 upload
return len(image)
retries=0 hands retry decisions to Celery, so a waiting task doesn't block a worker process. In FastAPI, call the httpx version from a background task or a separate worker, not from the request handler.
Receiving signed webhooks in Flask
Add a webhook object to a capture or job request (Basic plan and above) and Screenshotly POSTs the result to you:
import os
from jobs import submit_job
job = submit_job(
{
"url": "https://example.com",
"format": "png",
"webhook": {
"url": "https://your-app.example.com/webhooks/screenshotly",
"secret": os.environ["SCREENSHOTLY_WEBHOOK_SECRET"],
},
},
idempotency_key="homepage-2026-11-13",
)
The payload looks like {"event": "screenshot.completed", "timestamp": "...", "data": {"url", "format", "size", "storageUrl", "duration"}}. For async jobs, storageUrl is a signed download link. A job that fails for good sends screenshot.failed with data.error. With a secret set, each delivery carries X-Screenshotly-Signature: sha256=<hex>: an HMAC-SHA256 of the raw body. Deliveries are attempted up to five times, so make the handler idempotent.
# webhook_app.py
import hashlib
import hmac
import json
import os
from flask import Flask, abort, request
app = Flask(__name__)
SECRET = os.environ["SCREENSHOTLY_WEBHOOK_SECRET"].encode()
@app.post("/webhooks/screenshotly")
def screenshotly_webhook():
raw = request.get_data() # raw bytes, exactly as signed
expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
received = request.headers.get("X-Screenshotly-Signature", "")
if not hmac.compare_digest(received, expected):
abort(401)
event = json.loads(raw)
if event["event"] == "screenshot.completed":
pass # download event["data"]["storageUrl"] promptly; it expires
elif event["event"] == "screenshot.failed":
app.logger.warning("Capture failed: %s", event["data"].get("error"))
return "", 204
In Django, the same check works on request.body in a view decorated with @csrf_exempt.
A typed options helper
To keep payloads valid across a codebase, build them from a small dataclass instead of loose dicts:
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
from screenshotly_client import capture
@dataclass
class CaptureOptions:
device: Optional[str] = "desktop" # desktop | laptop | tablet | mobile
width: Optional[int] = None # 320-3840, overrides the device width
height: Optional[int] = None # 240-3840
format: str = "png" # png | jpeg | webp (pdf, html: Basic+)
full_page: bool = False
delay_ms: int = 0
wait_for_selector: Optional[str] = None
ai_removal_types: List[str] = field(default_factory=list) # Growth+
mockup: Optional[str] = None # Growth+, e.g. "macbook-pro"
def to_payload(self, url: str) -> Dict[str, Any]:
payload: Dict[str, Any] = {"url": url, "format": self.format}
if self.device:
payload["device"] = self.device
if self.width:
payload["width"] = self.width
if self.height:
payload["height"] = self.height
if self.full_page:
payload["fullPage"] = True
if self.delay_ms:
payload["delay"] = self.delay_ms
if self.wait_for_selector:
payload["waitForSelector"] = self.wait_for_selector
if self.ai_removal_types:
payload["aiRemoval"] = {"enabled": True, "types": self.ai_removal_types}
if self.mockup:
payload["mockup"] = self.mockup
return payload
opts = CaptureOptions(full_page=True, wait_for_selector="main")
with open("example.png", "wb") as f:
f.write(capture(opts.to_payload("https://example.com")))
Conclusion
Capturing screenshots in Python doesn't require running browsers. The patterns that hold up in production:
- One capture function that owns the key, the timeout and a retry policy that fails fast on 4xx and quota exhaustion.
- Valid payloads: top-level
width/height, stringmockupIDs, andformat: "pdf"with no extra PDF options. - httpx with a semaphore for concurrent batches, and async jobs for slow or must-not-lose captures.
- Background tasks (Celery, RQ) in web apps, and signature-checked webhooks for delivery.
Ready to start capturing screenshots in Python?
Create a free account →. The Free plan includes 100 captures to test the request and response shape.
See the Python integration page → for a quick start, and the API reference → for every parameter.
About the Author

Asad Ali
CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.
Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients
Frequently Asked Questions
Should I use requests or httpx for the capture call?
Use requests for scripts, cron jobs and classic Flask or Django code, where a blocking call is fine. Use httpx.AsyncClient when you need many captures in flight at once, for example in FastAPI or an asyncio pipeline, and bound it with asyncio.Semaphore.
How do I avoid blocking Django requests with screenshot capture?
Don't call the capture API inside save() or a view. Enqueue a Celery (or RQ, django-q) task from the view or a post_save signal, have the task call the API, and store the result on the model. For captures that must not be lost, the task can submit a Screenshotly async job instead.
What's the right concurrency limit for batch captures in Python?
Start with an asyncio.Semaphore of 3 to 5 and one shared httpx.AsyncClient. The API enforces a per-minute limit (5 on Free, 40 on Basic, 80 on Growth, 200 on Scale), so handle 429 responses by honoring a short Retry-After.
How many free screenshots do I get?
The Free plan includes 100 captures in total. It doesn't reset daily or monthly. Paid plans start at $14/month for 2,500 captures, and failed captures don't count against quota.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.