Solari

Browsers

solari-browser: classes Solari and BrowserSession. See the Python SDK hub for install and configuration.

pip install solari-browser
Requires Python 3.10 or newer
solari-browser needs Python 3.10+: it depends on patchright 1.62, which does not support 3.9. On Python 3.9 pip install solari-browser fails with ResolutionImpossible instead of installing anything.

Contents

Solari

The browser client. Creates sessions and manages profiles.

Properties

  • sessions _Sessions: session create/release/replay calls.
  • profiles _Profiles: stored browser profile CRUD.
  • base_url str: the resolved gateway base URL, read-only.

Constructors

Solari()

Solari(
    api_key: str,
    *,
    region: str = "us-west",
    base_url: str | None = None,
    max_attempts: int = 2,
    backoff_ms: int = 500,
    timeout_ms: int = 90_000,
) -> Solari

Creates a client. Does not open any connection.

Parameters:

  • api_key str: required; the only positional argument.
  • region str: "us-west" only. Ignored when base_url is set.
  • base_url str | None: override the resolved region URL.
  • max_attempts, backoff_ms, timeout_ms int: retry policy; see request().

Returns: Solari

Raises: SolariError if api_key is empty or region is unknown.

Example:

from solari_browser import Solari

solari = Solari(api_key="slr_live_...")

# or as an async context manager, which closes the client on exit
async with Solari(api_key="slr_live_...") as solari:
    ...

Methods

launch()

async launch(
    *,
    profile_id: str | None = None,
    recording: bool = False,
    stealth: bool = False,
    captcha: bool = False,
    proxy: str | ProxyRequest | None = None,
    session_timeout_ms: int | None = None,
    keep_alive: bool = False,
    user_metadata: dict | None = None,
    block_heavy: bool | dict | None = None,
    retries: int = 0,
    probe: bool | None = None,
    probe_timeout_ms: int = 2_000,
) -> BrowserSession

Creates a session and connects to it over the Playwright wire protocol, returning a BrowserSession that wraps a real patchright Browser.

Parameters:

  • profile_id, recording, stealth, captcha, proxy, session_timeout_ms, keep_alive, user_metadata, block_heavy: identical to sessions.create().
  • retries int: extra re-launch attempts. Default 0.
  • probe bool | None: probe the browser before returning. Defaults to True when retries > 0.
  • probe_timeout_ms int: probe cap. Default 2_000.

Returns: BrowserSession

Raises: the last connect error once attempts are spent; SolariError with code == BROWSER_UNHEALTHY if the probe fails; SolariError if patchright is not installed.

Example:

browser = await solari.launch(stealth=True, retries=2)
page = await browser.new_page()
await page.goto("https://example.com")
await browser.close()
retries only re-runs launch
Each retry calls sessions.create() again and sleeps 0.1s × attempt, and only for a health failure or a transient connect error. It does not change sessions.create()’s own HTTP retry policy. launch() connects through patchright (a Playwright client); the Go, Rust and C++ SDKs have their own launch helpers, see the SDK capabilities matrix.

close()

async close() -> None

Closes the HTTP client and, if launch() was used, stops the patchright driver. It does not release live sessions.

Returns: None

Example:

await browser.close()  # release the session first
await solari.close()   # then shut the client down

request()

async request(method: str, path: str, body: Any | None = None) -> httpx.Response

Low-level authenticated call against the API, with the client’s retry and timeout policy applied. An escape hatch for endpoints the SDK does not wrap.

Parameters:

  • method str: HTTP verb.
  • path str: path appended to base_url, e.g. /sessions.
  • body Any | None: JSON-serialized when present.

Returns: httpx.Response, the raw response. A non-2xx is returned, not raised.

Raises: SolariError only when all attempts are exhausted.

Example:

res = await solari.request("GET", "/profiles")
print(res.status_code, res.json())
Retry policy
502, 503, 504, and 507 (and transport errors) are retried, with a fixed backoff_ms sleep, not exponential. 507 is included although this gateway never emits one; it’s the desktop gateway’s transient InsufficientCapacity, kept so the client is correct regardless of which gateway build it reaches. A plain 500 is not retried, and neither is a 5xx the gateway marks retryable: false (or a 503 ProxyTierUnavailable). A response with any other status is retried only when its body says retryable: true and the request is safe to replay (a GET/DELETE/PUT, or a POST carrying an idempotency key, as POST /sessions does). max_attempts=2 means one retry. timeout_ms is per attempt. A 429 is not retried unless the gateway marks it retryable.

sessions.create()

