Metadata-Version: 2.5
Name: raspbytes
Version: 1.1.0
Summary: Official Python SDK for the Raspbytes API
Project-URL: Documentation, https://docs.raspbytes.com/reference
Project-URL: Homepage, https://raspbytes.com
Project-URL: Issues, https://github.com/raspbytes-labs/python-sdk/issues
Project-URL: Repository, https://github.com/raspbytes-labs/python-sdk
Project-URL: Changelog, https://github.com/raspbytes-labs/python-sdk/blob/main/CHANGELOG.md
Author: Raspbytes
License-Expression: BSD-2-Clause
License-File: LICENSE
Keywords: browser-api,proxy,raspbytes,scraping
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx<1,>=0.27
Provides-Extra: dev
Requires-Dist: mypy<2,>=1.13; extra == 'dev'
Requires-Dist: pytest-asyncio<2,>=1.4.1; extra == 'dev'
Requires-Dist: pytest-cov<8,>=6; extra == 'dev'
Requires-Dist: pytest<9,>=8; extra == 'dev'
Requires-Dist: ruff<1,>=0.8; extra == 'dev'
Requires-Dist: twine<8,>=7; extra == 'dev'
Description-Content-Type: text/markdown

# Raspbytes Python SDK  

The official Python SDK for Raspbytes provides synchronous and asynchronous clients for
Proxies, Browser API, Web Unblocker, and Scraper API. It includes typed requests, structured
API errors, and helpers for polling long-running operations.

## Installation

Requires Python 3.11 or later.

```bash
python -m pip install raspbytes
```

## Authentication

Create an API key in the Raspbytes dashboard and set `RASPBYTES_API_KEY` in your environment.

```bash
export RASPBYTES_API_KEY='rb_live_your_key_here'
```

Both clients read `RASPBYTES_API_KEY` automatically. You can also pass `api_key=` when
creating a client.

## Quick start

Fetch a page with Web Unblocker. The client context manager closes the HTTP connection pool.

```python
from raspbytes import Raspbytes, UnblockRequest

with Raspbytes() as client:
    page = client.unblocker.retrieve(UnblockRequest(url="https://example.com"))

print(page["status"], page["http_status"])
```

## Proxies

```python
from raspbytes import ProxyConnectionParams, Raspbytes

with Raspbytes() as client:
    connection = client.proxies.create(
        ProxyConnectionParams(
            proxy_type="residential",
            country="US",
            protocol="http",
        )
    )
    proxy_url = connection["proxy_url"]
```

Pass `proxy_url` directly to your HTTP client's proxy setting. The URL contains credentials.
Use `proxies.options()` to discover available locations and protocols for your account.
For a sticky connection, provide `session_type="sticky"` and a `session_id`. Use
`release_sticky_session(session_id)` to end the session early.

## Browser API

```python
from raspbytes import BrowserProxy, BrowserSessionParams, Raspbytes

with Raspbytes() as client:
    created = client.browser.create_session(
        BrowserSessionParams(
            browser="chromium",
            proxy=BrowserProxy(type="datacenter", country="GB"),
            session_timeout_seconds=900,
        )
    )
    try:
        session = client.browser.wait_until_ready(created["id"])
        browser_url = session["connection"]["url"]
        # Use browser_url with Playwright's chromium.connect_over_cdp().
    finally:
        client.browser.terminate_session(created["id"])
```

Keep the browser WebSocket URL private. Use `browser.proxy_options()` to discover available
proxy options for your account.

## Web Unblocker

Use `retrieve()` to fetch a page in one request. To submit the request and collect the result
later, use `create_request()` and `wait_for_request()`.

```python
from raspbytes import Raspbytes, UnblockRequest

with Raspbytes() as client:
    queued = client.unblocker.create_request(UnblockRequest(url="https://example.com"))
    completed = client.unblocker.wait_for_request(queued["id"], timeout=120)
```

## Scraper API

Google, Bing, and DuckDuckGo are managed scrapers under `client.scraper`. The managed catalog
exports a typed input dictionary and a revision-pinned handle for each scraper.

```python
from uuid import uuid4

from raspbytes import Raspbytes
from raspbytes.managed_scrapers import GOOGLE_SEARCH, GoogleSearchInputs

with Raspbytes() as client:
    scraper = client.scraper
    inputs = GoogleSearchInputs(
        query="coffee shops in London",
        country="gb",
        language="en",
        device="desktop",
    )
    run = scraper.hub.run_managed(
        GOOGLE_SEARCH,
        inputs,
        idempotency_key=str(uuid4()),
    )
    completed = scraper.runs.wait(run["id"], timeout=90)
    print(completed.get("result"))
```

Use `hub.list()` and `hub.get()` to discover available scrapers, revisions, and input and
output schemas. For private or newly discovered scrapers, pass the Hub ID and inputs to
`hub.run()` or `hub.run_and_wait()`. Use the scraper's output schema to validate the `result`
field for your application.

Use `runs.iterate()` to stream run history across pages and `runs.cancel(run_id)` to cancel a
server-side run. Cancelling an asyncio task stops the local wait. An idempotency key enables
response retries for a submission when the service marks the failure retryable. Use a new key
for each logical run and reuse it when retrying that run.

`COUNTRIES` provides ISO country codes and display names. For managed search scrapers, the
`country` input selects the search market and `configuration.country` sets the execution origin.

### Manage Scraper workflows

Use `scraper.tasks` to save Hub inputs, create revisions, and run a saved task. Use
`scraper.schedules` to run a task on a cadence or submit an immediate run.

```python
from raspbytes import Raspbytes
from raspbytes.managed_scrapers import GOOGLE_SEARCH
from raspbytes.scraper_types import CreateScrapingTaskParams

task_request = CreateScrapingTaskParams(
    scraper=GOOGLE_SEARCH.id,
    revision=GOOGLE_SEARCH.revision,
    name="London coffee shops",
    configuration={
        "inputs": {
            "query": "coffee shops in London",
            "country": "gb",
            "language": "en",
            "device": "desktop",
        }
    },
)

with Raspbytes() as client:
    task = client.scraper.tasks.create(task_request)
    schedule = client.scraper.schedules.create(
        {
            "task": task["id"],
            "name": "Weekday refresh",
            "frequency": "custom",
            "weekdays": [1, 2, 3, 4, 5],
            "timezone": "Europe/London",
            "time_of_day": "09:00:00",
        }
    )
    run = client.scraper.schedules.run_now(schedule["id"])
    finished = client.scraper.runs.wait(run["id"], timeout=90)
    artifacts = client.scraper.storage.list_for_run(finished["id"])
```

- `storage.iterate()` streams retained outputs. `create_download_link()` returns a short-lived
  URL that should be treated as a secret.
- `monitoring.get(scope_type="task", scope_id=task_id, window="24h")` reads task metrics.
  `list_scopes()` discovers available scopes. Policy methods read, patch, or evaluate alerts.
- `builder` manages account-owned scrapers, immutable revisions, access shares, and publication.
- `schedules.pause()` and `schedules.resume()` set an explicit enabled state. Use
  `toggle_pause()` when you want the API to flip the current state.

Request and response types are available from `raspbytes.scraper_types`. With
`AsyncRaspbytes`, await the same methods and use `async for` with `storage.iterate()`.

### Migrating from SERP

Replace `client.serp` with `client.scraper`. Choose `GOOGLE_SEARCH`, `BING_SEARCH`, or
`DUCKDUCKGO_SEARCH` in place of the old engine argument, and consult that scraper's input schema.
Read the output from the completed run's `result` field. Move `SerpConfig` to
`RaspbytesConfig(scraper=ScraperConfig(...))`.

## Async client

The async client exposes the same resource and method names:

```python
import asyncio

from raspbytes import AsyncRaspbytes


async def main() -> None:
    async with AsyncRaspbytes() as client:
        result = await client.scraper.hub.list(scope="raspbytes")
        print(result)


asyncio.run(main())
```

## Configuration

Use `RaspbytesConfig` to share defaults across products, then configure individual products
with `ProxyConfig`, `BrowserConfig`, `UnblockerConfig`, or `ScraperConfig`. Both clients
accept the same configuration objects.

```python
from raspbytes import BrowserConfig, Raspbytes, RaspbytesConfig

config = RaspbytesConfig(
    timeout=30,
    max_retries=2,
    browser=BrowserConfig(timeout=120, poll_timeout=90, poll_interval=0.5),
)

with Raspbytes(config=config) as client:
    options = client.browser.proxy_options()
```

Product settings override constructor arguments for that product. Constructor arguments override
values in `RaspbytesConfig`. A polling argument such as `timeout=` on `scraper.runs.wait()`
applies to that call. The default API root is `https://api.raspbytes.com/api/v1/`.

## Errors

```python
from raspbytes import APIError, Raspbytes, RateLimitError, ScraperRunError

try:
    with Raspbytes() as client:
        client.scraper.runs.wait("run_id_from_submission", timeout=30)
except ScraperRunError as exc:
    print(exc.request_id, exc.status, exc.code, exc.retryable)
except RateLimitError as exc:
    print(exc.status_code, exc.code, exc.request_id)
except APIError as exc:
    print(exc.status_code, exc.message, exc.body)
```

`APIError` exposes the HTTP status, message, and response body. The SDK raises more specific
exceptions for common failures such as rate limits. It retries connection establishment failures
and API responses marked as retryable, subject to the configured retry limit.

## Resources

- [Raspbytes API reference](https://docs.raspbytes.com/reference) for endpoints and schemas
- [Changelog](CHANGELOG.md) for SDK changes
- [BSD 2-Clause license](LICENSE)
- [Contributing](CONTRIBUTING.md) for SDK development
