Tutorial

Go Screenshot API Tutorial: net/http Client, Workers and Webhooks

Working Go code for the Screenshotly screenshot API: a standard-library quick start, a small client package with typed errors and safe retries, a rate-limited batch worker, a CLI, an HTTP preview service, async jobs and webhook verification.

Asad AliNovember 25, 202512 min read

Go is a good fit for screenshot work that runs as a worker, a CLI or a small service: one shared http.Client, a few goroutines and io.Copy handle most of it. This guide builds that up from a standard-library quick start to a small client package, then uses it for a batch worker, a command-line tool, a preview service, async jobs and signed webhooks.

Every program here was compiled with go vet clean and run against a mock of the API that applies the real request schema and plan rules. The code needs Go 1.22 or newer (it uses method-based http.HandleFunc patterns and per-iteration loop variables). For the full parameter list, see the screenshot API reference.

The API contract in one table

Endpoint POST https://screenshotly.app/api/screenshot
Authentication x-api-key: YOUR_API_KEY header (Authorization: Bearer YOUR_API_KEY also works)
Body JSON. Unknown fields are rejected with 400, so send only documented options.
Success 200 with the file itself (image/png by default)
Errors JSON {"error": "...", "message": "..."} with the status codes in the error reference
Per-minute limit Free 5, Basic 40, Growth 80, Scale 200 requests
Quota Free: 100 captures in total. Basic $14: 2,500/month. Growth $59: 12,000/month. Scale $199: 50,000/month. Failed captures don't count. See pricing.

Quick start: standard library only

Set your key and run this program. It captures a full page and streams the PNG to disk.

export SCREENSHOTLY_API_KEY=your_key_here
package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"
)

const endpoint = "https://screenshotly.app/api/screenshot"