async sessions.create(
    *,
    profile_id: str | None = None,
    recording: bool = False,
    stealth: bool = False,
    captcha: bool = False,
    proxy: str | ProxyRequest | None = None,
    session_timeout_ms: int | None = None,
    keep_alive: bool = False,
    user_metadata: dict | None = None,
    block_heavy: bool | dict | None = None,
) -> Session

Acquires a browser session without connecting. Use it when you want to drive the endpoints yourself; otherwise use launch().

Parameters:

  • profile_id str | None: attach a stored profile.
  • recording bool: record the session.
  • stealth bool: enable the runtime stealth shim.
  • captcha bool: managed captcha solving. Requires stealth.
  • proxy str | ProxyRequest | None: a country code ("us"), a ProxyRequest, or the "off" / "smart" sentinels. Requires stealth.
  • session_timeout_ms int | None: end the session earlier than the plan maximum, in milliseconds. Rounded up to whole seconds; the gateway refuses anything under 60 000 (a 400, not clamped). None or 0 leaves the plan maximum; a negative, fractional or non-int value raises SolariError before any request.
  • keep_alive bool: keep the session when the client disconnects, so it can reconnect. The hold ends session_timeout_ms after the session was created (an hour after creation when unset, never past the plan maximum) or when it is released; expires_at is the hard deadline, not the hold. A host can be replaced by scale-in or repair, which ends the sessions on it.
  • user_metadata dict | None: a JSON object stored with the session and echoed on Session.user_metadata. See sessions.list() for when it comes back.
  • block_heavy bool | dict | None: skip heavy files so a proxied session does not pay proxy bandwidth for them. True blocks video/audio and images over 100 KB; a dict overlays that with media, fonts and image_max_bytes (an unknown key raises). Blocked requests fail inside the browser.

Returns: Session

Raises: SolariError carrying status and the server code (e.g. FeatureRequiresPlan, ConcurrencyLimitExceeded).

Example:

session = await solari.sessions.create(stealth=True, proxy="us")
# connect with any Playwright-compatible client
browser = await chromium.connect(session.ws_endpoint)
captcha and proxy require stealth
captcha=True and any proxy request are rejected unless stealth=True is also set.
Checking proxy availability
await solari.proxy.countries() returns GET /proxy/countries: the egress countries this gateway supports right now, and whether residential proxy credentials are configured, so you can pick a proxy value you know will resolve before you spend a session on it.

sessions.release()

async sessions.release(session_id: str) -> None

Best-effort release. Failures are logged rather than raised. Use release_and_wait() when you need confirmation.

Parameters:

  • session_id str: session id.

Returns: None

Example:

await solari.sessions.release(session.id)

sessions.release_and_wait()

async sessions.release_and_wait(session_id: str) -> None

Releases a session and waits for the server to confirm. A bare 404 (the session is already gone) is success; a 404 with code InvalidSessionId is not: the gateway refused the id and released nothing, so it raises.

Parameters:

  • session_id str: session id.

Returns: None

Raises: SolariError on any other error status, and on a 404 InvalidSessionId.

Example:

await solari.sessions.release_and_wait(session.id)
# the replay is available ~1-3s later

sessions.get()

async sessions.get(session_id: str) -> dict

Fetches the raw session view from GET /sessions/:id.

Parameters:

  • session_id str: session id.

Returns: dict, the decoded JSON body.

Raises: SolariError on any error status.

The endpoint answers from gateway state with status one of active, released (ended by a release or server-side; terminal), expired, or unknown (owning pool not registered on the answering replica). A well-formed id from your own org never 404s; polling until released confirms a release. See the endpoint reference.

view = await solari.sessions.get(session.id)
if view["status"] == "released":
    ...  # release confirmed

The view carries the userMetadata you set at create. While the session is active it also carries the websocket endpoints. Once the session has been released the endpoints are gone, but userMetadata stays on the view.

sessions.list()

async sessions.list(
    *,
    limit: int | None = None,
    cursor: str | None = None,
    metadata: dict[str, str] | None = None,
) -> SessionList

One page of your organisation’s sessions (GET /sessions). Rows never carry the websocket endpoints, because those are bearer capabilities: call get() for a single session’s.

Parameters:

  • limit int | None, cursor str | None: page size, and the previous page’s next_cursor.
  • metadata dict[str, str] | None: keep sessions whose user_metadata has all these string values (at most 10 pairs; keys of 1–128 characters, and no single quote in a key or value).

Returns: SessionList: sessions (each with id, status, kind, created_at, expires_at, user_metadata) and next_cursor (None on the last page).

Raises: SolariError on any error status.

page = await solari.sessions.list(limit=50, metadata={"job": "nightly-42"})
for s in page.sessions:
    print(s.id, s.status, s.user_metadata)
user_metadata is kept after release
user_metadata comes back from list() and get() for a released session too: it stays in the list with status released and its metadata intact.

sessions.get_replay_url()

async sessions.get_replay_url(session_id: str) -> ReplayUrl

Returns a presigned URL for a recorded session’s replay. Requires recording=True at create time.

Parameters:

  • session_id str: session id.

Returns: ReplayUrl: url, expires_in_seconds, content_encoding: the actual encoding of the bytes url will serve ("identity" on GCP, "gzip" on AWS). Check this before decompressing.

Raises: SolariError if the replay is not ready or does not exist.

Example:

replay = await solari.sessions.get_replay_url(session.id)
print(replay.url, replay.expires_in_seconds)

sessions.download_replay()

async sessions.download_replay(session_id: str) -> bytes

Resolves the replay URL and downloads the NDJSON bytes in one call.

Parameters:

  • session_id str: session id.

Returns: bytes. Plain NDJSON on GCP, gzipped on AWS; check content_encoding from get_replay_url() before decompressing; this function does not decompress for you.

Raises: SolariError if the download fails.

Example:

data = await solari.sessions.download_replay(session.id)
with open("replay.ndjson.gz", "wb") as f:
    f.write(data)

profiles.create()

async profiles.create(name: str) -> Profile

Creates an empty profile. Attach it to a session with profile_id to persist cookies and localStorage.

Parameters:

  • name str: human-facing name.

Returns: Profile

Raises: SolariError with the server code on failure.

Example:

profile = await solari.profiles.create("logged-in")
browser = await solari.launch(profile_id=profile.id)

profiles.list()

async profiles.list() -> list[Profile]

Lists every profile on the account.

Returns: list[Profile]

Example:

for p in await solari.profiles.list():
    print(p.id, p.name)

profiles.save()

async profiles.save(profile_id: str, storage_state: StorageState) -> SaveResult

Overwrites a profile with the given storage state. Pair it with Playwright’s context.storage_state() to snapshot a logged-in session.

Parameters:

  • profile_id str: profile id.
  • storage_state StorageState: a plain dict of cookies + origins.

Returns: SaveResult: version, size_bytes.

Raises: SolariError on a non-2xx response.

Example:

state = await browser.context.storage_state()
result = await solari.profiles.save(profile.id, state)
print(result.version, result.size_bytes)

profiles.delete()

async profiles.delete(profile_id: str) -> None

Deletes a profile. Idempotent, so a 404 is success.

Parameters:

  • profile_id str: profile id.

Returns: None

Example:

await solari.profiles.delete(profile.id)

BrowserSession

A live browser and its session. Returned by launch(); not constructed directly. Works as an async context manager, which calls close() on exit.

Properties

  • session Session: the raw session record.
  • id str: session id.
  • expires_at str: ISO 8601 UTC deadline; the session auto-releases then.
  • proxy ResolvedProxyConfig | None: the resolved timezone, country and tier, when a proxy was requested (no credentials; see ResolvedProxyConfig).
  • ws_endpoint str: upstream Playwright wire-protocol endpoint.
  • cdp_endpoint str: upstream raw-CDP endpoint.
  • context BrowserContext | None: the session’s primary context, the one carrying the attached profile’s cookies and localStorage and the proxy timezone.
  • raw Browser: the underlying patchright Browser, for APIs this wrapper does not surface.
Endpoints are upstream URLs, unlike TypeScript
ws_endpoint and cdp_endpoint point straight at the gateway. The TypeScript SDK rewrites them to a loopback proxy it runs in-process; Python deliberately does not, so these URLs are real, remote, and reusable from another process.
Raw CDP skips input humanization
Driving the browser over cdp_endpoint bypasses the pool’s Playwright-path mouse and keyboard humanization. Relevant only if you care about stealth.

Methods

is_connected()

is_connected() -> bool

True while the browser connection is alive. Synchronous.

Returns: bool

Example:

if not browser.is_connected():
    raise RuntimeError("session dropped")

version

version: str

The browser version string. A property, not a method. Do not call it.

Returns: str, e.g. "130.0.6723.31".

Example:

print(browser.version)

contexts()

contexts() -> list[BrowserContext]

All open contexts, straight from the browser. The list is not guaranteed to be non-empty, and contexts()[0] is not guaranteed to be the profile-seeded context. Use the context property (or new_page()) for that. Synchronous.

Returns: list[BrowserContext]

Example:

ctx = browser.context          # the primary, profile-seeded context
page = await ctx.new_page()

new_context()

async new_context(**kwargs) -> BrowserContext

Opens an additional, empty context. Most callers want browser.context instead, because a new context does not carry the session’s profile or proxy timezone.

Parameters:

  • **kwargs: passed through to patchright’s browser.new_context().

Returns: BrowserContext

Example:

ctx = await browser.new_context(locale="en-GB")

new_page()

async new_page() -> Page

Opens a page in the session’s primary context (browser.context), so it carries the attached profile and the proxy timezone.

Returns: Page

Example:

page = await browser.new_page()
await page.goto("https://example.com")

close()

async close() -> None

Closes the browser and releases the session, waiting for confirmation. Idempotent. A browser-close failure is swallowed, because releasing the slot matters more.

Returns: None

Raises: SolariError if the release itself fails.

Example:

async with await solari.launch(stealth=True) as browser:
    page = await browser.new_page()
    await page.goto("https://example.com")
# released automatically at scope exit

Types

Session

A dataclass. Returned by sessions.create().

  • id str: session id.
  • ws_endpoint str: upstream Playwright endpoint, for chromium.connect().
  • cdp_endpoint str: upstream CDP endpoint, for connect_over_cdp().
  • expires_at str: ISO 8601 UTC deadline.
  • storage_state StorageState | None | _Unset: tri-state; see below.
  • proxy ResolvedProxyConfig | None: present only when a managed proxy was requested.
  • user_metadata dict | None: echo of the user_metadata sent at create; None when none was sent.
storage_state is tri-state
UNSET (the sentinel, and the default) means no profile was attached. None means a profile exists but is empty. A dict is the profile’s state. TypeScript encodes this as undefined vs null; Python has only None, hence the sentinel. Test with is UNSET / is None, never truthiness. UNSET is falsy.

SessionList

One page from sessions.list(): sessions list[SessionSummary] and next_cursor str | None. A SessionSummary has id, status, kind, created_at, expires_at and user_metadata, and never the websocket endpoints.

StorageState

An alias for dict[str, Any], a Playwright storage state (cookies + origins/localStorage) passed straight through to patchright. No schema is imposed on it.

ProxyRequest

A dataclass. Only non-None fields are sent, because the gateway distinguishes absent from null.

  • country str | None: ISO-3166-1 alpha-2, lowercase. Server default "us".
  • tier "residential" | "static" | "mobile" | None: server default "residential" (rotating).
  • asn str | None: pin egress to an ASN.
  • session str | None: sticky-session id (any label of 1 to 128 characters; the same label gets the same exit IP).
  • session_duration int | None: sticky lifetime in minutes (1 to 30, default 10). Only with session.
  • state, city str | None: US-only geo narrowing. State takes a name or a two-letter code; one the tier can’t serve returns a 400. See Picking a US state.
from solari_browser import ProxyRequest

browser = await solari.launch(
    stealth=True,
    proxy=ProxyRequest(country="us", tier="mobile", asn="21928"),
)

ResolvedProxyConfig

A coarse confirmation of the proxy the gateway resolved. It carries no server address or credentials (there is no server, username or password): egress is applied server-side, so you never dial the proxy yourself.

  • timezone_id str: timezone matching the egress IP.
  • country str: resolved country.
  • tier str | None: resolved tier.

Profile

  • id str: profile id.
  • name str: human-facing name.
  • raw dict: the full wire object, for forward compatibility.

ReplayUrl

  • url str: presigned download URL.
  • expires_in_seconds int: URL lifetime.
  • content_encoding str: default "gzip".

SaveResult

  • version int: the profile’s new version.
  • size_bytes int: stored size.

SolariError

Extends Exception. Every failure the browser SDK raises.

  • status int | None: HTTP status, when the error came from a response.
  • cause BaseException | None: the underlying error.
  • code str | None: the gateway code. The known values are exported as constants: FEATURE_REQUIRES_PLAN, CONCURRENCY_LIMIT_EXCEEDED, PLAN_LIMIT_EXCEEDED, BROWSER_UNHEALTHY. Unknown codes pass through as plain strings.
from solari_browser import FEATURE_REQUIRES_PLAN, SolariError

try:
    await solari.launch(stealth=True, captcha=True)
except SolariError as e:
    if e.code == FEATURE_REQUIRES_PLAN:
        print("upgrade required:", e.status)

derive_cdp_from_ws()

derive_cdp_from_ws(ws_endpoint: str) -> str

Module-level helper mapping /ws/<id> to /cdp/<id>. The gateway normally returns cdp_endpoint explicitly; this is the fallback for older gateways. Returns its input unchanged if it is not a parseable /ws/ URL.