API reference
Website screenshots with Python
Calling Shotfly from Python takes one requests.get: send the page URL and your secret key to /v1/screenshot and write the response body to a file. Install the library with pip install requests. The examples read the key from the SHOTFLY_SECRET_KEY environment variable.
How do I take a screenshot in Python?
import os
import time
import requests
API = "https://api.shotfly.dev"
RETRYABLE = {429, 500, 502, 503} # rate limits and server errors, never charged
def screenshot(params, retries=3):
"""One screenshot. Retries rate limits and server errors; other errors are final."""
for attempt in range(retries + 1):
r = requests.get(
f"{API}/v1/screenshot",
params=params,
headers={"Authorization": f"Bearer {os.environ['SHOTFLY_SECRET_KEY']}"},
timeout=90,
)
if r.ok:
return r.content, int(r.headers["x-credits-charged"])
if r.status_code in RETRYABLE and attempt < retries:
time.sleep(int(r.headers.get("retry-after", 2**attempt)))
continue
try: # a proxy in front of the API can answer with HTML
error = r.json()["error"]
except (ValueError, KeyError):
error = {"code": f"http_{r.status_code}", "message": r.reason}
raise RuntimeError(f"{error['code']}: {error['message']}")
image, credits = screenshot({"url": "https://example.com", "full_page": "true", "format": "webp"})
with open("example.webp", "wb") as f:
f.write(image)
print(f"saved example.webp, {credits} credit")Rate limits and errors on Shotfly's side are retried; other errors are final and cost nothing. For page metadata instead of the image, add "response_type": "json" and read r.json()["metadata"].
How do I capture many pages without waiting?
import os
import time
import requests
API = "https://api.shotfly.dev"
headers = {"Authorization": f"Bearer {os.environ['SHOTFLY_SECRET_KEY']}"}
r = requests.post(f"{API}/v1/jobs", json={"url": "https://example.com", "full_page": True}, headers=headers, timeout=30)
if r.status_code != 202:
raise RuntimeError(r.json()["error"]["message"])
job_id = r.json()["job_id"]
# Poll until it finishes. Or pass webhook_url when submitting and skip this loop.
while True:
job = requests.get(f"{API}/v1/jobs/{job_id}", headers=headers, timeout=30).json()
if job["status"] == "completed":
print("image:", job["url"])
break
if job["status"] == "failed":
raise RuntimeError(f"{job['error']['code']}: {job['error']['message']}")
time.sleep(2)How do I embed a screenshot without exposing my key?
import hashlib
import hmac
import os
import time
from urllib.parse import quote, urlencode
API = "https://api.shotfly.dev"
def signed_screenshot_url(params, public_key, secret, expires_in=None):
"""A URL for <img src> or og:image: it carries the public key and a signature, never the secret."""
signed = {k: str(v) for k, v in params.items()}
signed["access_key"] = public_key
if expires_in:
signed["expires"] = str(int(time.time()) + expires_in)
canonical = "&".join(f"{quote(k, safe='')}={quote(v, safe='')}" for k, v in sorted(signed.items()))
signature = hmac.new(secret.encode(), canonical.encode(), hashlib.sha256).hexdigest()
return f"{API}/v1/screenshot?{urlencode({**signed, 'signature': signature})}"
print(signed_screenshot_url(
{"url": "https://example.com", "viewport_width": 1200, "viewport_height": 630},
public_key=os.environ["SHOTFLY_PUBLIC_KEY"],
secret=os.environ["SHOTFLY_SECRET_KEY"],
expires_in=86400,
))The URL carries your public key (pk_…) and a signature; the secret stays on your server. Changing any parameter breaks the signature.
How do I verify a webhook in Python?
import hashlib
import hmac
import time
def verify_webhook(raw_body: bytes, header: str, secret: str) -> bool:
"""Checks X-Shotfly-Signature (t=<unix>,v1=<hex>) against the raw request body."""
parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
t, v1 = parts.get("t", ""), parts.get("v1", "")
if not t.isdigit() or abs(time.time() - int(t)) > 300:
return False
expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, v1)Pass the raw request body, before any JSON parsing: request.get_data() in Flask, request.body in Django. The secret is the one of the key that created the job or monitor.
Which errors should I handle?
| Status | Codes | What to do |
|---|---|---|
| 400 | invalid_params, url_not_allowed | Fix the request; details lists each problem |
| 401, 403 | unauthorized, forbidden, signature_invalid, signature_expired, domain_blocked | Check the key, the signature or the target |
| 402 | quota_exceeded, credits_limit | Upgrade, wait for the next period, or raise max_credits |
| 422 | target_blocked, blank_page, target_http_error, cookie_wall | Not charged. Change the parameters (wait_for_selector, escalation=auto) or skip the page |
| 429 | rate_limited, concurrency_limited | Wait (Retry-After when present) and retry |
| 500, 502, 503 | internal_error, render_failed, service_unavailable | Retry with backoff; not charged |
| 504 | render_timeout | Raise timeout, or queue the capture as an async job |
Every error is JSON: { "error": { "code", "message", "request_id", "docs_url" } }. See error codes for the full list.
Last updated 2026-12-01. Markdown version: /docs/guides/python.md