Long renders, videos and webhooks: going async
When to use async rendering, how to receive and verify signed webhooks, and how to poll for results instead.
9 min read
Most screenshots come back in a second or two, in the same HTTP request. Some don’t: long pages captured in full, slow sites, scrolling videos, and batches. For those, shotsmith renders in the background and tells you when it’s done.
When to go async
Synchronous requests must finish within 18 seconds. Use async=true when you’re capturing:
- full-page screenshots of very long pages, or slow sites
- videos longer than 10 seconds (WebM and GIF also take longer to encode than MP4)
- pages that need a
delayof more than 10 seconds - anything in a background job, where nobody is waiting for the response
Async renders may run for up to 600 seconds.
1. Queue the render
Add async=true, and optionally a webhook_url. The API answers immediately with 202 Accepted:
import { Shotsmith } from '@shotsmith/sdk';
const shotsmith = new Shotsmith({ accessKey: 'YOUR_ACCESS_KEY' });
const job = await shotsmith.takeAsync({
url: 'https://shotsmith.dev/sample',
full_page: true,
webhook_url: 'https://your-app.com/hooks/shotsmith',
});
console.log(job.id, job.status_url);
<?php
require 'vendor/autoload.php';
use Shotsmith\Client;
$shotsmith = new Client('YOUR_ACCESS_KEY');
$job = $shotsmith->takeAsync([
'url' => 'https://shotsmith.dev/sample',
'full_page' => true,
'webhook_url' => 'https://your-app.com/hooks/shotsmith',
]);
echo $job['status_url'];
curl -X POST "https://shotsmith.dev/v1/take" \
-H "X-Access-Key: YOUR_ACCESS_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://shotsmith.dev/sample",
"full_page": true,
"webhook_url": "https://your-app.com/hooks/shotsmith",
"async": true
}'
const res = await fetch('https://shotsmith.dev/v1/take', {
method: 'POST',
headers: {
'X-Access-Key': 'YOUR_ACCESS_KEY',
'Content-Type': 'application/json',
},
body: JSON.stringify({
url: 'https://shotsmith.dev/sample',
full_page: true,
webhook_url: 'https://your-app.com/hooks/shotsmith',
async: true,
}),
});
if (!res.ok) throw new Error((await res.json()).error_message);
console.log(await res.json());
import json
import urllib.request
body = {
"url": "https://shotsmith.dev/sample",
"full_page": True,
"webhook_url": "https://your-app.com/hooks/shotsmith",
"async": True
}
req = urllib.request.Request(
"https://shotsmith.dev/v1/take",
data=json.dumps(body).encode(),
headers={"X-Access-Key": "YOUR_ACCESS_KEY", "Content-Type": "application/json"},
method="POST",
)
# Raises urllib.error.HTTPError on a 4xx/5xx response
with urllib.request.urlopen(req, timeout=60) as res:
print(json.load(res))
<?php
$ch = curl_init('https://shotsmith.dev/v1/take');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => ['X-Access-Key: YOUR_ACCESS_KEY', 'Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode([
'url' => 'https://shotsmith.dev/sample',
'full_page' => true,
'webhook_url' => 'https://your-app.com/hooks/shotsmith',
'async' => true,
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
]);
$response = json_decode(curl_exec($ch), true);
if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) >= 400) {
throw new RuntimeException($response['error_message']);
}
print_r($response);
package main
import (
"fmt"
"io"
"net/http"
"strings"
)
func main() {
body := strings.NewReader(`{
"url": "https://shotsmith.dev/sample",
"full_page": true,
"webhook_url": "https://your-app.com/hooks/shotsmith",
"async": true
}`)
req, _ := http.NewRequest("POST", "https://shotsmith.dev/v1/take", body)
req.Header.Set("X-Access-Key", "YOUR_ACCESS_KEY")
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
out, _ := io.ReadAll(res.Body)
fmt.Println(string(out))
}
require "net/http"
require "json"
body = {
"url" => "https://shotsmith.dev/sample",
"full_page" => true,
"webhook_url" => "https://your-app.com/hooks/shotsmith",
"async" => true
}
res = Net::HTTP.post(
URI("https://shotsmith.dev/v1/take"),
body.to_json,
"X-Access-Key" => "YOUR_ACCESS_KEY",
"Content-Type" => "application/json"
)
raise res.body unless res.is_a?(Net::HTTPSuccess)
puts JSON.parse(res.body)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Request {
public static void main(String[] args) throws Exception {
var body = """
{
"url": "https://shotsmith.dev/sample",
"full_page": true,
"webhook_url": "https://your-app.com/hooks/shotsmith",
"async": true
}
""";
var request = HttpRequest.newBuilder(URI.create("https://shotsmith.dev/v1/take"))
.header("X-Access-Key", "YOUR_ACCESS_KEY")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
var res = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(res.body());
}
}
using System;
using System.Net.Http;
using System.Text;
using var http = new HttpClient();
http.DefaultRequestHeaders.Add("X-Access-Key", "YOUR_ACCESS_KEY");
var body = """
{
"url": "https://shotsmith.dev/sample",
"full_page": true,
"webhook_url": "https://your-app.com/hooks/shotsmith",
"async": true
}
""";
var res = await http.PostAsync(
"https://shotsmith.dev/v1/take",
new StringContent(body, Encoding.UTF8, "application/json")
);
res.EnsureSuccessStatusCode();
Console.WriteLine(await res.Content.ReadAsStringAsync());
Content-Type: application/json
X-Capture-Id: 01m8kvpk6jsmeykdfs0wy6awbn
{
"is_successful": true,
"id": "01m8kvpk6jsmeykdfs0wy6awbn",
"status": "queued",
"status_url": "https://shotsmith.dev/v1/captures/01m8kvpk6jsmeykdfs0wy6awbn"
}
Set external_identifier to your own reference, such as an order ID. It comes back in the webhook, so you can match the result to your record without storing the capture ID.
2. Receive the webhook
When the render finishes, shotsmith POSTs the capture to your webhook_url, signed with your webhook secret in X-Shotsmith-Signature. Always verify the signature before trusting the payload. These handlers use only each language’s standard library:
import http from 'node:http';
import { Shotsmith } from '@shotsmith/sdk';
http.createServer(async (req, res) => {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
try {
// Throws if the signature is wrong. Pass the body exactly as received.
const event = await Shotsmith.parseWebhook(
Buffer.concat(chunks).toString(),
req.headers['x-shotsmith-signature'],
process.env.SHOTSMITH_WEBHOOK_SECRET,
);
console.log(event.event, event.data.id);
res.writeHead(204).end();
} catch {
res.writeHead(401).end();
}
}).listen(3000);
<?php
require 'vendor/autoload.php';
use Shotsmith\Webhook;
try {
// Throws if the signature is wrong. Pass the body exactly as received.
$event = Webhook::parse(
file_get_contents('php://input'),
$_SERVER['HTTP_X_SHOTSMITH_SIGNATURE'] ?? null,
getenv('SHOTSMITH_WEBHOOK_SECRET'),
);
} catch (Throwable $e) {
http_response_code(401);
exit;
}
error_log($event['event'] . ' ' . $event['data']['id']);
http_response_code(204);
import crypto from 'node:crypto';
import http from 'node:http';
http.createServer(async (req, res) => {
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const body = Buffer.concat(chunks); // the exact bytes received
const expected = crypto.createHmac('sha256', process.env.SHOTSMITH_WEBHOOK_SECRET).update(body).digest('hex');
const given = req.headers['x-shotsmith-signature'] ?? '';
if (given.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected))) {
return res.writeHead(401).end();
}
const event = JSON.parse(body);
console.log(event.event, event.data.id);
res.writeHead(204).end();
}).listen(3000);
import hashlib
import hmac
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
SECRET = os.environ["SHOTSMITH_WEBHOOK_SECRET"].encode()
class WebhookHandler(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length", 0))) # the exact bytes received
expected = hmac.new(SECRET, body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, self.headers.get("X-Shotsmith-Signature", "")):
self.send_response(401)
self.end_headers()
return
event = json.loads(body)
print(event["event"], event["data"]["id"])
self.send_response(204)
self.end_headers()
HTTPServer(("", 3000), WebhookHandler).serve_forever()
<?php
$body = file_get_contents('php://input'); // the exact bytes received
$given = $_SERVER['HTTP_X_SHOTSMITH_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', $body, getenv('SHOTSMITH_WEBHOOK_SECRET'));
if (! hash_equals($expected, $given)) {
http_response_code(401);
exit;
}
$event = json_decode($body, true);
error_log($event['event'] . ' ' . $event['data']['id']);
http_response_code(204);
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"os"
)
func webhook(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body) // the exact bytes received
mac := hmac.New(sha256.New, []byte(os.Getenv("SHOTSMITH_WEBHOOK_SECRET")))
mac.Write(body)
expected := hex.EncodeToString(mac.Sum(nil))
if !hmac.Equal([]byte(expected), []byte(r.Header.Get("X-Shotsmith-Signature"))) {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
var event map[string]any
json.Unmarshal(body, &event)
log.Println(event["event"])
w.WriteHeader(http.StatusNoContent)
}
func main() {
http.HandleFunc("POST /", webhook)
log.Fatal(http.ListenAndServe(":3000", nil))
}
require "json"
require "openssl"
# Call from your web handler with the raw request body and the
# X-Shotsmith-Signature header. Returns the event, or nil if the signature is wrong.
def parse_shotsmith_webhook(raw_body, signature)
expected = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("SHOTSMITH_WEBHOOK_SECRET"), raw_body)
return nil unless OpenSSL.secure_compare(expected, signature.to_s)
JSON.parse(raw_body)
end
Compute the signature over the raw body, exactly as received. If your framework has already parsed the JSON, re-encoding it can change the bytes and the signature won’t match.
3. Or poll for the result
No public endpoint for webhooks? Poll the status_url from the 202 response every few seconds until status is succeeded or failed. The SDKs do this for you with waitFor(id).
Retries and failures
- If your endpoint doesn’t answer with a 2xx within 15 seconds, the webhook is retried after 10 seconds, then 1 minute, 5 minutes, 30 minutes and 2 hours. Every attempt is visible on the Webhooks page, where you can resend one.
- Failed renders don’t send a webhook by default. Add
webhook_errors=trueto hear about failures too, with the error code and message. - Answer quickly: return 200 first, then do the slow work (downloading the file, image processing) in your own background job.
The async and webhooks docs have the full payload format.