Skip to content

Official Python SDK for SnapAPI - Screenshots, PDF, Video, Extract & AI Analysis

License

Notifications You must be signed in to change notification settings

Sleywill/snapapi-python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

snapapi

Official Python SDK for SnapAPI - Lightning-fast screenshot, PDF, video, extraction & AI analysis API.

Installation

pip install snapapi

Or from GitHub:

pip install git+https://github.com/Sleywill/snapapi-python

Quick Start

from snapapi import SnapAPI

client = SnapAPI(api_key='sk_live_xxx')

# Capture a screenshot
screenshot = client.screenshot(url='https://example.com')
with open('screenshot.png', 'wb') as f:
    f.write(screenshot)

API Endpoints

Endpoint Method Description
/v1/ping ping() Health check
/v1/screenshot screenshot() Screenshot (PNG/JPEG/WebP/AVIF/PDF)
/v1/pdf pdf() Dedicated PDF generation
/v1/screenshot/batch batch() Batch screenshots (up to 10 URLs)
/v1/video video() Video recording with scroll
/v1/extract extract() Content extraction
/v1/analyze analyze() AI-powered analysis
/v1/usage get_usage() Usage statistics
/v1/devices get_devices() Device presets
/v1/capabilities get_capabilities() API capabilities
/v1/screenshot (async) screenshot_async() Async screenshot
/v1/screenshot/async/{id} get_async_status() Poll async job

Usage Examples

Screenshots

# Basic PNG
data = client.screenshot(url='https://example.com')

# Different formats
jpeg = client.screenshot(url='https://example.com', format='jpeg', quality=80)
webp = client.screenshot(url='https://example.com', format='webp', quality=90)
avif = client.screenshot(url='https://example.com', format='avif')

# Full page
data = client.screenshot(url='https://example.com', full_page=True)

# Device preset
data = client.screenshot_device(url='https://example.com', device='iphone-15-pro')

# Dark mode
data = client.screenshot(url='https://example.com', dark_mode=True)

# Element capture
data = client.screenshot(url='https://example.com', selector='h1')

# Clip region
data = client.screenshot(url='https://example.com',
                          clip_x=0, clip_y=0, clip_width=400, clip_height=300)

# Mobile emulation
data = client.screenshot(url='https://example.com',
                          width=375, height=812,
                          device_scale_factor=3.0,
                          is_mobile=True, has_touch=True)

# Custom CSS & JavaScript
data = client.screenshot(url='https://example.com',
                          css='body { background: red !important; }',
                          javascript='document.querySelector(".popup")?.remove()')

# Block ads, trackers, cookie banners, chat widgets
data = client.screenshot(url='https://example.com',
                          block_ads=True, block_trackers=True,
                          block_cookie_banners=True, block_chat_widgets=True)

# Hide specific elements
data = client.screenshot(url='https://example.com',
                          hide_selectors=['#banner', '.sidebar'])

# Wait options
data = client.screenshot(url='https://example.com',
                          delay=1000,
                          wait_for_selector='#content',
                          wait_until='networkidle')

# Custom headers, user agent, timezone, locale
data = client.screenshot(url='https://example.com',
                          user_agent='MyBot/1.0',
                          extra_headers={'Accept-Language': 'de-DE'},
                          timezone='Europe/Berlin',
                          locale='de-DE')

# Landscape orientation
data = client.screenshot(url='https://example.com',
                          is_landscape=True, width=812, height=375)

# Reduced motion
data = client.screenshot(url='https://example.com', reduced_motion=True)

From HTML or Markdown

# From HTML
data = client.screenshot_from_html(
    html='<h1 style="color:blue">Hello!</h1><p>Generated by SDK</p>'
)

# From Markdown
data = client.screenshot_from_markdown(
    markdown='# Hello World\n\n**Bold** text\n- Item 1\n- Item 2'
)

JSON Response with Metadata

result = client.screenshot(
    url='https://example.com',
    response_type='json',
    include_metadata=True,
    extract_metadata=ExtractMetadata(
        fonts=True, colors=True, links=True, http_status_code=True
    )
)
print(result.success)           # True
print(result.width, result.height)  # 1280 800
print(result.file_size)         # bytes
print(result.took)              # ms
print(result.data)              # base64 image data
print(result.metadata.title)    # page title
print(result.metadata.fonts)    # ['Arial', ...]
print(result.metadata.colors)   # ['#ffffff', ...]

Thumbnails

from snapapi.types import ThumbnailOptions

result = client.screenshot(
    url='https://example.com',
    response_type='json',
    thumbnail=ThumbnailOptions(enabled=True, width=200, height=150, fit='cover')
)
print(result.thumbnail)  # base64 thumbnail

Cookies (Authenticated Pages)

from snapapi.types import Cookie

data = client.screenshot(
    url='https://example.com/dashboard',
    cookies=[Cookie(name='session', value='abc123', domain='example.com')]
)

PDF Generation

from snapapi.types import PdfOptions

# Basic PDF
pdf = client.pdf(url='https://example.com')

