screenshotapi

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 11 Imported by: 0

README

ScreenshotAPI Go SDK

Official Go SDK for ScreenshotAPI. Capture website screenshots, PDFs, and HTML renders from Go with the standard library only.

Go Reference

Installation

go get github.com/miketromba/screenshotapi-go
import screenshotapi "github.com/miketromba/screenshotapi-go"

Requires Go 1.21 or later.

Authentication

Create an API key from the ScreenshotAPI dashboard, then keep it in an environment variable:

export SCREENSHOTAPI_KEY="sk_live_your_key_here"

The SDK sends the key in the x-api-key header. Never commit live keys to source control.

First Screenshot

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	screenshotapi "github.com/miketromba/screenshotapi-go"
)

func main() {
	apiKey := os.Getenv("SCREENSHOTAPI_KEY")
	if apiKey == "" {
		log.Fatal("SCREENSHOTAPI_KEY is required")
	}

	client := screenshotapi.NewClient(apiKey)
	metadata, err := client.Save(context.Background(), screenshotapi.ScreenshotOptions{
		URL: "https://example.com",
	}, "screenshot.png")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Saved screenshot.png, credits remaining: %d\n", metadata.CreditsRemaining)
}

Advanced Options

Use Screenshot when you want the image bytes in memory:

result, err := client.Screenshot(ctx, screenshotapi.ScreenshotOptions{
	URL:                 "https://example.com",
	Width:               1440,
	Height:              900,
	FullPage:            true,
	Type:                screenshotapi.WebP,
	Quality:             85,
	ColorScheme:         screenshotapi.Dark,
	WaitUntil:           screenshotapi.NetworkIdle2,
	WaitForSelector:     "#app-ready",
	Delay:               250,
	BlockAds:            true,
	RemoveCookieBanners: true,
	CSSInject:           ".newsletter-modal { display: none !important; }",
	JSInject:            "document.body.dataset.capture = 'true'",
	StealthMode:         true,
	DevicePixelRatio:    2,
	Timezone:            "America/New_York",
	Locale:              "en-US",
	CacheTTL:            300,
	PreloadFonts:        true,
	RemoveElements:      []string{".popup", "#promo-banner"},
	RemovePopups:        true,
	Geolocation: &screenshotapi.Geolocation{
		Latitude:  37.7749,
		Longitude: -122.4194,
		Accuracy:  25,
	},
})
if err != nil {
	return err
}

fmt.Println(result.ContentType)
fmt.Println(result.Metadata.ScreenshotID)

Render raw HTML with a POST request by setting HTML:

result, err := client.Screenshot(ctx, screenshotapi.ScreenshotOptions{
	HTML: "<main><h1>Hello from Go</h1></main>",
	Type: screenshotapi.PDF,
})

Device mockups are available with MockupDevice: screenshotapi.BrowserMockup, IPhoneMockup, or MacBookMockup. Do not combine mockups with FullPage or Type: screenshotapi.PDF.

See the Go SDK docs and Screenshot API reference for the full parameter reference.

Error Handling

The SDK returns typed errors for common API failures:

import "errors"

result, err := client.Screenshot(ctx, screenshotapi.ScreenshotOptions{
	URL: "https://example.com",
})
if err != nil {
	var authErr *screenshotapi.AuthenticationError
	var creditsErr *screenshotapi.InsufficientCreditsError
	var keyErr *screenshotapi.InvalidAPIKeyError
	var failedErr *screenshotapi.ScreenshotFailedError

	switch {
	case errors.As(err, &authErr):
		// 401: API key missing or malformed.
	case errors.As(err, &creditsErr):
		fmt.Printf("Out of credits, balance: %d\n", creditsErr.Balance)
	case errors.As(err, &keyErr):
		// 403: API key revoked or invalid.
	case errors.As(err, &failedErr):
		// 500: Screenshot capture failed server-side.
	default:
		// Network errors, validation errors, or other API responses.
	}
}

_ = result

When contacting support, include result.Metadata.ScreenshotID if a request reached the API.

Client Configuration

client := screenshotapi.NewClient(apiKey,
	screenshotapi.WithTimeout(30*time.Second),
	screenshotapi.WithBaseURL("https://screenshotapi.to"),
	screenshotapi.WithHTTPClient(&http.Client{Timeout: 30 * time.Second}),
)

WithBaseURL is mainly for proxies, private gateways, and tests. The default is https://screenshotapi.to.

Pricing And Free Tier

New accounts include 200 free screenshots per month with no credit card required. Create a free account or review pricing and credit packs when you are ready to scale.

Support

Development

go test ./...
go vet ./...

Tests use httptest and do not call the live ScreenshotAPI service.

License

MIT

Documentation

Overview

Package screenshotapi provides a Go client for the ScreenshotAPI service.

Index

Examples

Constants

View Source
const DefaultBaseURL = "https://screenshotapi.to"
View Source
const DefaultTimeout = 60 * time.Second

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Code       string
	Message    string
}

APIError is the base error type for all ScreenshotAPI errors.

func (*APIError) Error

func (e *APIError) Error() string

type AuthenticationError

type AuthenticationError struct {
	APIError
}

AuthenticationError indicates a missing or malformed API key (HTTP 401).

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a ScreenshotAPI client.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient creates a new ScreenshotAPI client.

func (*Client) Save

func (c *Client) Save(ctx context.Context, opts ScreenshotOptions, path string) (*Metadata, error)

Save takes a screenshot and saves it to the specified file path.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"os"

	screenshotapi "github.com/miketromba/screenshotapi-go"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "image/png")
		w.Header().Set("x-credits-remaining", "199")
		w.Header().Set("x-screenshot-id", "ss_example")
		w.Header().Set("x-duration-ms", "450")
		_, _ = w.Write([]byte("png"))
	}))
	defer server.Close()

	file, err := os.CreateTemp("", "screenshotapi-*.png")
	if err != nil {
		log.Fatal(err)
	}
	path := file.Name()
	_ = file.Close()
	defer os.Remove(path)

	client := screenshotapi.NewClient(
		"sk_test_abc123",
		screenshotapi.WithBaseURL(server.URL),
	)
	metadata, err := client.Save(context.Background(), screenshotapi.ScreenshotOptions{
		URL: "https://example.com",
	}, path)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Credits remaining: %d\n", metadata.CreditsRemaining)

}
Output:
Credits remaining: 199

func (*Client) Screenshot

func (c *Client) Screenshot(ctx context.Context, opts ScreenshotOptions) (*Result, error)

Screenshot takes a screenshot with the given options.

Example (AdvancedOptions)
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"

	screenshotapi "github.com/miketromba/screenshotapi-go"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "image/webp")
		w.Header().Set("x-credits-remaining", "198")
		w.Header().Set("x-screenshot-id", "ss_advanced")
		w.Header().Set("x-duration-ms", "875")
		_, _ = w.Write([]byte("webp"))
	}))
	defer server.Close()

	client := screenshotapi.NewClient(
		"sk_test_abc123",
		screenshotapi.WithBaseURL(server.URL),
	)
	result, err := client.Screenshot(context.Background(), screenshotapi.ScreenshotOptions{
		URL:                 "https://example.com",
		Width:               1440,
		Height:              900,
		FullPage:            true,
		Type:                screenshotapi.WebP,
		Quality:             85,
		ColorScheme:         screenshotapi.Dark,
		WaitUntil:           screenshotapi.NetworkIdle2,
		BlockAds:            true,
		RemoveCookieBanners: true,
		DevicePixelRatio:    2,
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s %s\n", result.ContentType, result.Metadata.ScreenshotID)

}
Output:
image/webp ss_advanced
Example (ErrorHandling)
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	screenshotapi "github.com/miketromba/screenshotapi-go"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusPaymentRequired)
		_, _ = w.Write([]byte(`{"error":"Insufficient credits","creditBalance":0}`))
	}))
	defer server.Close()

	client := screenshotapi.NewClient(
		"sk_test_abc123",
		screenshotapi.WithBaseURL(server.URL),
	)
	_, err := client.Screenshot(context.Background(), screenshotapi.ScreenshotOptions{
		URL: "https://example.com",
	})

	var creditsErr *screenshotapi.InsufficientCreditsError
	if errors.As(err, &creditsErr) {
		fmt.Printf("out of credits: %d\n", creditsErr.Balance)
	}

}
Output:
out of credits: 0

type ColorScheme

type ColorScheme string
const (
	Light ColorScheme = "light"
	Dark  ColorScheme = "dark"
)

type Geolocation

type Geolocation struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	Accuracy  float64 `json:"accuracy,omitempty"`
}

Geolocation configures browser geolocation emulation.

type ImageType

type ImageType string
const (
	PNG  ImageType = "png"
	JPEG ImageType = "jpeg"
	WebP ImageType = "webp"
	PDF  ImageType = "pdf"
)

type InsufficientCreditsError

type InsufficientCreditsError struct {
	APIError
	Balance int
}

InsufficientCreditsError indicates the account has no credits remaining (HTTP 402).

func (*InsufficientCreditsError) Error

func (e *InsufficientCreditsError) Error() string

type InvalidAPIKeyError

type InvalidAPIKeyError struct {
	APIError
}

InvalidAPIKeyError indicates the API key is revoked or invalid (HTTP 403).

type Metadata

type Metadata struct {
	CreditsRemaining int
	ScreenshotID     string
	DurationMs       int
}

Metadata contains response metadata from a screenshot request.

type MockupDevice

type MockupDevice string
const (
	BrowserMockup MockupDevice = "browser"
	IPhoneMockup  MockupDevice = "iphone"
	MacBookMockup MockupDevice = "macbook"
)

type Option

type Option func(*Client)

Option configures a Client.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets a custom base URL for the API.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) Option

WithHTTPClient sets a custom HTTP client.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the HTTP client timeout.

type Result

type Result struct {
	Image       []byte
	ContentType string
	Metadata    Metadata
}

Result contains the screenshot image data and metadata.

type ScreenshotFailedError

type ScreenshotFailedError struct {
	APIError
}

ScreenshotFailedError indicates the screenshot capture failed server-side (HTTP 500).

type ScreenshotOptions

type ScreenshotOptions struct {
	URL                 string
	HTML                string
	Width               int
	Height              int
	FullPage            bool
	Type                ImageType
	Quality             int
	ColorScheme         ColorScheme
	WaitUntil           WaitUntil
	WaitForSelector     string
	Delay               int
	BlockAds            bool
	RemoveCookieBanners bool
	CSSInject           string
	JSInject            string
	StealthMode         bool
	DevicePixelRatio    int
	Timezone            string
	Locale              string
	CacheTTL            int
	PreloadFonts        bool
	RemoveElements      []string
	RemovePopups        bool
	MockupDevice        MockupDevice
	Geolocation         *Geolocation
}

ScreenshotOptions configures a screenshot request.

type WaitUntil

type WaitUntil string
const (
	Load             WaitUntil = "load"
	DOMContentLoaded WaitUntil = "domcontentloaded"
	NetworkIdle0     WaitUntil = "networkidle0"
	NetworkIdle2     WaitUntil = "networkidle2"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL