🐍 Python SDK — Quick Start

Install the SnapAPI Python SDK and start capturing screenshots, generating PDFs, and extracting web content. Supports sync and async.

On This Page

Installation

Install the official SnapAPI package from PyPI:

pip install snapapi

Requires Python 3.7+. For async support, install with extras:

pip install snapapi[async]

Authentication

Get your API key from the SnapAPI dashboard and initialize the client:

import snapapi
import os

# Initialize with your API key
client = snapapi.Client("YOUR_API_KEY")

# Or use environment variable (recommended)
client = snapapi.Client(os.environ["SNAPAPI_KEY"])
💡 Tip: Use python-dotenv to load API keys from a .env file in development.

Take Screenshots

Basic Screenshot

import snapapi
import os

client = snapapi.Client(os.environ["SNAPAPI_KEY"])

# Capture a screenshot
screenshot = client.screenshot(
    url="https://example.com",
    format="png",
    width=1280,
    height=800
)

# Save to file
with open("screenshot.png", "wb") as f:
    f.write(screenshot)

print("Screenshot saved!")

Full Page Screenshot

screenshot = client.screenshot(
    url="https://example.com",
    format="png",
    full_page=True,
    width=1280
)

Screenshot with All Options

screenshot = client.screenshot(
    url="https://example.com",
    format="avif",           # png, jpeg, webp, avif
    width=1440,
    height=900,
    full_page=False,
    block_ads=True,           # Block advertisements
    block_cookies=True,       # Block cookie banners
    delay=2000,               # Wait 2s before capture
    device_preset="iPhone15", # Mobile emulation
    css="body { background: white; }",  # Inject CSS
    response_type="url"       # Get hosted URL
)

Get Hosted URL

result = client.screenshot(
    url="https://example.com",
    format="png",
    response_type="url"
)

print(result["url"])
# → https://cdn.snapapi.pics/screenshots/abc123.png

Generate PDFs

pdf = client.pdf(
    url="https://example.com",
    format="A4",
    print_background=True,
    margin={
        "top": "20mm",
        "bottom": "20mm",
        "left": "15mm",
        "right": "15mm"
    }
)

with open("page.pdf", "wb") as f:
    f.write(pdf)

PDF from HTML String

pdf = client.pdf(
    html="<h1>Invoice #1234</h1><p>Total: $99.00</p>",
    format="A4",
    print_background=True
)

Extract Content

Extract clean markdown or structured data from any webpage — perfect for LLM pipelines and data scraping.

content = client.extract(
    url="https://example.com/blog-post",
    format="markdown"
)

print(content["markdown"])
# → # Blog Post Title\n\nArticle content here...

Extract Structured Data

data = client.extract(
    url="https://example.com/product",
    format="structured",
    schema={
        "title": "string",
        "price": "number",
        "description": "string"
    }
)

print(f"Product: {data['title']} - ${data['price']}")

Async Support

Use the async client for high-throughput applications:

import asyncio
import snapapi

async def capture_multiple():
    client = snapapi.AsyncClient(os.environ["SNAPAPI_KEY"])

    urls = [
        "https://example.com",
        "https://github.com",
        "https://news.ycombinator.com"
    ]

    # Capture all screenshots concurrently
    tasks = [
        client.screenshot(url=url, format="png")
        for url in urls
    ]
    results = await asyncio.gather(*tasks)

    for i, screenshot in enumerate(results):
        with open(f"screenshot_{i}.png", "wb") as f:
            f.write(screenshot)

    await client.close()

asyncio.run(capture_multiple())

Error Handling

import snapapi

client = snapapi.Client(os.environ["SNAPAPI_KEY"])

try:
    screenshot = client.screenshot(url="https://example.com")
    with open("screenshot.png", "wb") as f:
        f.write(screenshot)

except snapapi.AuthenticationError:
    print("Invalid API key")

except snapapi.RateLimitError as e:
    print(f"Rate limit exceeded. Retry after {e.retry_after}s")

except snapapi.BadRequestError as e:
    print(f"Bad request: {e.message}")

except snapapi.SnapAPIError as e:
    print(f"API error ({e.status}): {e.message}")
⚠️ Rate Limits: Free tier: 200 requests/month. The SDK automatically includes retry info in rate limit exceptions. Upgrade for higher limits.

Framework Integration

Django View

from django.http import HttpResponse
import snapapi

client = snapapi.Client(os.environ["SNAPAPI_KEY"])

def screenshot_view(request):
    url = request.GET.get("url", "https://example.com")
    image = client.screenshot(url=url, format="png")

    response = HttpResponse(image, content_type="image/png")
    response["Content-Disposition"] = 'attachment; filename="screenshot.png"'
    return response

Flask Route

from flask import Flask, request, send_file
import snapapi
import io

app = Flask(__name__)
client = snapapi.Client(os.environ["SNAPAPI_KEY"])

@app.route("/screenshot")
def screenshot():
    url = request.args.get("url", "https://example.com")
    image = client.screenshot(url=url, format="png")

    return send_file(
        io.BytesIO(image),
        mimetype="image/png",
        download_name="screenshot.png"
    )

Next Steps