func capture(ctx context.Context, pageURL, path string) error {
	body, err := json.Marshal(map[string]any{
		"url":      pageURL,
		"format":   "png",
		"fullPage": true,
	})
	if err != nil {
		return err
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Set("x-api-key", os.Getenv("SCREENSHOTLY_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		var apiErr struct{ Error, Message string }
		_ = json.NewDecoder(resp.Body).Decode(&apiErr)
		return fmt.Errorf("screenshotly: HTTP %d: %s", resp.StatusCode, apiErr.Message)
	}

	f, err := os.Create(path)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = io.Copy(f, resp.Body) // stream to disk, no full-size buffer
	return err
}

func main() {
	// Slow pages can take tens of seconds; give the whole call a minute.
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	if err := capture(ctx, "https://example.com", "example.png"); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Saved example.png")
}

Three details matter even in the short version:

  • The request is built with http.NewRequestWithContext, so the 60-second deadline cancels it.
  • The status is checked before anything is written. Error responses are JSON, and you don't want them saved as example.png.
  • io.Copy streams the body to the file instead of reading it all into memory first.

A small client package

For anything beyond a script, wrap the call in a package: one http.Client, typed options that match the API, and a typed error so callers can tell a plan problem from a rate limit.

// Package screenshotly is a small client for the Screenshotly screenshot API.
package screenshotly

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

// Options mirrors the API's top-level request fields. Zero values are omitted.
type Options struct {
	Format          string     `json:"format,omitempty"` // png, jpeg, webp; pdf, html (Basic+)
	Quality         int        `json:"quality,omitempty"`
	Device          string     `json:"device,omitempty"` // desktop, laptop, tablet, mobile
	Width           int        `json:"width,omitempty"`  // 320–3840
	Height          int        `json:"height,omitempty"` // 240–3840
	FullPage        bool       `json:"fullPage,omitempty"`
	DeviceScale     float64    `json:"deviceScaleFactor,omitempty"`
	Delay           int        `json:"delay,omitempty"` // ms, up to 10000
	WaitForSelector string     `json:"waitForSelector,omitempty"`
	BlockAds        bool       `json:"blockAds,omitempty"`
	DarkMode        bool       `json:"darkMode,omitempty"`
	Selector        string     `json:"selector,omitempty"`
	Mockup          string     `json:"mockup,omitempty"` // Growth+
	AIRemoval       *AIRemoval `json:"aiRemoval,omitempty"`
}

// AIRemoval hides common overlays before capture (Growth+).
type AIRemoval struct {
	Enabled bool     `json:"enabled"`
	Types   []string `json:"types,omitempty"` // cookie-banner, newsletter, chat-widget, social-overlay, ad
}

// APIError is returned for any non-200 response.
type APIError struct {
	Status      int
	Code        string // the "error" field, e.g. "Plan upgrade required"
	Message     string
	MinimumPlan string
	RetryAfter  time.Duration
}

func (e *APIError) Error() string {
	return fmt.Sprintf("screenshotly: HTTP %d: %s: %s", e.Status, e.Code, e.Message)
}

// Temporary reports whether retrying the same request can succeed.
func (e *APIError) Temporary() bool {
	return e.Status == 429 || e.Status == 500 || e.Status == 503
}

type Client struct {
	BaseURL    string
	APIKey     string
	HTTPClient *http.Client
}

func New(apiKey string) *Client {
	return &Client{
		BaseURL: "https://screenshotly.app",
		APIKey:  apiKey,
		// One shared client so connections are reused. The timeout covers the
		// whole call, including reading the body; slow pages need tens of seconds.
		HTTPClient: &http.Client{Timeout: 65 * time.Second},
	}
}

// CaptureTo captures pageURL and streams the file into w. Nothing is written
// to w unless the API returns 200.
func (c *Client) CaptureTo(ctx context.Context, w io.Writer, pageURL string, opts Options) error {
	payload := struct {
		URL string `json:"url"`
		Options
	}{pageURL, opts}
	body, err := json.Marshal(payload)
	if err != nil {
		return err
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/api/screenshot", bytes.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Set("x-api-key", c.APIKey)
	req.Header.Set("Content-Type", "application/json")

	resp, err := c.HTTPClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return decodeError(resp)
	}
	_, err = io.Copy(w, resp.Body)
	return err
}

func decodeError(resp *http.Response) error {
	var body struct {
		Error       string `json:"error"`
		Message     string `json:"message"`
		MinimumPlan string `json:"minimumPlan"`
	}
	_ = json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&body)
	seconds, _ := strconv.Atoi(resp.Header.Get("Retry-After"))
	return &APIError{
		Status:      resp.StatusCode,
		Code:        body.Error,
		Message:     body.Message,
		MinimumPlan: body.MinimumPlan,
		RetryAfter:  time.Duration(seconds) * time.Second,
	}
}

Options uses omitempty on every field, so unset options are left out of the JSON. The API rejects unknown keys, so keep these names in sync with the API reference. Note the absence of a viewport object: width and height are top-level fields.

Retrying the right errors

Only three statuses are worth retrying: 429 (rate limit), 500 (the capture failed) and 503 (capture proxy unavailable). Everything else — 400, 401, 403, 413 — fails the same way every time.

429 needs one more check. When you exceed the per-minute limit, Retry-After is a few seconds. When your monthly quota is used up, Retry-After counts down to the quota reset, which can be days away. Sleeping that long inside a worker is never what you want, so this helper gives up when the wait exceeds a minute.

package screenshotly

import (
	"context"
	"errors"
	"io"
	"time"
)

// MaxWait caps how long CaptureWithRetry will sleep on one Retry-After.
// A longer Retry-After means the plan's quota is used up, so we give up.
const MaxWait = time.Minute

// CaptureWithRetry retries 429, 500 and 503 up to three times. Retries only
// happen on API errors, before anything has been written to w.
func (c *Client) CaptureWithRetry(ctx context.Context, w io.Writer, pageURL string, opts Options) error {
	backoff := time.Second
	for attempt := 0; ; attempt++ {
		err := c.CaptureTo(ctx, w, pageURL, opts)
		if err == nil {
			return nil
		}

		var apiErr *APIError
		if !errors.As(err, &apiErr) || !apiErr.Temporary() || attempt == 3 {
			return err
		}
		wait := backoff
		if apiErr.RetryAfter > 0 {
			wait = apiErr.RetryAfter
		}
		if wait > MaxWait {
			return err // quota exhausted: retrying now cannot succeed
		}

		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(wait):
		}
		backoff *= 2
	}
}