# With options
pdf = client.pdf(
    url='https://example.com',
    pdf_options=PdfOptions(
        page_size='a4',
        landscape=True,
        print_background=True,
        margin_top='20mm',
        margin_bottom='20mm',
        margin_left='15mm',
        margin_right='15mm',
        scale=0.8
    )
)

# PDF from HTML
pdf = client.pdf(
    html='<h1>Invoice #123</h1><p>Total: $99.99</p>',
    pdf_options=PdfOptions(page_size='letter')
)

with open('document.pdf', 'wb') as f:
    f.write(pdf)

Video Recording

# Basic video (duration in seconds, 1-30)
video = client.video(url='https://example.com', duration=5)
with open('capture.mp4', 'wb') as f:
    f.write(video)

# Scroll animation video
video = client.video(
    url='https://example.com',
    duration=10,
    scroll=True,
    scroll_duration=1500,
    scroll_easing='ease_in_out',
    scroll_back=True
)

# GIF format
gif = client.video(url='https://example.com', format='gif', duration=3, fps=10)

# JSON response with metadata
result = client.video(url='https://example.com', duration=3, response_type='json')
print(result.success, result.format, result.file_size)

Batch Screenshots

# Submit batch job
batch = client.batch(
    urls=['https://example.com', 'https://httpbin.org/html'],
    format='png',
    dark_mode=True,
    block_ads=True
)
print(batch.job_id, batch.status)

# Poll for completion
import time
while True:
    status = client.get_batch_status(batch.job_id)
    if status.status in ('completed', 'failed'):
        for item in status.results:
            print(f'{item.url}: {item.status}')
        break
    time.sleep(2)

Content Extraction

# Convenience methods for each type
result = client.extract_markdown(url='https://example.com')
result = client.extract_text(url='https://example.com')
result = client.extract_article(url='https://blog.example.com/post')
result = client.extract_structured(url='https://example.com')
result = client.extract_links(url='https://example.com')
result = client.extract_images(url='https://example.com')
result = client.extract_metadata(url='https://example.com')

# Full control
result = client.extract(
    url='https://example.com',
    type='html',           # markdown|text|html|article|structured|links|images|metadata
    selector='article',
    block_ads=True,
    block_cookie_banners=True,
    clean_output=True,
    max_length=5000
)
print(result.success, result.type, result.content)

AI Analysis

# Basic analysis (requires provider API key)
result = client.analyze(
    url='https://example.com',
    prompt='Summarize this page in one sentence',
    provider='openai',
    api_key='sk-...'
)
print(result.result)

# Structured JSON output
result = client.analyze(
    url='https://example.com/products',
    prompt='Extract product names and prices',
    provider='openai',
    api_key='sk-...',
    json_schema={
        'type': 'object',
        'properties': {
            'products': {
                'type': 'array',
                'items': {
                    'type': 'object',
                    'properties': {
                        'name': {'type': 'string'},
                        'price': {'type': 'number'}
                    }
                }
            }
        }
    }
)

# With screenshot and metadata
result = client.analyze(
    url='https://example.com',
    prompt='Describe the visual layout',
    provider='anthropic',
    api_key='sk-ant-...',
    include_screenshot=True,
    include_metadata=True
)

Async Screenshots

# Submit async job
job = client.screenshot_async(url='https://example.com')
job_id = job['jobId']

# Poll for result
import time
while True:
    status = client.get_async_status(job_id)
    if status['status'] == 'completed':
        print(f"Done! Size: {status['fileSize']} bytes")
        break
    time.sleep(1)

Utility Endpoints

# Ping
result = client.ping()  # {'status': 'ok', 'timestamp': ...}

# Usage stats
usage = client.get_usage()
print(f'{usage.used}/{usage.limit} used, {usage.remaining} remaining')
print(f'Resets: {usage.reset_at}')

# Device presets
devices = client.get_devices()
for category, device_list in devices.devices.items():
    print(f'{category}: {len(device_list)} devices')

# Capabilities
caps = client.get_capabilities()
print(caps.version, caps.capabilities)

Error Handling

from snapapi import SnapAPI, SnapAPIError

try:
    client.screenshot(url='invalid-url')
except SnapAPIError as e:
    print(e.code)        # 'VALIDATION_ERROR'
    print(e.status_code) # 400
    print(e.message)     # Error message
    print(e.details)     # Additional details
Code Status Description
VALIDATION_ERROR 400 Invalid parameters
UNAUTHORIZED 401 Invalid API key
FORBIDDEN 403 Feature requires higher plan
QUOTA_EXCEEDED 402 Monthly quota exceeded
TOO_MANY_REQUESTS 429 Rate limit exceeded
INTERNAL_SERVER_ERROR 500 Server error

Type Hints

Full type hints included for IDE support:

from snapapi import SnapAPI, ScreenshotResult
from snapapi.types import (
    ScreenshotOptions, PdfOptions, ThumbnailOptions,
    ExtractMetadata, Cookie, HttpAuth, ProxyConfig,
    Geolocation, VideoOptions, VideoResult,
    BatchOptions, BatchResult, ExtractOptions, ExtractResult,
    AnalyzeOptions, AnalyzeResult
)

License

MIT

About

Official Python SDK for SnapAPI - Screenshots, PDF, Video, Extract & AI Analysis

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages