Browsers
solari-browser: classes Solari and BrowserSession. See the Python SDK hub for install and configuration.
pip install solari-browsersolari-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: Solari(), launch(), close(), request(), sessions.create(), sessions.release(), sessions.release_and_wait(), sessions.get(), sessions.list(), sessions.get_replay_url(), sessions.download_replay(), profiles.create(), profiles.list(), profiles.save(), profiles.delete()BrowserSession: is_connected(), version, contexts(), new_context(), new_page(), close()- Types:
Session,SessionList,StorageState,ProxyRequest,ResolvedProxyConfig,Profile,ReplayUrl,SaveResult,UNSET,SolariError,derive_cdp_from_ws()
Solari
The browser client. Creates sessions and manages profiles.
Properties
sessions_Sessions: session create/release/replay calls.profiles_Profiles: stored browser profile CRUD.base_urlstr: 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,
) -> SolariCreates a client. Does not open any connection.
Parameters:
api_keystr: required; the only positional argument.regionstr:"us-west"only. Ignored whenbase_urlis set.base_urlstr | None: override the resolved region URL.max_attempts,backoff_ms,timeout_msint: 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,
) -> BrowserSessionCreates 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().retriesint: extra re-launch attempts. Default0.probebool | None: probe the browser before returning. Defaults toTruewhenretries > 0.probe_timeout_msint: probe cap. Default2_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()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() -> NoneCloses 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 downrequest()
async request(method: str, path: str, body: Any | None = None) -> httpx.ResponseLow-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:
methodstr: HTTP verb.pathstr: path appended tobase_url, e.g./sessions.bodyAny | 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())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,
) -> SessionAcquires a browser session without connecting. Use it when you want to drive the endpoints yourself; otherwise use launch().
Parameters:
profile_idstr | None: attach a stored profile.recordingbool: record the session.stealthbool: enable the runtime stealth shim.captchabool: managed captcha solving. Requiresstealth.proxystr | ProxyRequest | None: a country code ("us"), aProxyRequest, or the"off"/"smart"sentinels. Requiresstealth.session_timeout_msint | None: end the session earlier than the plan maximum, in milliseconds. Rounded up to whole seconds; the gateway refuses anything under 60 000 (a400, not clamped).Noneor0leaves the plan maximum; a negative, fractional or non-int value raisesSolariErrorbefore any request.keep_alivebool: keep the session when the client disconnects, so it can reconnect. The hold endssession_timeout_msafter the session was created (an hour after creation when unset, never past the plan maximum) or when it is released;expires_atis the hard deadline, not the hold. A host can be replaced by scale-in or repair, which ends the sessions on it.user_metadatadict | None: a JSON object stored with the session and echoed onSession.user_metadata. See sessions.list() for when it comes back.block_heavybool | dict | None: skip heavy files so a proxied session does not pay proxy bandwidth for them.Trueblocks video/audio and images over 100 KB; a dict overlays that withmedia,fontsandimage_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=True and any proxy request are rejected unless stealth=True is also set.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) -> NoneBest-effort release. Failures are logged rather than raised. Use release_and_wait() when you need confirmation.
Parameters:
session_idstr: session id.
Returns: None
Example:
await solari.sessions.release(session.id)sessions.release_and_wait()
async sessions.release_and_wait(session_id: str) -> NoneReleases 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_idstr: 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 latersessions.get()
async sessions.get(session_id: str) -> dictFetches the raw session view from GET /sessions/:id.
Parameters:
session_idstr: 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 confirmedThe 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,
) -> SessionListOne 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:
limitint | None,cursorstr | None: page size, and the previous page’snext_cursor.metadatadict[str, str] | None: keep sessions whoseuser_metadatahas 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 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) -> ReplayUrlReturns a presigned URL for a recorded session’s replay. Requires recording=True at create time.
Parameters:
session_idstr: 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) -> bytesResolves the replay URL and downloads the NDJSON bytes in one call.
Parameters:
session_idstr: 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) -> ProfileCreates an empty profile. Attach it to a session with profile_id to persist cookies and localStorage.
Parameters:
namestr: 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) -> SaveResultOverwrites a profile with the given storage state. Pair it with Playwright’s context.storage_state() to snapshot a logged-in session.
Parameters:
profile_idstr: profile id.storage_stateStorageState: 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) -> NoneDeletes a profile. Idempotent, so a 404 is success.
Parameters:
profile_idstr: 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
sessionSession: the raw session record.idstr: session id.expires_atstr: ISO 8601 UTC deadline; the session auto-releases then.proxyResolvedProxyConfig | None: the resolved timezone, country and tier, when a proxy was requested (no credentials; see ResolvedProxyConfig).ws_endpointstr: upstream Playwright wire-protocol endpoint.cdp_endpointstr: upstream raw-CDP endpoint.contextBrowserContext | None: the session’s primary context, the one carrying the attached profile’s cookies and localStorage and the proxy timezone.rawBrowser: the underlying patchrightBrowser, for APIs this wrapper does not surface.
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.cdp_endpoint bypasses the pool’s Playwright-path mouse and keyboard humanization. Relevant only if you care about stealth.Methods
is_connected()
is_connected() -> boolTrue while the browser connection is alive. Synchronous.
Returns: bool
Example:
if not browser.is_connected():
raise RuntimeError("session dropped")version
version: strThe 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) -> BrowserContextOpens 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’sbrowser.new_context().
Returns: BrowserContext
Example:
ctx = await browser.new_context(locale="en-GB")new_page()
async new_page() -> PageOpens 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() -> NoneCloses 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 exitTypes
Session
A dataclass. Returned by sessions.create().
idstr: session id.ws_endpointstr: upstream Playwright endpoint, forchromium.connect().cdp_endpointstr: upstream CDP endpoint, forconnect_over_cdp().expires_atstr: ISO 8601 UTC deadline.storage_stateStorageState | None | _Unset: tri-state; see below.proxyResolvedProxyConfig | None: present only when a managed proxy was requested.user_metadatadict | None: echo of theuser_metadatasent at create;Nonewhen none was sent.
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.
countrystr | None: ISO-3166-1 alpha-2, lowercase. Server default"us".tier"residential" | "static" | "mobile" | None: server default"residential"(rotating).asnstr | None: pin egress to an ASN.sessionstr | None: sticky-session id (any label of 1 to 128 characters; the same label gets the same exit IP).session_durationint | None: sticky lifetime in minutes (1 to 30, default 10). Only withsession.state,citystr | 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_idstr: timezone matching the egress IP.countrystr: resolved country.tierstr | None: resolved tier.
Profile
idstr: profile id.namestr: human-facing name.rawdict: the full wire object, for forward compatibility.
ReplayUrl
urlstr: presigned download URL.expires_in_secondsint: URL lifetime.content_encodingstr: default"gzip".
SaveResult
versionint: the profile’s new version.size_bytesint: stored size.
SolariError
Extends Exception. Every failure the browser SDK raises.
statusint | None: HTTP status, when the error came from a response.causeBaseException | None: the underlying error.codestr | 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) -> strModule-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.