Because CaptureTo writes nothing until it gets a 200, a retry never appends to a half-written file.

Capture options and plan gates

Option Plans Notes
format: png, jpeg, webp All quality 0–100 for JPEG/WebP
format: pdf, html Basic and up PDF is A4 with 1 cm margins, backgrounds printed; size and margins are not configurable
device, width, height, fullPage, deviceScaleFactor All device: desktop, laptop, tablet, mobile. Width 320–3840, height 240–3840, scale 1–3
delay, waitForSelector, waitForNetworkIdle, selector, blockAds, darkMode All delay up to 10,000 ms
headers, cookies, stealth, cache, storage, webhook Basic and up for logged-in pages and delivery
aiRemoval, mockup, javascript, hideSelectors, scroll, geolocation Growth and up mockup IDs: browser-light, browser-dark, browser-minimal, iphone-14, ipad-pro, macbook-pro
proxyRegion (us, eu, apac), format: "webm" Scale WebM length 1–15 s via videoDuration

Requesting a gated option on a lower plan returns 403 with "error": "Plan upgrade required" and a minimumPlan field. The client above exposes it as APIError.MinimumPlan.

A command-line tool

A thin main around the package gives you a reusable CLI. signal.NotifyContext makes Ctrl-C cancel the in-flight request, and a failed capture removes the empty output file.

// Command shot captures one URL: shot -url https://example.com -out example.png -full
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"
	"os"
	"os/signal"

	"example.com/shots/screenshotly"
)

func main() {
	pageURL := flag.String("url", "", "page to capture (required)")
	out := flag.String("out", "screenshot.png", "output file")
	format := flag.String("format", "png", "png, jpeg or webp (pdf needs Basic+)")
	device := flag.String("device", "desktop", "desktop, laptop, tablet or mobile")
	full := flag.Bool("full", false, "capture the full scrollable page")
	flag.Parse()

	apiKey := os.Getenv("SCREENSHOTLY_API_KEY")
	if *pageURL == "" || apiKey == "" {
		fmt.Fprintln(os.Stderr, "usage: SCREENSHOTLY_API_KEY=... shot -url <url> [-out file] [-format png] [-device desktop] [-full]")
		os.Exit(2)
	}

	// Ctrl-C cancels the in-flight request.
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	f, err := os.Create(*out)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	client := screenshotly.New(apiKey)
	err = client.CaptureWithRetry(ctx, f, *pageURL, screenshotly.Options{
		Format:   *format,
		Device:   *device,
		FullPage: *full,
	})
	f.Close()
	if err != nil {
		os.Remove(*out)
		var apiErr *screenshotly.APIError
		if errors.As(err, &apiErr) && apiErr.MinimumPlan != "" {
			fmt.Fprintf(os.Stderr, "%s (needs the %s plan)\n", apiErr.Message, apiErr.MinimumPlan)
		} else {
			fmt.Fprintln(os.Stderr, err)
		}
		os.Exit(1)
	}
	fmt.Println("saved", *out)
}
go run ./cmd/shot -url https://example.com -out example.webp -format webp -device mobile -full

On the Free plan, -format pdf exits with PDF output requires the basic plan or higher (needs the basic plan) and leaves no file behind.

Batch captures with a rate limiter and a worker cap

Two separate limits apply to a batch: how many requests per minute your plan allows, and how many requests you want in flight at once. golang.org/x/time/rate handles the first and errgroup.SetLimit the second.

go get golang.org/x/sync/errgroup golang.org/x/time/rate
package screenshotly

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"golang.org/x/sync/errgroup"
	"golang.org/x/time/rate"
)

// CaptureAll saves one PNG per URL into dir. perMinute should be at or below
// your plan's limit (Free 5, Basic 40, Growth 80, Scale 200); workers bounds
// how many captures are in flight at once.
func (c *Client) CaptureAll(ctx context.Context, urls []string, dir string, perMinute, workers int) map[string]error {
	limiter := rate.NewLimiter(rate.Every(time.Minute/time.Duration(perMinute)), 1)
	errs := make([]error, len(urls))

	g, ctx := errgroup.WithContext(ctx)
	g.SetLimit(workers)
	for i, u := range urls {
		g.Go(func() error {
			if err := limiter.Wait(ctx); err != nil {
				errs[i] = err
				return nil
			}
			errs[i] = c.captureFile(ctx, u, filepath.Join(dir, fmt.Sprintf("%03d.png", i)))
			return nil // record per-URL failures instead of cancelling the batch
		})
	}
	_ = g.Wait()

	failed := map[string]error{}
	for i, err := range errs {
		if err != nil {
			failed[urls[i]] = err
		}
	}
	return failed
}

func (c *Client) captureFile(ctx context.Context, pageURL, path string) error {
	f, err := os.Create(path)
	if err != nil {
		return err
	}
	err = c.CaptureWithRetry(ctx, f, pageURL, Options{Format: "png", BlockAds: true})
	if closeErr := f.Close(); err == nil {
		err = closeErr
	}
	if err != nil {
		os.Remove(path) // do not leave an empty or partial file behind
	}
	return err
}

Each goroutine records its own error and returns nil, so one bad URL doesn't cancel the rest of the batch. Failed captures delete their partial file.

package main

import (
	"bufio"
	"context"
	"log"
	"os"

	"example.com/shots/screenshotly"
)

func main() {
	var urls []string
	scanner := bufio.NewScanner(os.Stdin) // one URL per line
	for scanner.Scan() {
		if line := scanner.Text(); line != "" {
			urls = append(urls, line)
		}
	}

	client := screenshotly.New(os.Getenv("SCREENSHOTLY_API_KEY"))
	if err := os.MkdirAll("captures", 0o755); err != nil {
		log.Fatal(err)
	}

	// Basic plan: 40 requests per minute; keep 4 captures in flight.
	failed := client.CaptureAll(context.Background(), urls, "captures", 40, 4)
	for u, err := range failed {
		log.Printf("FAILED %s: %v", u, err)
	}
	log.Printf("%d captured, %d failed", len(urls)-len(failed), len(failed))
}
cat urls.txt | go run ./cmd/batch

For hundreds of URLs, or captures that must survive a restart, queue them as async jobs instead; on Growth and Scale, POST /api/jobs/batch accepts up to 20 captures per request.

Serving previews from an HTTP handler

A preview endpoint is a common reason to run capture inside a Go service. Two rules keep it safe: only capture URLs you expect (an open endpoint lets anyone spend your quota), and don't write headers until you know the capture succeeded.

package main

import (
	"errors"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"

	"example.com/shots/screenshotly"
)

// Only capture pages on hosts you own; an open endpoint would let anyone
// spend your quota on arbitrary URLs.
var allowedHosts = map[string]bool{"example.com": true, "www.example.com": true}

func main() {
	client := screenshotly.New(os.Getenv("SCREENSHOTLY_API_KEY"))

	http.HandleFunc("GET /preview", func(w http.ResponseWriter, r *http.Request) {
		target, err := url.Parse(r.URL.Query().Get("url"))
		if err != nil || target.Scheme != "https" || !allowedHosts[strings.ToLower(target.Hostname())] {
			http.Error(w, "url not allowed", http.StatusBadRequest)
			return
		}

		w.Header().Set("Content-Type", "image/webp")
		w.Header().Set("Cache-Control", "public, max-age=3600")
		// The client writes nothing until the API returns 200, so the error
		// path below can still send its own status code.
		err = client.CaptureTo(r.Context(), w, target.String(), screenshotly.Options{
			Format: "webp", Quality: 80, Width: 1200, Height: 630,
		})
		if err != nil {
			w.Header().Del("Cache-Control")
			var apiErr *screenshotly.APIError
			if errors.As(err, &apiErr) && apiErr.Status == http.StatusTooManyRequests {
				w.Header().Set("Retry-After", "60")
				http.Error(w, "busy, try again", http.StatusServiceUnavailable)
				return
			}
			log.Printf("preview %s: %v", target, err)
			http.Error(w, "capture failed", http.StatusBadGateway)
		}
	})

	log.Fatal(http.ListenAndServe(":8080", nil))
}

Because CaptureTo streams only after a 200, the handler can still return its own 400, 502 or 503 when something goes wrong. The 429 from Screenshotly becomes a 503 with Retry-After for your own callers, and the cache header is only kept on success.

Async jobs for slow pages and PDFs

A synchronous capture can take tens of seconds; page navigation alone is allowed up to 30. For slow pages, PDFs and anything that must survive a deploy, use the async jobs API (Basic plan and up). POST /api/jobs takes the same body, returns 202 with a job ID, and an Idempotency-Key header makes a retried submission return the same job.

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"
)

const base = "https://screenshotly.app"

type job struct {
	ID        string `json:"id"`
	Status    string `json:"status"`
	StatusURL string `json:"statusUrl"`
	ResultURL string `json:"resultUrl"`
}

func call(ctx context.Context, method, path, idemKey string, body any, out any) error {
	var reader io.Reader
	if body != nil {
		b, err := json.Marshal(body)
		if err != nil {
			return err
		}
		reader = bytes.NewReader(b)
	}
	req, err := http.NewRequestWithContext(ctx, method, base+path, reader)
	if err != nil {
		return err
	}
	req.Header.Set("x-api-key", os.Getenv("SCREENSHOTLY_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	if idemKey != "" {
		req.Header.Set("Idempotency-Key", idemKey)
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 300 {
		msg, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
		return fmt.Errorf("%s %s: HTTP %d: %s", method, path, resp.StatusCode, msg)
	}
	return json.NewDecoder(resp.Body).Decode(out)
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()

	// 1. Queue the capture (Basic+). The same Idempotency-Key on a retry returns the same job.
	var j job
	err := call(ctx, http.MethodPost, "/api/jobs", "invoice-4821",
		map[string]any{"url": "https://example.com/invoices/4821", "format": "pdf"}, &j)
	if err != nil {
		log.Fatal(err)
	}

	// 2. Poll until the job reaches a final state.
	for j.Status == "QUEUED" || j.Status == "RUNNING" {
		select {
		case <-ctx.Done():
			log.Fatal(ctx.Err())
		case <-time.After(2 * time.Second):
		}
		if err := call(ctx, http.MethodGet, "/api/jobs/"+j.ID, "", nil, &j); err != nil {
			log.Fatal(err)
		}
	}
	if j.Status != "SUCCEEDED" {
		log.Fatalf("job %s ended as %s", j.ID, j.Status)
	}

	// 3. resultUrl is a short-lived signed link: download it now, without the API key.
	resp, err := http.Get(j.ResultURL)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		log.Fatalf("download failed: HTTP %d (signed link expired? read the job again)", resp.StatusCode)
	}
	f, err := os.Create("invoice-4821.pdf")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	if _, err := io.Copy(f, resp.Body); err != nil {
		log.Fatal(err)
	}
	fmt.Println("saved invoice-4821.pdf")
}

The job status is one of QUEUED, RUNNING, SUCCEEDED, FAILED or CANCELED. resultUrl is a short-lived signed link: download it straight away with a plain GET and never send your API key to it. If it has expired, read the job again for a fresh one. Workers retry failed jobs up to three times on the server side.

Receiving signed webhooks

Instead of polling, add a webhook object to the request (Basic plan and up): {"url": "https://your-app.example.com/hooks/screenshotly", "secret": "..."}. When the capture finishes, Screenshotly POSTs JSON like this:

{
  "event": "screenshot.completed",
  "timestamp": "2026-11-13T08:00:00.000Z",
  "data": {
    "url": "https://example.com/invoices/4821",
    "format": "pdf",
    "size": 48213,
    "storageUrl": "https://screenshotly.app/api/assets/...",
    "duration": 4210
  }
}

The request carries X-Screenshotly-Signature: sha256=<hex>, an HMAC-SHA256 of the raw body using your secret, plus X-Screenshotly-Timestamp. Failed jobs send screenshot.failed with an error field. Deliveries are attempted up to five times and redirects are not followed, so register the final URL.

package screenshotly

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"io"
	"log"
	"net/http"
)

// ValidSignature checks an X-Screenshotly-Signature header against the raw body.
func ValidSignature(body []byte, header, secret string) bool {
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write(body)
	expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(expected), []byte(header))
}

// WebhookHandler verifies and logs screenshot.completed events.
func WebhookHandler(secret string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
		if err != nil || !ValidSignature(body, r.Header.Get("X-Screenshotly-Signature"), secret) {
			http.Error(w, "invalid signature", http.StatusUnauthorized)
			return
		}

		var event struct {
			Event string `json:"event"`
			Data  struct {
				URL        string `json:"url"`
				Format     string `json:"format"`
				Size       int    `json:"size"`
				StorageURL string `json:"storageUrl"` // set when the capture used storage
			} `json:"data"`
		}
		if err := json.Unmarshal(body, &event); err != nil {
			http.Error(w, "bad payload", http.StatusBadRequest)
			return
		}
		if event.Event == "screenshot.completed" {
			log.Printf("captured %s (%d bytes)", event.Data.URL, event.Data.Size)
		}
		w.WriteHeader(http.StatusNoContent)
	}
}

Verify the signature over the exact bytes you received, before parsing, and compare with hmac.Equal so the check runs in constant time.

Testing without the network

httptest.NewServer gives you a fake API in a few lines. These tests check that the key and body are sent, that a plan error is not retried, and that an exhausted quota fails fast instead of sleeping.

package screenshotly

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestCaptureSendsKeyAndStreamsBody(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/api/screenshot" || r.Header.Get("x-api-key") != "test-key" {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
		var body map[string]any
		_ = json.NewDecoder(r.Body).Decode(&body)
		if body["url"] != "https://example.com" || body["fullPage"] != true {
			t.Errorf("unexpected body: %v", body)
		}
		w.Header().Set("Content-Type", "image/png")
		w.Write([]byte("\x89PNG"))
	}))
	defer srv.Close()

	c := New("test-key")
	c.BaseURL = srv.URL
	var out bytes.Buffer
	if err := c.CaptureTo(context.Background(), &out, "https://example.com", Options{FullPage: true}); err != nil {
		t.Fatal(err)
	}
	if out.String() != "\x89PNG" {
		t.Fatalf("got %q", out.String())
	}
}

func TestPlanErrorIsNotRetried(t *testing.T) {
	calls := 0
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		calls++
		w.WriteHeader(http.StatusForbidden)
		w.Write([]byte(`{"error":"Plan upgrade required","message":"PDF output requires the basic plan or higher","minimumPlan":"basic"}`))
	}))
	defer srv.Close()

	c := New("test-key")
	c.BaseURL = srv.URL
	err := c.CaptureWithRetry(context.Background(), &bytes.Buffer{}, "https://example.com", Options{Format: "pdf"})

	var apiErr *APIError
	if !errors.As(err, &apiErr) || apiErr.MinimumPlan != "basic" || calls != 1 {
		t.Fatalf("err=%v calls=%d", err, calls)
	}
}

func TestQuotaExhaustedFailsFast(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Retry-After", "1500000")
		w.WriteHeader(http.StatusTooManyRequests)
		w.Write([]byte(`{"error":"Rate limit exceeded","message":"Limit resets at 2026-12-01T00:00:00.000Z"}`))
	}))
	defer srv.Close()

	c := New("test-key")
	c.BaseURL = srv.URL
	err := c.CaptureWithRetry(context.Background(), &bytes.Buffer{}, "https://example.com", Options{})

	var apiErr *APIError
	if !errors.As(err, &apiErr) || apiErr.Status != http.StatusTooManyRequests {
		t.Fatalf("expected a 429 APIError, got %v", err)
	}
}

Error reference

Status Meaning What to do
400 Invalid JSON, an unknown or out-of-range option, or an unsafe URL (private or internal addresses are refused) Fix the request; don't retry
401 Missing or invalid API key Check the key; don't retry
403 The option needs a higher plan (minimumPlan in the body), or the account email is not verified yet Upgrade or verify; don't retry
413 Request body larger than 64 KB Send less (usually a huge javascript or header set)
429 Per-minute limit or monthly quota reached; Retry-After in seconds Retry after a short wait; give up on long waits
500 The capture failed Retry with backoff; failed captures are free
503 Capture proxy unavailable Retry with backoff

Production checklist

  • One shared http.Client with a timeout of about 65 seconds.
  • A context.Context passed into every capture, tied to your shutdown signal.
  • A rate limiter at or below your plan's per-minute limit, plus a cap on in-flight requests.
  • Retries only for 429, 500 and 503, with a cap on Retry-After.
  • io.Copy to the destination, and nothing written before a 200.
  • The API key from an environment variable or secret store, never in source or logs.
  • Async jobs with an Idempotency-Key for slow pages, PDFs and anything that must not be lost.
  • Webhook signatures checked with hmac.Equal on the raw body.

Conclusion

The Screenshotly API needs nothing beyond net/http. Production Go code comes down to context deadlines, typed errors, retries limited to the errors that can succeed, a limiter sized to your plan, and streaming bodies with io.Copy. Start with the quick start, move to the client package when you need retries, and use async jobs once captures get slow or numerous.

Related guides: Python, Node.js, Java and the Go integration page. Create a free account to get 100 captures for testing.

go
golang
tutorial
api
integration

About the Author

Asad Ali

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

Do I need an SDK to call Screenshotly from Go?

No. The API is one JSON POST to https://screenshotly.app/api/screenshot with an x-api-key header, so net/http is enough. The quick start in this guide uses only the standard library; the batch worker adds golang.org/x/sync and golang.org/x/time.

Should I reuse http.Client across capture calls?

Yes. Create one client with a timeout and share it. A new client per request loses connection reuse. The client package in this guide holds one http.Client with a 65-second timeout, because a capture can take tens of seconds.

How should a Go worker handle 429 responses?

Read the Retry-After header. A short value means you hit the per-minute limit, so wait and retry. A very long value means the monthly quota is used up and retrying cannot succeed, so return the error. The CaptureWithRetry function in this guide waits at most one minute.

Why use io.Copy instead of io.ReadAll on the response body?

io.ReadAll holds the whole file in memory before you write it anywhere. io.Copy streams it to a file, an upload or an http.ResponseWriter, which matters for full-page captures and PDFs when many workers run at once.

How many captures can I run in parallel?

It depends on your plan's per-minute limit: Free 5, Basic 40, Growth 80, Scale 200 requests per minute. Use a rate limiter for requests per minute and a separate cap on how many requests are in flight, as the batch example does.

Ready to capture your first screenshot?

Get started with 100 free screenshots. No credit card required.

Related Articles